com.powermonitor.epitech.ViewModules.java Source code

Java tutorial

Introduction

Here is the source code for com.powermonitor.epitech.ViewModules.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.powermonitor.epitech;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.powermonitor.epitech.Charts.LineChartFragment;
import com.powermonitor.epitech.Dialogs.ErrorDialog;
import com.powermonitor.epitech.Models.Module;
import com.powermonitor.epitech.Utils.Communication;
import com.powermonitor.epitech.Utils.DatePickerFragment;
import com.powermonitor.epitech.Utils.RequestHandler;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author jourda_c
 */

//TODO: Check session singleton. Remove it and add to application class
//TODO: Check list view is null
public class ViewModules extends FragmentActivity {

    private ListView list;
    private List<Module> dataList;
    private ModuleListAdapter adapter;
    private ChartViewAdapter chartViewAdapter;
    private ViewPager chartViewPager;
    private Button validate;
    private SparseArray<String> modNames;
    private EditText dateFrom;
    private EditText dateTo;
    private JSONArray modulesID;

    @Override
    public void onCreate(Bundle saveInstance) {
        super.onCreate(saveInstance);
        setContentView(R.layout.viewmodules);
        modNames = new SparseArray<String>();
        this.list = (ListView) findViewById(R.id.ViewModules_modulesListView);
        this.dataList = new ArrayList<Module>();

        try {
            modulesID = new JSONArray(getIntent().getStringExtra("ModulesID"));
            for (int i = 0; i < modulesID.length(); i++) {
                JSONObject obj = modulesID.getJSONObject(i);
                modNames.put(obj.getInt("id"), obj.getString("name"));
                this.dataList.add(new Module(obj.getInt("id"), obj.getString("name"), null, true));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            modulesID = new JSONArray();
        }

        // List view
        //        Communication.INSTANCE.getModulesList(new RequestHandler(this) {
        //            @Override
        //            public void onResult(JSONObject result, JSONObject params) {
        //                JSONArray modList;
        //                try {
        //                    modList = result.getJSONArray("modules");
        //                    for (int i = 0; i < modList.length(); i++) {
        //                        JSONObject obj = modList.getJSONObject(i);
        //                        Module mod = new Module(obj.getInt("id"), obj.getString("name"), null, true);
        //                        ViewModules.this.modNames.append(mod.id, mod.getName());
        //                        ViewModules.this.dataList.add(mod);
        //                    }
        //                    adapter.notifyDataSetChanged();
        //                } catch (JSONException ex) {
        //                    Logger.getLogger(ViewModules.class.getName()).log(Level.SEVERE, null, ex);
        //                }
        //            }
        //        });
        //this.dataList.add(new Module(0));
        this.adapter = new ModuleListAdapter(this, R.layout.modulerow_min, this.dataList);
        this.list.setAdapter(this.adapter);

        // Date filter
        dateFrom = (EditText) findViewById(R.id.ViewModules_dateFrom);
        dateTo = (EditText) findViewById(R.id.ViewModules_dateTo);
        dateFrom.setOnClickListener(new OnDateClickListener());
        dateTo.setOnClickListener(new OnDateClickListener());

        // Chart
        this.chartViewAdapter = new ChartViewAdapter(getSupportFragmentManager());
        this.chartViewPager = (ViewPager) this.findViewById(R.id.ViewModules_pager);
        this.chartViewPager.setAdapter(this.chartViewAdapter);
        this.chartViewPager.setOffscreenPageLimit(2);

        // Button Validate
        this.validate = (Button) findViewById(R.id.ViewModules_bValidate);
        this.validate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                LineChartFragment chart = (LineChartFragment) ViewModules.this.chartViewAdapter.getFragment(0);
                LineChartFragment chart2 = (LineChartFragment) ViewModules.this.chartViewAdapter.getFragment(1);
                LineChartFragment chart3 = (LineChartFragment) ViewModules.this.chartViewAdapter.getFragment(2);
                if (chart != null)
                    chart.empty();
                if (chart2 != null)
                    chart2.empty();
                if (chart3 != null)
                    chart3.empty();
                if (ViewModules.this.dateFrom.getTag() == null || ViewModules.this.dateTo.getTag() == null) {
                    ErrorDialog eDialog = new ErrorDialog(ViewModules.this,
                            "Veuillez entrer une date de dbut et une date de fin", null);
                    eDialog.show();
                    return;
                }
                //                for (int i = 0; i < ViewModules.this.adapter.getCount(); i++) {
                //                    CheckBox cb = (CheckBox) list.getChildAt(i).findViewById(R.id.name);
                //                    if (cb.isChecked()) {
                //                        Communication.INSTANCE.getModuleConsoData(ViewModules.this.dataList.get(i).id,
                //                                ((Long) ViewModules.this.dateFrom.getTag()).intValue(), ((Long) ViewModules.this.dateTo.getTag()).intValue(), 2,
                //                                ViewModules.this.onConsoDataFetched);
                //                    }
                //                }

                for (int id = 0; id < modulesID.length(); id++) {
                    try {
                        int moduleID = modulesID.getJSONObject(id).getInt("id");
                        Communication.INSTANCE.getModuleConsoData(moduleID,
                                ((Long) ViewModules.this.dateFrom.getTag()).intValue(),
                                ((Long) ViewModules.this.dateTo.getTag()).intValue(), 1,
                                ViewModules.this.onConsoDataFetchedW);
                        Communication.INSTANCE.getModuleConsoData(moduleID,
                                ((Long) ViewModules.this.dateFrom.getTag()).intValue(),
                                ((Long) ViewModules.this.dateTo.getTag()).intValue(), 2,
                                ViewModules.this.onConsoDataFetchedA);
                        Communication.INSTANCE.getModuleConsoData(moduleID,
                                ((Long) ViewModules.this.dateFrom.getTag()).intValue(),
                                ((Long) ViewModules.this.dateTo.getTag()).intValue(), 3,
                                ViewModules.this.onConsoDataFetchedV);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                //                Communication.INSTANCE.getModuleConsoData(ViewModules.this.dataList.get(2).id,
                //                        ((Long) ViewModules.this.dateFrom.getTag()).intValue(), ((Long) ViewModules.this.dateTo.getTag()).intValue(), 2,
                //                        ViewModules.this.onConsoDataFetched);
            }
        });
    }

