Jb11281992 Jb11281992 - 6 months ago 24
Android Question

Why is my method invocation force closing my application?

So I am attempting to gather battery info from my android device. My two methods: getPhoneTemp and getBatteryLevel both work flawlessly, but when I invoke my new method getMah, the application force closes upon launch. I have no idea what is causing this issue.

Code:

public class MainActivity extends AppCompatActivity {

public float getBatteryLevel() {
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

// Error checking that probably isn't needed but I added just in case.
if(level == -1 || scale == -1) {
return 50.0f;
}

return ((float)level / (float)scale) * 100.0f;
}

//Gathers ambient temperature of internal hardware
public float getPhoneTemp() {

float temp = Sensor.TYPE_AMBIENT_TEMPERATURE;
return temp;
}

public int getMah() {
BatteryManager mBatteryManager = (BatteryManager)MainActivity.this.getSystemService(Context.BATTERY_SERVICE);
int energy = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);

return energy;

}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


//Handler Object for interval execution
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {

public void run() {

TextView batLevel = (TextView) findViewById(R.id.level1);
TextView textAMBIENT_TEMPERATURE_read = (TextView)findViewById(R.id.textAMBIENT_TEMPERATURE_read);
TextView mahReadOut = (TextView)findViewById(R.id.mahRead);

int mAh = getMah();
mahReadOut.setText(mAh);


float phoneTemp = getPhoneTemp();
char tmp = 0x00B0;
String tempRead = (int) phoneTemp + "" + tmp + "C";

textAMBIENT_TEMPERATURE_read.setText(tempRead);


float level = getBatteryLevel();
String levelText = Float.toString(level);
String batteryLevel = (int) level + "%";

batLevel.setText(batteryLevel);

if ((int) level <= 100 && (int) level >= 95) {
batLevel.setBackgroundResource(R.drawable.batteryfull);

}

if ((int) level < 95 && (int) level >= 75) {
batLevel.setBackgroundResource(R.drawable.battery80);

}

if ((int) level < 75 && (int) level >= 60) {
batLevel.setBackgroundResource(R.drawable.batt65);

}

handler.postDelayed(this, 10000); //executes consistently at 10 second intervals
}
}, 500); //1/2 second to execution




}
}

Answer

I ran the correction I posted in the comments & it did fix it. So here:

mahReadOut.setText(mAh);

You're sending an int where you should send a String. The int comes from int mAh = getMah(); Do instead:

mahReadOut.setText(Integer.toString(mAh));

Comments