解析JSON对象的AsyncTask#3错误。 String无法转换为JSONObject

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解析JSON对象的AsyncTask#3错误。 String无法转换为JSONObject相关的知识,希望对你有一定的参考价值。

有人可以告诉我我的错误是什么吗?我从androidHive.info下载了这段代码。我一直在收到“解析数据错误的错误。也有人能告诉我如何找出错误在哪一行?

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = "http://xxx.xxx.xxx.xxx/include/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

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

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

这是我的logcat

01-26 18:14:35.366: D/dalvikvm(12395): GC_CONCURRENT freed 72K, 52% free 2619K/5379K, external 1529K/2026K, paused 8ms+2ms
01-26 18:14:36.296: E/JSON Parser(12395): Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject
01-26 18:14:36.296: W/dalvikvm(12395): threadid=9: thread exiting with uncaught exception (group=0x2aac8560)
01-26 18:14:36.306: E/AndroidRuntime(12395): FATAL EXCEPTION: AsyncTask #1
01-26 18:14:36.306: E/AndroidRuntime(12395): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 18:14:36.306: E/AndroidRuntime(12395):    at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.lang.Thread.run(Thread.java:1019)
01-26 18:14:36.306: E/AndroidRuntime(12395): Caused by: java.lang.NullPointerException
01-26 18:14:36.306: E/AndroidRuntime(12395):    at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:129)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-26 18:14:36.306: E/AndroidRuntime(12395):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
01-26 18:14:36.306: E/AndroidRuntime(12395):    ... 4 more
01-26 18:14:36.566: E/WindowManager(12395): Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afca938 that was originally added here
01-26 18:14:36.566: E/WindowManager(12395): android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afca938 that was originally added here
01-26 18:14:36.566: E/WindowManager(12395):     at android.view.ViewRoot.<init>(ViewRoot.java:265)
01-26 18:14:36.566: E/WindowManager(12395):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-26 18:14:36.566: E/WindowManager(12395):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-26 18:14:36.566: E/WindowManager(12395):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-26 18:14:36.566: E/WindowManager(12395):     at android.app.Dialog.show(Dialog.java:241)
01-26 18:14:36.566: E/WindowManager(12395):     at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:116)
01-26 18:14:36.566: E/WindowManager(12395):     at android.os.AsyncTask.execute(AsyncTask.java:391)
01-26 18:14:36.566: E/WindowManager(12395):     at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57)
01-26 18:14:36.566: E/WindowManager(12395):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-26 18:14:36.566: E/WindowManager(12395):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-26 18:14:36.566: E/WindowManager(12395):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
01-26 18:14:36.566: E/WindowManager(12395):     at android.app.ActivityThread.access$1500(ActivityThread.java:121)
01-26 18:14:36.566: E/WindowManager(12395):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
01-26 18:14:36.566: E/WindowManager(12395):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-26 18:14:36.566: E/WindowManager(12395):     at android.os.Looper.loop(Looper.java:123)
01-26 18:14:36.566: E/WindowManager(12395):     at android.app.ActivityThread.main(ActivityThread.java:3701)
01-26 18:14:36.566: E/WindowManager(12395):     at java.lang.reflect.Method.invokeNative(Native Method)
01-26 18:14:36.566: E/WindowManager(12395):     at java.lang.reflect.Method.invoke(Method.java:507)
01-26 18:14:36.566: E/WindowManager(12395):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
01-26 18:14:36.566: E/WindowManager(12395):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
01-26 18:14:36.566: E/WindowManager(12395):     at dalvik.system.NativeStart.main(Native Method)
01-26 18:16:02.626: I/Process(12395): Sending signal. PID: 12395 SIG: 9

谢谢!

编辑:这是AllProductsActivity.java的代码:

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://xxx.xxx.xxx.xxx/include/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() {

            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);
                }
            });

        }

    }
}
答案

首先,将您的方法包装在一个

try{
} catch(Throwable t) { Log.e("MyActivity", t.getMessage(), t); }

您应该更容易阅读堆栈跟踪。

要使此代码工作,您需要在Web服务器上使用“include / get_all_products.php”。然后,您需要使用服务器的IP地址更新url_all_products中定义的URL。你做过这个吗?

内部JSON解析器可用于少量数据。对于更多数据,像GSON这样的东西可以节省你的理智。

以上是关于解析JSON对象的AsyncTask#3错误。 String无法转换为JSONObject的主要内容,如果未能解决你的问题,请参考以下文章

来自使用 AsyncTask 解析的 JSON 对象的 setText [重复]

使用 AsyncTask 和 POST 方法将变量发送到服务器并返回 JSON 对象

为 AsyncTask 实现一个常规的 JSON 解析器函数

text 使用AsyncTask和okHttp&JSON解析获取API数据

android中的JSON解析和获取图像

致命异常:AsyncTask #1,java.lang.RuntimeException:执行 doInBackground() 时发生错误