简体   繁体   English

运行应用程序时出现JSON PARSING错误

[英]JSON PARSING error while running app

Iam making an app with connecting to server and reading the json,but am getting java.lang.String org.json.JSONObject.toString()' on a null object reference error.please help me.thanks in advance Here is my activity 我正在制作一个与服务器连接并读取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();
    }
}
}

here is my Json parser public class JSONParser { 这是我的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;
}
}

here is my php file 这是我的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);
}

 ?>

here is my error log 这是我的错误日志

            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) 

i am able to create a new product,my product list json is being updated,but i cant see the products list 我能够创建新产品,我的产品列表json正在更新,但是我看不到产品列表

here is the products list activity 这是产品列表活动

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

}

} }

The error is in this line. 错误在这一行。

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

Because of null object, it gives you null pointer exception. 由于存在null对象,因此会为您提供空指针异常。 Double check with this line, Just add the safety check as below 仔细检查这一行,只需添加如下安全检查

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

Suggestion:(not related to crash) 意见建议:(与当机无关)

Just remove this line inputName = (EditText)findViewById(R.id.nameEt); 只需删除此行inputName = (EditText)findViewById(R.id.nameEt); in doInBackground() . doInBackground() You already initilised this variable in onCreate(), so just remove it. 您已经在onCreate()中初始化了此变量,因此只需将其删除即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM