我在android中遇到了NullPointerException,我的代码出了什么问题?

时间:2015-05-12 09:24:09

标签: android multithreading nullpointerexception

我是一名java / android初学者。尝试运行以下应用程序时,我收到NullPointerException。我想使用getScanResults()获取访问点,但是当我不使用线程时我得到null,所以我使用它。有人可以告诉我我的代码有什么问题吗?先谢谢!

public class MainActivity extends Activity implements View.OnClickListener {

Button btn;
WifiManager wifi;
final String TAG = "connectToWifi";
String[] wifis;
ListView list;
WifiScanReceiver wifiReciever;

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

    btn = (Button) findViewById(R.id.button_id);
    btn.setOnClickListener(this);

    if (wifi.isWifiEnabled()) {

        btn.setText(R.string.on_label);
    } else {
        btn.setText(R.string.off_label);
    }
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            wifi = (WifiManager) getSystemService(WIFI_SERVICE);

            list = (ListView) findViewById(R.id.listView1);
            wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wifiReciever = new WifiScanReceiver();
            wifi.startScan();
        }

    }).start();

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if (wifi.isWifiEnabled()) {

        wifi.setWifiEnabled(false);
        btn.setText(R.string.off_label);
    } else {
        Log.d(TAG, String.valueOf(wifi.getWifiState()));
        wifi.startScan();
        Log.d(TAG, String.valueOf(wifi.getScanResults()));
        wifi.getScanResults();
        wifi.setWifiEnabled(true);
        Log.d(TAG, String.valueOf(wifi.getWifiState()));
        btn.setText(R.string.on_label);
        Log.d(TAG, String.valueOf(wifi.getWifiState()));

    }
}

class WifiScanReceiver extends BroadcastReceiver {
    public void onReceive(Context c, Intent intent) {
        try {
            List<ScanResult> wifiScanList = wifi.getScanResults();
            wifis = new String[wifiScanList.size()];
            for (int i = 0; i < wifiScanList.size(); i++) {
                wifis[i] = ((wifiScanList.get(i)).toString());
            }
        } finally {
            list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
                    android.R.layout.simple_list_item_1, wifis));
        }

    }
}

}

1 个答案:

答案 0 :(得分:1)

在使用之前,您没有初始化wifi

首次使用wifi之前wifi = (WifiManager) getSystemService(WIFI_SERVICE);,即wifi.isWifiEnabled()

另外,要注意logcat。它会告诉你它发生的确切原因。 类似的东西:

11-14 21:30:52.517: E/AndroidRuntime(18929): Caused by: java.lang.NullPointerException
11-14 21:30:52.517: E/AndroidRuntime(18929): at com.kay.MainActivity.onCreate(MainActivity.java:88)