【问题标题】:Value Unknown of type java.lang.String cannot be converted to JSONObject [duplicate]java.lang.String 类型的值未知无法转换为 JSONObject [重复]
【发布时间】:2016-03-03 09:41:59
【问题描述】:

我正在尝试制作一个应用程序并将其连接到我的数据库(MySQL wamp)。我已经制作了我的 php 文件,这是出现错误的 NewProductActivity.java 文件。我已经制作了一个示例。我从here得到了代码

    package com.example.abc.androidhive;

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

    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.Activity;
    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.Button;
    import android.widget.EditText;

    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://api.androidhive.info/android_connect/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() {

            @Override
            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();
        }

    }
  }

给出错误的部分是:

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

我的 Logcat 是:

03-03 04:06:10.552 1944-1967/? E/JSON Parser: Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject
03-03 04:06:10.552 1944-1967/? W/dalvikvm: threadid=15: thread exiting with uncaught exception (group=0xb17d3678)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:841)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:  Caused by: java.lang.NullPointerException
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at com.example.abc.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:100)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at com.example.abc.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:64)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:841) 

请向我提出可能的整改建议。

【问题讨论】:

  • NewProductActivity 的第 100 行有什么内容?
  • @Raghavendra 非常抱歉...此代码属于 NewProductActivity
  • @Haketo.... 不,没有帮助
  • 请在" Log.d("Create Response", json.toString()); " 中发布你得到的内容
  • @logan 请检查JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params);后的json是否为空

标签: java android json android-studio


【解决方案1】:

问题是您的服务器返回的不是有效的 json。您应该检查此呼叫的响应是什么

我尝试使用随意的参数(名称 = a,价格 = b,描述 = c)并且服务器返回

未知数据库'download_androidhive'

这是一个字符串,99% 是您的问题的原因。

【讨论】:

    【解决方案2】:

    不是因为这个类,而是你写这些行的JSONParser类的错误

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

    我想建议您,它似乎根本不是一个 JsonObject。因此,只需尝试替换此行

    jObj = new JSONObject(json);
    

    JSONArray jsonArray = new JSONArray(json);  
    JSONObject jObj = jsonArray.getJSONObject(0); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-03
      • 2017-10-02
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多