Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get NullPointerException when calling getSystemService()

My problem is, that in onCreate() method of my MainActivity I am creating new Thread object to which I want to pass reference to this activity, and than in that thread use it to call getSystemService(). But in the end, when I start the app it crashes and I get NullPointerException.

I have already found that problem could be that I am passing reference to activity befor super.onCreate(), but in my code super.onCreate() is performed before passing the reference.

This is my MainActivity's onCreate() method

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Instance which contains thread for obtaining wifi info
    final WifiInfoThread wifi_info = new WifiInfoThread(this);
....
}

And this is Thread class in which I am trying to get reference to system service

public class WifiInfoThread extends Thread {
// Constructor for passing context to this class to be able to access xml resources
Activity activity;
WifiInfoThread(Activity current) {
    activity = current;
}

// Flag for stopping thread
boolean flag = false;
// Obtain service and WifiManager object
WifiManager current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);

// Runnable object passed to UIThread
Runnable uirunnable = new Runnable() {
    @Override
    public void run() {
        // Get current wifi status
        WifiInfo wifi_info = current_wifi.getConnectionInfo();

        // Things with showing it on screen
        TextView tv_output = (TextView) activity.findViewById(R.id.tv_output);
        String info = "SSID: " + wifi_info.getSSID();
        info += "\nSpeed: " + wifi_info.getLinkSpeed() + " Mbps";
        tv_output.setText(info);
    }
};

public void run() {
    flag = true;

    for(; flag; ) {
        activity.runOnUiThread(uirunnable);
        try {
            this.sleep(500);
        }
        catch(InterruptedException e) {}
    }
}

}


1 Answers

You are using activity.getSystemService before initializing activity. To get ride of this, move below line into Constructor

// Obtain service and WifiManager object
WifiManager current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);

Like

WifiManager current_wifi;
WifiInfoThread(Activity current) {
    activity = current;
    current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
}
like image 93
Pankaj Kumar Avatar answered Mar 18 '26 23:03

Pankaj Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!