【问题标题】:Android FATAL EXCEPTION: AsyncTask #1 with JASONParserAndroid 致命异常:带有 JASONParser 的 AsyncTask #1
【发布时间】:2014-08-26 20:05:47
【问题描述】:

我是 Android 新手,运行程序后,我的 Log cat 出现此错误。请告诉我如何解决这个问题

    08-27 01:16:12.910: E/AndroidRuntime(602): FATAL EXCEPTION: AsyncTask #1
    08-27 01:16:12.910: E/AndroidRuntime(602): java.lang.RuntimeException: An error       occured while executing doInBackground()
    08-27 01:16:12.910: E/AndroidRuntime(602):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.lang.Thread.run(Thread.java:856)
    08-27 01:16:12.910: E/AndroidRuntime(602): Caused by: java.lang.NullPointerException
    08-27 01:16:12.910: E/AndroidRuntime(602):  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
    08-27 01:16:12.910: E/AndroidRuntime(602):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    08-27 01:16:12.910: E/AndroidRuntime(602):  ... 4 more

这是我的 AllProductsActivity 类的代码。除了 MainActivity 之外,还有另外三个类。我想要的是使用远程服务器从数据库中检索我的数据。

    package com.example.androidhive;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    import org.apache.http.NameValuePair;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;

    public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://localhost/AndroidPHP/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

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

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    }

    /**
    * Background Async Task to Load all product by making HTTP Request
    * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 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());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // 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 name = c.getString(TAG_NAME);

                    // 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_NAME, name);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } 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(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME},
                        new int[] { R.id.pid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

    }
    }

【问题讨论】:

  • 您必须在第 130 行告诉我们 AllProductsActivity 中发生了什么。
  • 你的代码哪一部分抛出空指针异常,你也要贴出代码
  • 这是发生在 AllProductsActivity 中的 nullPointerException。查看那里的代码,也许您会发现问题或发布代码以便我们为您提供帮助。
  • @JaySnayder 我发布了代码。请帮我解决这个问题。

标签: android exception android-asynctask runtime-error


【解决方案1】:

以下指令返回空值:

products = json.getJSONArray(TAG_PRODUCTS);

这会导致调用时出现 NullPointerException:

for (int i = 0; i < products.length(); i++) {

您要么拼错了 TAG_PRODUCTS,要么在 JSONObject 中根本没有 TAG_PRODUCTS

编辑: 似乎这条指令导致了 NullPointerException:

    Log.d("All Products: ", json.toString());

这意味着这个方法返回null:

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

您尝试从中获取数据的原因:

http://localhost/AndroidPHP/get_all_products.php

但您的设备上不存在此本地主机。您应该使用在线版本,或以其他方式访问它。 StackOverflow“安卓的本地主机”。

【讨论】:

  • 粘贴json变量的内容:json.toString()
  • 没听懂。在哪里粘贴它
  • 好的。感谢您的关心。我将尝试在线版本。您能否给我一个正确的链接,以参考有关使用 PHP 的 android 的教程,我可以在 localhost 环境中对其进行测试。
  • @AmindaMandawala 并将此答案标记为正确答案,如果它解决了您面临的问题;)
猜你喜欢
  • 2014-09-26
  • 2015-07-16
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 2015-09-17
  • 1970-01-01
相关资源
最近更新 更多