我有一个 AsyncTask android 的致命错误

Posted

技术标签:

【中文标题】我有一个 AsyncTask android 的致命错误【英文标题】:I have a fatal error with AsyncTask android 【发布时间】:2017-09-14 04:46:21 【问题描述】:

我正在尝试从数据库(phpmyadmin)中获取我的数据并将其转换为 json 以将其放入 ListViewTextView 但是当我运行应用程序时它关闭并且当我检查日志时发现异常。

这是我的代码:

MainActivity.java

public class MainActivity extends AppCompatActivity 

ProgressDialog pDialog;
// Creating JSON Parser object

ListView lv;
ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://192.168.0.100/takeofftravel/test.php";
// products JSONArray
JSONArray products = null;
int error=0;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NOTIF = "notif";
private static final String TAG_PID = "id";
private static final String TAG_Type = "type";
private static final String TAG_REQUETE = "requete";
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Hashmap for ListView.
    productsList = new ArrayList<HashMap<String, String>>();
    // Get listview
    lv = (ListView)findViewById(R.id.listView);
    // Loading products in Background Thread
    new LoadAllProducts().execute();



    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() 

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) 
  /*          HashMap<String,String> map=new HashMap<String, String>();
            map=(HashMap<String,String>)lv.getAdapter().getItem(position);
            String ide=map.get(TAG_PID);
            Toast.makeText(All.this,ide,Toast.LENGTH_LONG).show();
            Intent i=new Intent(getApplicationContext(),Detail.class);
            i.putExtra("id",ide);
            startActivity(i);
            finish();*/
        
    );





class LoadAllProducts extends AsyncTask<String, String, String> 

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() 
        super.onPreExecute();

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) 
        // Building Parameters
        HashMap<String, String> params = new HashMap<String, String>();
        JSONParser jParser = new JSONParser();
        // getting JSON string from URL

        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());






        // Checking for SUCCESS TAG
        int success = 0;
        try 
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) 
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_NOTIF);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) 
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String type = c.getString(TAG_Type);
                    String requete=c.getString(TAG_REQUETE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_Type, type);
                    map.put(TAG_REQUETE,requete);

                    // adding HashList to ArrayList
                    productsList.add(map);
                
             else 
            
         catch (JSONException e) 
            e.printStackTrace();
        



        return null;
    

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) 
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        //    runOnUiThread(new Runnable() 
        //       public void run() 
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, productsList,
                R.layout.item, new String[]  TAG_PID,
                TAG_Type,TAG_REQUETE,
                new int[]  R.id.pid, R.id.nom,R.id.nature );
        // updating listview
        lv.setAdapter(adapter);
        //  
        // );

    


JSONParse.java 文件:

public class JSONParser 
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONObject makeHttpRequest(String url, String method,
                                  HashMap<String, String> params) 

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) 
        try 
            if (i != 0)
                sbParams.append("&");
            
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

         catch (UnsupportedEncodingException e) 
            e.printStackTrace();
        
        i++;
    

    if (method.equals("POST")) 
        // request method is POST
        try 
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(true);

            conn.setRequestMethod("POST");

            conn.setRequestProperty("Accept-Charset", charset);

            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);

            conn.connect();

            paramsString = sbParams.toString();

            wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(paramsString);
            wr.flush();
            wr.close();

         catch (IOException e) 
            e.printStackTrace();
        
    
    else if(method.equals("GET"))
        // request method is GET

        if (sbParams.length() != 0) 
            url += "?" + sbParams.toString();
        

        try 
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(false);

            conn.setRequestMethod("GET");

            conn.setRequestProperty("Accept-Charset", charset);

            conn.setConnectTimeout(15000);

            conn.connect();

         catch (IOException e) 
            e.printStackTrace();
        

    

    try 
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) 
            result.append(line);
        

        Log.d("JSON Parser", "result: " + result.toString());

     catch (IOException e) 
        e.printStackTrace();
    

    conn.disconnect();

    // try parse the string to a JSON object
    try 
        jObj = new JSONObject(result.toString());
     catch (JSONException e) 
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    

    // return JSON Object
    return jObj;

错误信息:

E/androidRuntime: FATAL EXCEPTION: AsyncTask #1
              Process: com.example.asus.json, PID: 11657
              java.lang.RuntimeException: An error occured while executing doInBackground()
                  at android.os.AsyncTask$3.done(AsyncTask.java:300)
                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                  at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                  at java.lang.Thread.run(Thread.java:841)
               Caused by: java.lang.NullPointerException
                  at com.example.asus.json.JSONParser.makeHttpRequest(JSONParser.java:124)
                  at com.example.asus.json.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:100)
                  at com.example.asus.json.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:75)
                  at android.os.AsyncTask$2.call(AsyncTask.java:288)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                  at java.lang.Thread.run(Thread.java:841) 

【问题讨论】:

【参考方案1】:

主要问题在于第 124 行的 JSONParser 类。发生这种情况是因为 JSONParser 类没有返回任何 JSON,并且结果 JSON 为 null,并且您正在对 null JSON 对象调用函数 getInt(),这就是为什么NullPointerException。

【讨论】:

那我该怎么办? 你应该尝试为 result.toString() 做一个 Toast 并检查它是否显示了什么。

以上是关于我有一个 AsyncTask android 的致命错误的主要内容,如果未能解决你的问题,请参考以下文章

Android SQLite 更新无法在 AsyncTask 的后台运行

android asynctask导致另一个活动

android asynctask 导致另一个活动

如何在Android中强制停止AsyncTask [重复]

Android 简单列表与 AsyncTask 替代

Android 从 AsyncTask 调用 notifyDataSetChanged