AsyncTask #3 解析 JSON 对象时出错。字符串无法转换为 JSONObject

Posted

技术标签:

【中文标题】AsyncTask #3 解析 JSON 对象时出错。字符串无法转换为 JSONObject【英文标题】:AsyncTask #3 error parsing JSON object. String cannot be converted to JSONObject 【发布时间】:2013-01-10 15:30:26 【问题描述】:

谁能告诉我我的错误是什么?我从 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();
        

    

这是我的日志

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

        

    

【问题讨论】:

线缝为 AllProductsActivity.java:129。为我们提供要解析的 JSON 字符串的转储。 发布 AllProductsActivity 的代码。另外,您使用的是哪个 JSON 解析器? @ErikNedwidek 我发布了 AllProductsActivity.java 的代码...我不确定我使用的是哪个 JSON 解析器...我对 Android 还很陌生。只是想让这些教程发挥作用;) @jtrain - 哦,我是个白痴。他们正在使用内部的。我以前用过它,并尽快切换到 GSON(似乎也把内部存在的事实放在心上)。 @ErikNedwidek 好的,我明白了。感谢您花时间查看我的代码! 【参考方案1】:

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

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

你应该得到一个更容易阅读的堆栈跟踪。

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

内部 JSON 解析器可用于少量数据。对于更多数据,GSON 之类的东西可以让您保持理智。

【讨论】:

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

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

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

在 Android Studio 中使用 AsyncTask 解析在线 XML 文件时出现 NetworkOnMainThreadException

解析 JSON 对象时出现 NoClassDefFoundError JsonAutoDetect

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

Javascript:解析 document.cookie JSON 对象时出现问题