    private final RequestHandler onConsoDataFetchedV = new RequestHandler(this) {
        @Override
        public void onResult(JSONObject result, JSONObject params) {
            System.out.println(result);
            loadChartData(3, result);
        }
    };

    private final RequestHandler onConsoDataFetchedA = new RequestHandler(this) {
        @Override
        public void onResult(JSONObject result, JSONObject params) {
            System.out.println(result);
            loadChartData(2, result);
        }
    };

    private final RequestHandler onConsoDataFetchedW = new RequestHandler(this) {
        @Override
        public void onResult(JSONObject result, JSONObject params) {
            System.out.println(result);
            loadChartData(1, result);
        }
    };

    private void loadChartData(int unit, JSONObject result) {
        try {
            JSONArray arr = result.getJSONArray("infos");
            LineChartFragment chart = (LineChartFragment) ViewModules.this.chartViewAdapter.getFragment(unit - 1);
            if (chart != null) {
                //chart.empty();
                for (int i = 0; i < arr.length(); i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    chart.addData(ViewModules.this.modNames.get(obj.getInt("moduleId")), obj.getInt("time"),
                            (float) obj.getDouble("value"));
                }
            }
        } catch (JSONException ex) {
            Logger.getLogger(ViewModules.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public class OnDateClickListener implements View.OnClickListener {

        public void onClick(View v) {
            final EditText clickedEdit = (EditText) v;
            DialogFragment dateFragment = new DatePickerFragment() {
                @Override
                public void onDateSet(DatePicker view, int y, int m, int d) {
                    clickedEdit.setText(String.format("%d/%d/%d", d, m + 1, y));
                    Date da = new Date(y - 1900, m, d);
                    clickedEdit.setTag(da.getTime() / 1000);
                }
            };
            dateFragment.show(getSupportFragmentManager(), "datePicker");
        }

    }

    private class ChartViewAdapter extends FragmentPagerAdapter {

        private static final int ITEM_COUNT = 3;
        private LineChartFragment fg1;
        private LineChartFragment fg2;
        private LineChartFragment fg3;

        public ChartViewAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            switch (i) {
            case 0:
                return new LineChartFragment();
            case 1:
                return new LineChartFragment();
            default:
                return new LineChartFragment();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
            // save the appropriate reference depending on position
            switch (position) {
            case 0:
                fg1 = (LineChartFragment) createdFragment;
                fg1.setTitle("Watts (W)");
                break;
            case 1:
                fg2 = (LineChartFragment) createdFragment;
                fg2.setTitle("Ampres (A)");
                break;
            case 2:
                fg3 = (LineChartFragment) createdFragment;
                fg3.setTitle("Volts (V)");
                break;
            }
            return createdFragment;
        }

        public LineChartFragment getFragment(int id) {
            switch (id) {
            case 0:
                return fg1;
            case 1:
                return fg2;
            case 2:
                return fg3;
            default:
                return fg1;
            }
        }

        @Override
        public int getCount() {
            return ITEM_COUNT;
        }

    }

    private class ModuleListAdapter extends ArrayAdapter<Module> {

        public ModuleListAdapter(Context context, int viewResourceId, List<Module> objects) {
            super(context, viewResourceId, objects);
        }

        @Override
        public View getView(int pos, View convertView, ViewGroup parent) {
            View v = convertView;
            // Check if view had already been inflated
            if (v == null) {
                LayoutInflater vi = LayoutInflater.from(getContext());
                v = vi.inflate(R.layout.modulerow_min, null);
                ViewHolder vh = new ViewHolder();
                vh.name = (TextView) v.findViewById(R.id.name);
                v.setTag(vh);
            }
            // Set view data
            Module item = getItem(pos);
            if (item != null) {
                ViewHolder vh = (ViewHolder) v.getTag();
                vh.name.setText(item.getName());
            }
            return v;
        }

        private class ViewHolder {

            public TextView name;
        }

    }

}