简体   繁体   中英

Error receiving broadcast intent using BatteryManager

I am getting Error in receiving broadcast intent i am using BatteryManager for it. I have no clue why I am getting this error.

Someone please help. thanks in advance

Let me know if you need more code.

Here is the error:

> Error receiving broadcast Intent {
> act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras)
> } in com.example.android.login.MainActivity$1@260e12dc
>             at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:933)
>             at android.os.Handler.handleCallback(Handler.java:739)
>             at android.os.Handler.dispatchMessage(Handler.java:95)
>             at android.os.Looper.loop(Looper.java:145)
>             at android.app.ActivityThread.main(ActivityThread.java:5972)
>             at java.lang.reflect.Method.invoke(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:372)
>             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
>             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
>      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.TextView.setText(java.lang.CharSequence)' on a null
> object reference
>             at com.example.android.login.MainActivity$1.onReceive(MainActivity.java:37)
>             at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:923)
>             at android.os.Handler.handleCallback(Handler.java:739)
>             at android.os.Handler.dispatchMessage(Handler.java:95)
>             at android.os.Looper.loop(Looper.java:145)
>             at android.app.ActivityThread.main(ActivityThread.java:5972)
>             at java.lang.reflect.Method.invoke(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:372)

Activity Class

package com.example.android.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.LogOutCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;

import com.parse.ParseException;


public class MainActivity extends ActionBarActivity {
    private TextView batteryTxt;
    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context ctxt, Intent intent) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            batteryTxt.setText(String.valueOf(level) + "%");
        }
    };
    private Toolbar toolbar;
    public Button logoutButton;
    public int level;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        batteryTxt = (TextView) this.findViewById(R.id.percent);
        this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_appbar);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);

        logoutButton = (Button) findViewById(R.id.logoutButton);
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
             public void onClick(View v) {
                // Set up a progress dialog
                final ProgressDialog logout = new ProgressDialog(MainActivity.this);
                logout.setTitle("Please wait.");
                logout.setMessage("Logging out.  Please wait.");
                logout.show();
                ParseUser.logOutInBackground(new LogOutCallback() {

                    public void done(ParseException e) {
                        logout.dismiss();
                        if (e == null) {
                            Intent logoutDone = new Intent(MainActivity.this, DispatchActivity.class);
                            startActivity(logoutDone);
                        } else {
                            Toast.makeText(MainActivity.this, "Logout Unsuccessful", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

Based on your stack trace, it looks like it is throwing a NullPointerException because the batteryTxt field is null at the time that the intent was received. As Daniel Nugent pointed out, this is because the receiver is registered before calling setContentView() . However, it looks like you're also never unregistering your receiver, so I suggest moving the code to register the receiver to the onResume() method, and adding an unregister call in the onPause() method to prevent this same NullPointerException from occurring when your activity is stopped.

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

@Override
protected void onPause() {
    unregisterReceiver(mBatInfoReceiver);
    super.onPause();
}

do this

batteryTxt = (TextView) this.findViewById(R.id.percent);

after this

setContentView(R.layout.activity_main_appbar);

always read this section in your error log

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 

Write the code like that

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_appbar);
    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    batteryTxt = (TextView) this.findViewById(R.id.percent);
    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM