得到错误java.lang.NullPointerException

时间:2012-11-12 14:38:54

标签: android nullpointerexception

我写了一段代码,通过网站获取一些信息并将其显示在ListView中。我无法配置为什么我收到强制关闭错误。我将日志猫和代码粘贴在一起。请帮我找到并解决错误

11-07 21:43:14.729: E/AndroidRuntime(2799): FATAL EXCEPTION: main
11-07 21:43:14.729: E/AndroidRuntime(2799): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.air.test/com.air.test.MainActivity}: java.lang.NullPointerException
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.os.Looper.loop(Looper.java:130)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.main(ActivityThread.java:3683)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.lang.reflect.Method.invokeNative(Native Method)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.lang.reflect.Method.invoke(Method.java:507)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at dalvik.system.NativeStart.main(Native Method)
11-07 21:43:14.729: E/AndroidRuntime(2799): Caused by: java.lang.NullPointerException
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.util.Arrays$ArrayList.<init>(Arrays.java:47)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.util.Arrays.asList(Arrays.java:169)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:138)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at com.air.test.MainActivity.onCreate(MainActivity.java:59)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
11-07 21:43:14.729: E/AndroidRuntime(2799):     ... 11 more

代码

private Spinner spinner1;
private ProgressDialog pd;
private StringBuilder response;
private ListView listView;
private String[] values;
private ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.mylist);
    spinner1 = (Spinner) findViewById(R.id.spinnerCategory);
    spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> av, View view, int id,
                long ids) {
            new sendMessageAsync().execute();
        }

        public void onNothingSelected(AdapterView<?> av) {
        }
    });

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, values);

    listView.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private class sendMessageAsync extends AsyncTask<Void, Void, String> {

    @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(MainActivity.this, null, "Loading...",
                true, true);
    }

    @Override
    protected void onCancelled() {
        Toast.makeText(getApplicationContext(),
                "Message Sending Cancelled", Toast.LENGTH_LONG).show();
    }

    @Override
    protected String doInBackground(Void... arg0) {
        try {
            doInBg();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        pd.dismiss();
    }
}

public void doInBg() {
    try {
        final String msgURL = "http://example.com/message?category="
                + String.valueOf(spinner1.getSelectedItem().toString()
                        .replace(" ", "%20"));
        URLConnection connection = new URL(msgURL).openConnection();
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        InputStream responseStream = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                responseStream));
        response = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        values = String.valueOf(response).split("<br/>");
        adapter.notifyDataSetChanged();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:4)

运行此行时,values为空。

adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, values);

要解决此问题,请在该行之前初始化values

values = new String[0];

或者,如果您希望它包含某些内容:

values = new String[]{ "Value 1", "Value 2" };

修改

检查了AsyncTask实现后,我会做什么:

我首先要使用以下代码初始化值:

adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>());

其次,我会将你的values String数组作为类属性删除。 (删除行private String[] values;

第三,我会将AsyncTask更改为<Void, String, Void>

第四,假设这段代码能给你正确的结果:

values = String.valueOf(response).split("<br/>");

在这里,我将用以下代码替换该行:

String[] values = String.valueOf(response).split("<br/>");
for (String str : values) publishProgress(str);

然后,在你的AsyncTask中,有这个方法:

@Override
protected void onProgressUpdate(String... values) {
    adapter.add(values[0]);
}

我希望这适合你。

答案 1 :(得分:3)

在尝试创建适配器之前,需要设置String数组values

此行会失败,因为valuesnull

adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, values);