I am trying to change the text of TextView when the battery is at a defined level, but when that happened I got an error instead, the error is
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) } in famium.fokus.fhg.de.monitoringthebatterylevelandchargingstate.MainActivity$1@4139cca8
and here my code, I commented before the lines taht causes the error.
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
/*
BatteryManager
The BatteryManager class contains strings and constants used for values in the
ACTION_BATTERY_CHANGED Intent, and provides a method for querying battery
and charging properties.
*/
/*
public static final String EXTRA_SCALE
Extra for ACTION_BATTERY_CHANGED: integer containing the maximum battery level.
Constant Value: "scale"
*/
// Get the battery scale
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
// Display the battery scale in TextView
mTextViewInfo.setText("Battery Scale : " + scale);
/*
public static final String EXTRA_LEVEL
Extra for ACTION_BATTERY_CHANGED: integer field containing the current battery
level, from 0 to EXTRA_SCALE.
Constant Value: "level"
*/
// get the battery level
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
// Display the battery level in TextView
mTextViewInfo.setText(mTextViewInfo.getText() + "\nBattery Level : " + level);
// Calculate the battery charged percentage
float percentage = level/ (float) scale;
// Update the progress bar to display current battery charged percentage
mProgressStatus = (int)((percentage)*100);
// Show the battery charged percentage text inside progress bar
mTextViewPercentage.setText("" + mProgressStatus + "%");
// Show the battery charged percentage in TextView
mTextViewInfo.setText(mTextViewInfo.getText() +
"\nPercentage : "+ mProgressStatus + "%");
// Display the battery charged percentage in progress bar
mProgressBar.setProgress(mProgressStatus);
String action = intent.getAction();
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level1 = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale1 = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level1*100)/scale1;
// here the lines that causes the error
if (percent >= 97) {
_textView2.setText(percent);
}
}
}
};
I tried to follow this post https://stackoverflow.com/a/10910024/9308420 but I do not know what is wrong.
I figured it out after reading this post
https://stackoverflow.com/a/23791368/9308420
so, instead of
_textView2.setText(percent);
Changed to
_textView2.setText("" + percent);