【问题标题】:JSON PARSING error while running app运行应用程序时出现 JSON PARSING 错误
【发布时间】:2016-06-27 11:34:39
【问题描述】:

我正在制作一个连接到服务器并读取 json 的应用程序,但是我在空对象引用错误上得到 java.lang.String org.json.JSONObject.toString()'。请帮助我。提前谢谢 这是我的活动

    public class NewProductActivity extends Activity {

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
Button createBtn;

private static String url_create_product = "http://10.0.2.2/create_product.php";

private static final String TAG_SUCCESS = "success";

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

    inputName = (EditText)findViewById(R.id.nameEt);
    createBtn = (Button)findViewById(R.id.createBt);

    createBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new CreateNewProduct().execute();
        }
    });

}
class CreateNewProduct extends AsyncTask<String,String,String>{
    String name = inputName.getText().toString();
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(NewProductActivity.this);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args){

        inputName = (EditText)findViewById(R.id.nameEt);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name",name ));

        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(), AllProductsActivty.class);
                startActivity(i);

                // closing this screen
                finish();
            } else {
                // failed to create product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }
}
}

这是我的 Json 解析器 公共类 JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser(){}

public JSONObject makeHttprequest(String url, String method, List<NameValuePair> params){

    try {
        if (method.equals( "POST")){

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }else if (method .equals( "GET")){
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params,"url");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);


            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
    }catch (UnsupportedEncodingException e ){
        e.printStackTrace();
    }catch (ClientProtocolException e){
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null){
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    }catch (Exception e){
        Log.e("Buffer error","Error Converting");
    }
    try {
        jObj = new JSONObject(json);
    }catch (JSONException e){
        Log.e("JSON Parser","Error parsing");
    }

    return jObj;
}
}

这是我的 php 文件

      <?php
 $response = array();
  if(isset($_POST['name'])){
   $name =  $_POST['name'];

 $con = mysql_connect("localhost","root","root");
$db = mysql_select_db("db");  
$result = mysql_query("INSERT INTO product(name) VALUES ('$name')");

if($result){
    $response["success"] = 1;
    $response["message"] = "successfully inserted";
    echo json_encode($respone);
}
else {
    $response["success"] = 0;
    $response["message"] ="error occured";
    echo json_encode($response);
}
} else{
 $response["success"] = 0;
   $response["message"] = "required feild missing";
  echo json_encode($response);
}

 ?>

这是我的错误日志

            06-27 18:35:55.097 3462-4317/com.example.joel339.sample           E/JSON Parser: Error parsing

                                                                   --------- beginning of crash
           06-27 18:35:55.097 3462-4317/com.example.joel339.sample E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1


                                                                      Process: com.example.joel339.sample, PID: 3462
                                                                      java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                          at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                          at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                          at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.doInBackground(NewProductActivity.java:70)
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.access$dispatch(NewProductActivity.java)
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:0)
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:50)
                                                                          at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                                                                          at java.lang.Thread.run(Thread.java:818) 

我可以创建一个新产品,我的产品列表 json 正在更新,但我看不到产品列表

这是产品列表活动

   public class AllProductsActivty extends ListActivity {

private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String,String>> productsList;

private static String url_all_products = "http://10.0.2.2/get_all_products_details.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";

JSONArray products = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    productsList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    new LoadAllProducts().execute(url_all_products);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String pid = ((TextView)view.findViewById(R.id.pid)).getText().toString();

            Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
            in.putExtra(TAG_PID,pid);

            startActivityForResult(in,100);
        }
    });
}
@Override
protected void onActivityResult(int requestCode,int resultCode , Intent data){
    super.onActivityResult(requestCode,resultCode,data);

    if(resultCode == 100){
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}

class LoadAllProducts extends AsyncTask< String,String,String>{
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivty.this);
        pDialog.setMessage("LoadingProducts.Please Wait");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args){
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttprequest(url_all_products,"GET",params);
        Log.d("Allproducts:",json.toString());

        try{
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1){

                products = json.getJSONArray(TAG_PRODUCTS);

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

                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);

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

                    map.put(TAG_PID,id);
                    map.put(TAG_NAME,name);
                    productsList.add(map);
                }
            }else{
                Intent i = new Intent(getApplicationContext(),NewProductActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String file_url){
        pDialog.dismiss();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivty.this,productsList,R.layout.list_view,new String[]{TAG_PID,TAG_NAME},
                        new int[]{R.id.pid,R.id.name});
                setListAdapter(adapter);
            }
        });
    }

}

}

【问题讨论】:

  • 您不应该在后台线程中初始化视图删除 doInBackground 中的 inputName = (EditText)findViewById(R.id.nameEt); 并且您的 jsonObject 为空,这就是为什么您在这里得到空指针期望 // check log cat fro response Log.d("Create Response", json.toString());
  • 代码中的“295”行号是什么?
  • 那我应该在哪里初始化视图?
  • @SaravInfern 你是对的。这可能是个问题。但这不会导致崩溃。对吗?
  • 我已经编辑了logcat

标签: android json


【解决方案1】:

错误在这一行。

Log.d("Create Response", json.toString());

因为null 对象,它给你空指针异常。 仔细检查这一行,只需添加安全检查,如下所示

if (json == null || json == JSONObject.NULL){
     // error handling.. 
}
else
{
     // Your code
}

建议:(与崩溃无关)

只需在doInBackground() 中删除这行inputName = (EditText)findViewById(R.id.nameEt);。您已经在 onCreate() 中初始化了这个变量,所以只需将其删除。

【讨论】:

  • @sunnyjoel 告诉我你更新的代码。否则删除这行Log.d("Create Response", json.toString()); 并检查它..
  • 是的,它起作用了。应用程序现在没有崩溃。但它没有继续执行 AllProductsActivity 的意图。
  • 我添加到代码if (if json == null || json.object == null){Log.d("null","null")};应用程序现在不会崩溃,并且logcat显示06-27 20:00:19.059 5082-5229/com.example.joel339.sample E/JSON Parser: Error parsing 06-27 20:00:19.059 5082-5229/com.example.joel339.sample D/null: null..json返回空。
  • 你的 json 是空的。你必须修复它。这可能是与服务器端有关的问题。
  • 我该怎么做?请帮帮我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-14
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多