如何解决NullPointerException

时间:2014-10-02 14:42:13

标签: java android android-asynctask nullpointerexception

我有一个活动,显示列表视图中的地点类别。当我尝试点击列表项时,应用程序因NullPointerException而崩溃。以下是活动

public class ListOfPlacesActivity extends Activity {

    ListView listView;
    public String tag_name;
    public List<NameAddress> nameAddressList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_of_places);

        listView = (ListView) findViewById(R.id.list_of_places);

        Intent intent = getIntent();
        if(intent!= null)
        {
            tag_name = intent.getStringExtra("CategoryName");
        }

        nameAddressList = null;
        try
        {
            final XMLDOMParserHandler parser = new XMLDOMParserHandler(tag_name.toLowerCase(), this);
            if(isConnectivityOn(this)){
                BackgroundRunner.doInBackground(new BackgroundRunner.DoInBackground() {
                    @Override
                    public void execute() {
                        try {
                            URL myURL = new URL("http://somewebsite.com/admin/data.xml");
                            URLConnection ucon = myURL.openConnection();
                            final InputStream is = ucon.getInputStream();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    nameAddressList = parser.parseXML(is);
                                }
                            });
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } else {
                nameAddressList = parser.parseXML(getAssets().open("data.xml"));
            }
            ListOfPlacesAdapter listOfPlacesAdapter = new ListOfPlacesAdapter(this, nameAddressList);
            listView.setAdapter(listOfPlacesAdapter);
            listView.setItemsCanFocus(true);

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public boolean isConnectivityOn(Context context) {
        boolean resCode = false;

        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            resCode = cm.getActiveNetworkInfo().isConnectedOrConnecting();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resCode;
    }
}

从错误中我知道我的Apdater得到&#34; nameAddressList&#34;为null,因为doInBakground中的代码未执行。所以它抛出了NullPointerException。我可以知道如何解决这个问题

以下是我得到的错误:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{asm.sdsuhood.app/asm.sdsuhood.app.places.ListOfPlacesActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
        at android.app.ActivityThread.access$900(ActivityThread.java:161)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at asm.sdsuhood.app.places.ListOfPlacesAdapter.getCount(ListOfPlacesAdapter.java:43)
        at android.widget.ListView.setAdapter(ListView.java:486)
        at asm.sdsuhood.app.places.ListOfPlacesActivity.onCreate(ListOfPlacesActivity.java:81)
        at android.app.Activity.performCreate(Activity.java:5426)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

让你的声明和onCreate方法是这样的,所以当你找到get extras然后调用异步类(基本上是在另一个线程上进行长时间操作)。

ListView listView;
public String tag_name;
public List<NameAddress> nameAddressList;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_of_places);

    context = YourActivityName.this;

    listView = (ListView) findViewById(R.id.list_of_places);

    Intent intent = getIntent();
    if (intent != null) {
        tag_name = intent.getStringExtra("CategoryName");
        new ListAsync().execute();
    }
}

现在,新的ListAsync()。execute();此语句将调用最终调用Web服务并将数据绑定到List的异步类,此操作必须在另一个线程上执行。

完成该长任务后,异步类方法onPostExecute执行,我们会相应地进行更改,以反映在unser接口上。

    private class ListAsync extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        Log.i("test", "Running on ui thread");
    }

    @Override
    protected Void doInBackground(Void... params) {
        Log.i("test", "Doding long operation on another thread");
        final XMLDOMParserHandler parser = new XMLDOMParserHandler(
                tag_name.toLowerCase(), this);
        if (isConnectivityOn(context)) {
            try {
                URL myURL = new URL("http://somewebsite.com/admin/data.xml");
                URLConnection ucon = myURL.openConnection();
                final InputStream is = ucon.getInputStream();
                nameAddressList = parser.parseXML(is);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            nameAddressList = parser.parseXML(getAssets().open("data.xml"));
        }
    }

    @Override
    protected void onPostExecute(Void result) {
        Log.i("tag", "getting back to uo thread to update user interface");
        ListOfPlacesAdapter listOfPlacesAdapter = new ListOfPlacesAdapter(
                this, nameAddressList);
        listView.setAdapter(listOfPlacesAdapter);
        listView.setItemsCanFocus(true);
    }

}

如果你卡在某个地方,请告诉我。