-3

So I am trying to create an android app to show some simple battery information. And now I want to take that info and plot a graph inside the app. I have the following codes:

public class MainActivity extends ActionBarActivity {
private TextView level,voltage, status1,temp,health1,tech,sour,amp;
Thread myThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        level=(TextView)findViewById(R.id.level);
        voltage=(TextView)findViewById(R.id.volt);
        status1=(TextView)findViewById(R.id.stat);
        temp=(TextView)findViewById(R.id.temp);
        health1=(TextView)findViewById(R.id.healt);
        tech=(TextView)findViewById(R.id.tech);
        sour=(TextView)findViewById(R.id.source);
        Button b = (Button) findViewById(R.id.ex);
        Button g = (Button) findViewById(R.id.graphButton);
        amp=(TextView)findViewById(R.id.current);
        b.setOnClickListener(new View.OnClickListener(){
             public void onClick(View v) {
                    // TODO Auto-generated method stub
                    finish();
                  }
        });

        g.setOnClickListener(new View.OnClickListener(){
             public void onClick(View v) {

       //how can i jump to DynamicGraphActivity

             }
        });

        this.registerReceiver(this.myBatteryReceiver,
                 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));


    }

    private BroadcastReceiver myBatteryReceiver
       = new BroadcastReceiver(){

     @SuppressLint("InlinedApi")
    @Override
     public void onReceive(Context arg0, Intent arg1) {
      // TODO Auto-generated method stub

      if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){

          int lv = arg1.getIntExtra("level", 0);
       level.setText("Level: "
         + String.valueOf(lv) + "%");

       voltage.setText("Voltage: "
                 + String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
               temp.setText("Temperature: "
                 + String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
               tech.setText("Technology: " + arg1.getStringExtra("technology"));

               int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
               String strStatus;
               if (status == BatteryManager.BATTERY_STATUS_CHARGING){
                strStatus = "Charging";
               } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
                strStatus = "Dis-charging";
               } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
                strStatus = "Not charging";
               } else if (status == BatteryManager.BATTERY_STATUS_FULL){
                strStatus = "Full";
               } else {
                strStatus = "Unknown";
               }
               status1.setText("Status: " + strStatus);

               //int source=arg1.getIntExtra("source", BatteryManager.BATTERY_STATUS_UNKNOWN);
               if(Build.VERSION.SDK_INT >= 21){
             BatteryManager battery = (BatteryManager)getSystemService(Context.BATTERY_SERVICE);
             int current=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
             int currentAvg=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
             int energy=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);
             int capacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
             int bCapacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
             String string1 = "Current: "+ current*1000+" uA"+"\n";
             string1+="Average Current: "+currentAvg+" uA"+"\n";
             string1+="Remaining energy: "+energy+" nWh"+"\n";
             string1+="Capacity: "+capacity+" uAh"+"\n\n";

             amp.setText(string1);
               }


               int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
               String strHealth;
               if (health == BatteryManager.BATTERY_HEALTH_GOOD){
                strHealth = "Good";
               } else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
                strHealth = "Over Heat";
               } else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
                strHealth = "Dead";
               } else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
                strHealth = "Over Voltage";
               } else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
                strHealth = "Unspecified Failure";
               } else{
                strHealth = "Unknown";
               }
               health1.setText("Health: " + strHealth);

              }
             }

               };



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

2nd Activity or DynamicGraphActivity:

public class DynamicGraphActivity extends Activity {

    private static GraphicalView view;
    private LineGraph line = new LineGraph();
    private static Thread thread;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        thread = new Thread() {
            public void run()
            {
                for (int i = 0; i < 15; i++) 
                {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Point p = MockData.getDataFromReceiver(i); // We got new data!
                    line.addNewPoints(p); // Add it to our graph
                    view.repaint();
                }
            }
        };
        thread.start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        view = line.getView(this);
        setContentView(view);
    }

}

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.Context;
import android.graphics.Color;

public class LineGraph {

    private GraphicalView view;

    private TimeSeries dataset = new TimeSeries("Rain Fall"); 
    private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();

    private XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
    private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph

    public LineGraph()
    {
        // Add single dataset to multiple dataset
        mDataset.addSeries(dataset);

        // Customization time for line 1!
        renderer.setColor(Color.WHITE);
        renderer.setPointStyle(PointStyle.SQUARE);
        renderer.setFillPoints(true);

        // Enable Zoom
        mRenderer.setZoomButtonsVisible(true);
        mRenderer.setXTitle("Day #");
        mRenderer.setYTitle("CM in Rainfall");

        // Add single renderer to multiple renderer
        mRenderer.addSeriesRenderer(renderer);  
    }

    public GraphicalView getView(Context context) 
    {
        view =  ChartFactory.getLineChartView(context, mDataset, mRenderer);
        return view;
    }

    public void addNewPoints(Point p)
    {
        dataset.add(p.getX(), p.getY());
    }

}

import java.util.Random;

public class MockData {

    // x is the day number, 0, 1, 2, 3
    public static Point getDataFromReceiver(int x)
    {
        return new Point(x, generateRandomData());
    }

    private static int generateRandomData()
    {
        Random random = new Random();
        return random.nextInt(40);
    }
}

public class Point {

    private int x;
    private int y;

    public Point( int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

}

Now inside the button g, I want to call DynamicGraphActivity class so that it calls the class and plots a graph using some random values. but its not working. When i click on the button, it doesnt do anything. How can I fix this?

And my another question is, how can I plot the battery info such as voltage, charge or discharge over time using these codes/ Any help would be greatly appreciated. Thank you

Talha Q
  • 4,301
  • 4
  • 27
  • 39
Tanvir
  • 1
  • 2
  • 5
    Possible duplicate of [How to start new activity on button click](http://stackoverflow.com/questions/4186021/how-to-start-new-activity-on-button-click) – Jas Feb 22 '16 at 06:23
  • http://stackoverflow.com/questions/35171876/android-login-app-display-the-email/35171974#35171974 – kgandroid Feb 22 '16 at 06:30

3 Answers3

1
Intent 2ndActivity = new Intent(this, blabla.class);
startActivity(2ndActivity);

For the button and for the extra value you can use Bundle,Parcel or just use putExtra.

And for the battery info, Read from google developer

Nils
  • 647
  • 6
  • 16
Alamin Aji
  • 71
  • 1
  • 5
1

Well there is a difference between any class or an activity. Activity have a visual layout maps to it.Check this link for more info.

Inside your g button click listener add this code.

g.setOnClickListener(new View.OnClickListener(){
         public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
    startActivity(intent);
      }
    });

Also you need to add the other activity in the AndroidManifest.xml as well under application tag.(You already have activity tag inside application tag if you create a new app.But you don't need any intent filters for newer activity)

<activity
    android:name=".DynamicGraphActivity"
 />

I noticed one more thing you are using same layout(main.xml) for both activities. Create another layout in layouts folder and map it to the DynamicGraphActivity. Lets say you create second.xml. So your DynamicGraphActivity oncreate() have:

setContentView(R.layout.second);
Talha Q
  • 4,301
  • 4
  • 27
  • 39
0

In your button click put this code

Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
startActivity(intent);

and define this activity in your AndroidManifest.xml

<activity
        android:name=".DynamicGraphActivity"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />

and for Battery information you can refer this links... http://developer.android.com/reference/android/os/BatteryManager.html http://mobiledevtuts.com/android/android-sdk-get-device-battery-information/ Get battery level and state in Android

Community
  • 1
  • 1
Nils
  • 647
  • 6
  • 16