NetworkOnMainThreadException

NetworkOnMainThreadException

This question already has answers here:
NetworkOnMainThreadException
                                
                                    (5个答案)
                                
                        
                6年前关闭。
            
        

我正在尝试使用JSON从服务器获取数据并将检索到的数据放入数组
这是检索类别,内部,id_news,图像的功能

public void getNewsFromServer(int beg){

    InputStream is = null;
    String result = "";

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("beg", Integer.toString(beg)));

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(strURL);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
    }
    // conversion of the query into string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,
     "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();


    } catch (Exception e) {
        Toast.makeText(context, e.toString(),Toast.LENGTH_LONG).show();
    }

    try {
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json_data = jArray.getJSONObject(i);

            id_news[i] = Integer.toString(json_data.getInt("id_news"));
            categorie[i] = json_data.getString("categorie");
            intitule[i] = json_data.getString("intitule");
            image[i] = json_data.getString("image");
        }


    }catch (Exception e){
        Toast.makeText(context, e.toString(),
                Toast.LENGTH_LONG).show();
    }
}


这是MainActivity.java

String [] id_news= new String [20];
String [] categorie= new String [20];
String [] intitule= new String [20];
String [] image= new String [20];

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
 try{
    //get data from the server and put it in tables
    getNewsFromServer(beg);
 }catch(NullPointerException e)
    {
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        e.getStackTrace();
    }
}


但我总是得到NULLPointerException
请帮助

这些logCat跟踪


这是上下文的初始化。

但会生成另一个异常NetworkOnMainThreadException和NullPointerException和JSONException:输入在字符0处结束。

最佳答案

NPE来自Toast初始化。确保您通过的context不为空。

由于您在异常捕获块中使用烤面包,因此请使用e.printStackTrace()掌握根本原因。 (主要嫌疑人:NetworkOnMainThreadException

对于NetworkOnMainThreadException,请在后台线程上执行网络操作。有关更多信息,请参见How to fix android.os.NetworkOnMainThreadException?

10-08 17:51