陷入错误" NullPointerException异常"即使有数据数组列表 [英] Caught error "NullPointerException" even though there is data for array list

查看:108
本文介绍了陷入错误" NullPointerException异常"即使有数据数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该抓的错误是NullPointerException异常。但是当我调试,也有一些是在ArrayList中的数据。该应用程序并没有停止,但没有发生在响应了。我的code是这样的:

 公共无效sendDestination_zhu(视图v){
    tryconnect TC =新tryconnect();
    名单<字符串> SR = tc.doInBackground();
    尝试{
        名单<字符串>数据=新的ArrayList<字符串>();
        数据= SR;
        ListView控件列表=(ListView控件)findViewById(R.id.listView);
        ArrayAdapter<字符串>适配器=新的ArrayAdapter<字符串> (FragmentHandler.this,R.layout.single_row,R.id.parkingplace,数据);
        list.setAdapter(适配器);
    }赶上(例外五){
        e.printStackTrace();
    }
}
 

解决方案

您使用的AsyncTask是错误的做法。 doInBackground方法应该由我们自己创建的AsyncTask子类调用。一个永远不应该直接调用它。

请参阅的例子。

什么是happenning在你的情况是低于code之前的AsyncTask完成并得到执行,因此空指针。

 尝试{
    名单<字符串>数据=新的ArrayList<字符串>();
    数据= SR;
    ListView控件列表=(ListView控件)findViewById(R.id.listView);
    ArrayAdapter<字符串>适配器=新的ArrayAdapter<字符串> (FragmentHandler.this,R.layout.single_row,R.id.parkingplace,数据);
    list.setAdapter(适配器);
}赶上(例外五){
    e.printStackTrace();
}
 

有关此方便,onPostExecute()方法是在AsyncTask的类可用。请参阅链接和其他许多在网上提供。

The caught error is "NullPointerException". But When I debugged, there is something in Arraylist data. The app did not stop, but nothing happened in response too. My code is like this:

 public void sendDestination_zhu(View v){
    tryconnect tc= new tryconnect();
    List<String> sR=tc.doInBackground();
    try{
        List<String> data=new ArrayList<String>();
        data=sR;
        ListView list = (ListView)findViewById(R.id.listView);
        ArrayAdapter<String> adapter=new ArrayAdapter<String> (FragmentHandler.this,R.layout.single_row,R.id.parkingplace,data);
        list.setAdapter(adapter);
    }catch(Exception e){
        e.printStackTrace();
    }
}

解决方案

Your approach of using Asynctask is wrong. The doInBackground method should be called by the Asynctask subclass we create on its own. One should never call it directly.

Please refer to an example.

What is happenning in your scenario is the below code gets executed even before Asynctask finishes and hence the NUll Pointer.

try{
    List<String> data=new ArrayList<String>();
    data=sR;
    ListView list = (ListView)findViewById(R.id.listView);
    ArrayAdapter<String> adapter=new ArrayAdapter<String> (FragmentHandler.this,R.layout.single_row,R.id.parkingplace,data);
    list.setAdapter(adapter);
}catch(Exception e){
    e.printStackTrace();
}

For this convenience only, onPostExecute() method is available in AsyncTask class. Please refer the link and many other available online.

这篇关于陷入错误&QUOT; NullPointerException异常&QUOT;即使有数据数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