陷入错误" NullPointerException异常"即使有数据数组列表数组、异常、错误、数据

2023-09-04 23:43:32 作者:蜀三川

该抓的错误是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.