在JSON解析jsonParser.makeHtt prequest错误 [英] jsonParser.makeHttpRequest error in json parsing

查看:139
本文介绍了在JSON解析jsonParser.makeHtt prequest错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用JSON和的AsyncTask 来分析数据。但我得到的错误对这些行:

 的JSONObject JSON = jsonParser.makeHtt prequest(url_product_detials,GET,则params);
 

这是我的code:

 公共类EditWatchListProducts延伸活动{

的EditText txtName的;
的EditText txtPrice;
按钮btnSave;
按钮btnDelete;

字符串PID;

私人ProgressDialog pDialog;

JSONParser jsonParser =新JSONParser();

        私有静态最后弦乐url_product_detials =htt​​p://192.168.2.22/android_connect/get_product_details.php;

     私有静态最后弦乐url_update_product =htt​​p://192.168.2.22/android_connect/update_product.php;

        私有静态最后弦乐url_delete_product =htt​​p://192.168.2.22/android_connect/delete_product.php;

 私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_PRODUCT =产品;
私有静态最后弦乐TAG_ID =PRODUCT_ID;
私有静态最后弦乐TAG_NAME =PRODUCT_NAME;
私有静态最后弦乐TAG_PRICE =target_price;
私有静态最后弦乐TAG_DESCRIPTION =零售商;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.edit_watchlist_product);

    btnSave =(按钮)findViewById(R.id.btnSave);
    btnDelete =(按钮)findViewById(R.id.btnDelete);

    意图I = getIntent();

   PID = i.getStringExtra(TAG_ID);

    新GetProductDetails()执行();

    btnSave.setOnClickListener(新View.OnClickListener(){

        @覆盖
        公共无效的onClick(查看为arg0){
            新SaveProductDetails()执行();
        }
    });

    btnDelete.setOnClickListener(新View.OnClickListener(){

        @覆盖
        公共无效的onClick(查看为arg0){
             新DeleteProduct()执行()。
        }
    });

}

 类GetProductDetails扩展的AsyncTask<字符串,字符串,字符串> {

  @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(EditWatchListProducts.this);
        pDialog.setMessage(装载产品的详细信息,请稍候...);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真正的);
        pDialog.show();
    }
    保护字符串doInBackground(字符串... PARAMS){

           runOnUiThread(新的Runnable(){
            公共无效的run(){
                //检查成功标签
                诠释成功;
                尝试 {
                    //大厦参数
                    名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
                    params.add(新BasicNameValuePair(PRODUCT_ID,PID));

                    //获取产品的详细信息通过HTTP请求
                    //注意产品细节的URL会使用GET请求
                    JSONObject的JSON = jsonParser.makeHtt prequest(
                            url_product_detials,GET,则params);



                   成功= json.getInt(TAG_SUCCESS);
                    如果(成功== 1){
                        JSONArray productObj = JSON
                                .getJSONArray(TAG_PRODUCT); // JSON数组

                        的JSONObject产物= productObj.getJSONObject(0);
                        txtName的=(的EditText)findViewById(R.id.inputName);
                        txtPrice =(EditText上)findViewById(R.id.inputPrice);
                        txtDesc =(EditText上)findViewById(R.id.inputDesc);

                        txtName.setText(product.getString(TAG_NAME));
                        txtPrice.setText(product.getString(TAG_PRICE));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));

                    }其他{
                        //没有找到产品与PID
                    }
                }赶上(JSONException E){
                    e.printStackTrace();
                }
            }
        });

        返回null;
    }

    保护无效onPostExecute(字符串file_url){
        pDialog.dismiss();
    }
}
类SaveProductDetails扩展的AsyncTask<字符串,字符串,字符串> {
    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(EditWatchListProducts.this);
        pDialog.setMessage(节能产品......);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真正的);
        pDialog.show();
    }

    保护字符串doInBackground(字符串参数... args){

        字符串名称= txtName.getText()的toString()。
        串价格= txtPrice.getText()的toString()。
        。字符串描述= txtDesc.getText()的toString();

        名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
        params.add(新BasicNameValuePair(tag_id,分别PID));
        params.add(新BasicNameValuePair(TAG_NAME,名));
        params.add(新BasicNameValuePair(TAG_PRICE,价格));
        params.add(新BasicNameValuePair(TAG_DESCRIPTION,描述));

        JSONObject的JSON = jsonParser.makeHtt prequest(url_update_product,
                POST,则params);

        尝试 {
            INT成功= json.getInt(TAG_SUCCESS);

            如果(成功== 1){
                意图=新的意图(getApplicationContext()
                        WatchListProducts.class);
                 startActivity(在);
            } 其他 {
                //无法更新产品
            }
        }赶上(JSONException E){
            e.printStackTrace();
        }

        返回null;
    }
    保护无效onPostExecute(字符串file_url){
        pDialog.dismiss();
    }
}

类DeleteProduct扩展的AsyncTask<字符串,字符串,字符串> {
    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(EditWatchListProducts.this);
        pDialog.setMessage(删除产品......);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真正的);
        pDialog.show();
    }

    保护字符串doInBackground(字符串参数... args){

        诠释成功;
        尝试 {
            名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
            params.add(新BasicNameValuePair(PRODUCT_ID,PID));
            JSONObject的JSON = jsonParser.makeHtt prequest(
                    url_delete_product,POST,PARAMS);

            Log.d(删除产品,json.toString());

            成功= json.getInt(TAG_SUCCESS);
            如果(成功== 1){
             意图=新的意图(getApplicationContext()
                        WatchListProducts.class);
                 startActivity(在);
            }
        }赶上(JSONException E){
            e.printStackTrace();
        }

        返回null;
    }

    保护无效onPostExecute(字符串file_url){
        pDialog.dismiss();

    }

  }
 }
 

编辑:

同样的code运作良好,在不同的project.when我与我的项目,时间LY我得到以下情况例外...实施

什么是错误的,我code ???

编辑:更新日志

  07-19 16:43:31.018:E / AndroidRuntime(3009):致命异常:主要
      07-19 16:43:31.018:E / AndroidRuntime(3009):android.os.NetworkOnMainThreadException
       07-19 16:43:31.018:E / AndroidRuntime(3009):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
    07-19 16:43:31.018:E / AndroidRuntime(3009):在java.net.InetAddress.lookupHostByName(InetAddress.java:391)
      07-19 16:43:31.018:E / AndroidRuntime(3009):在java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在java.net.InetAddress.getAllByName(InetAddress.java:220)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
     07-19 16:43:31.018:E / AndroidRuntime(3009):在org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
     07-19 16:43:31.018:E / AndroidRuntime(3009):在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
     07-19 16:43:31.018:E / AndroidRuntime(3009):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    07-19 16:43:31.018:E / AndroidRuntime(3009):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    07-19 16:43:31.018:E / AndroidRuntime(3009):在com.example.androidbestinuk.JSONParser.makeHtt prequest(JSONParser.java:60)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在com.example.androidbestinuk.EditWatchListProducts$GetProductDetails$1.run(EditWatchListProducts.java:131)
       07-19 16:43:31.018:E / AndroidRuntime(3009):在android.os.Handler.handleCallback(Handler.java:605)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在android.os.Handler.dispatchMessage(Handler.java:92)
     07-19 16:43:31.018:E / AndroidRuntime(3009):在android.os.Looper.loop(Looper.java:137)
      07-19 16:43:31.018:E / AndroidRuntime(3009):在android.app.ActivityThread.main(ActivityThread.java:4340)
    07-19 16:43:31.018:E / AndroidRuntime(3009):在java.lang.reflect.Method.invokeNative(本机方法)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在java.lang.reflect.Method.invoke(Method.java:511)
   07-19 16:43:31.018:E / AndroidRuntime(3009):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
    07-19 16:43:31.018:E / AndroidRuntime(3009):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  07-19 16:43:31.018:E / AndroidRuntime(3009):在dalvik.system.NativeStart.main(本机方法)
 

解决方案

runOnUiThread 它运行在UI线程上,你有这样的

 的JSONObject JSON = jsonParser.makeHtt prequest(
                        url_product_detials,GET,则params);
 

从你上述评论的code 获得产品的详细信息通过HTTP请求。所以,你做的UI线程上的HTTP请求。您将获得 NetworkOnMainThreadException

  

公众最终无效runOnUiThread(Runnable的动作)

     

加在API级别1

     

运行在UI线程在指定的操作。如果当前线程是UI线程,则该动作被立即执行。如果当前线程不是UI线程,该操作被张贴到UI线程的事件队列。

     

参数

     

动作的UI线程上运行的操作

所以,在preExecute 和 onPostExecute删除 runOnUiThread 和更新UI在 。发出HTTP请求 doInbackground

I try to parse data using json and AsyncTask. But am getting the error on these line:

JSONObject json = jsonParser.makeHttpRequest(url_product_detials, "GET", params);

this is my code:

public class EditWatchListProducts extends Activity {

EditText txtName;
EditText txtPrice;
Button btnSave;
Button btnDelete;

String pid;

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

        private static final String url_product_detials = "http://192.168.2.22/android_connect/get_product_details.php";

     private static final String url_update_product = "http://192.168.2.22/android_connect/update_product.php";

        private static final String url_delete_product = "http://192.168.2.22/android_connect/delete_product.php";

 private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_ID = "product_id";
private static final String TAG_NAME = "product_name";
private static final String TAG_PRICE = "target_price";
private static final String TAG_DESCRIPTION = "retailer";

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

    btnSave = (Button) findViewById(R.id.btnSave);
    btnDelete = (Button) findViewById(R.id.btnDelete);

    Intent i = getIntent();

   pid = i.getStringExtra(TAG_ID);

    new GetProductDetails().execute();

    btnSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new SaveProductDetails().execute();
        }
    });

    btnDelete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
             new DeleteProduct().execute();
        }
    });

}

 class GetProductDetails extends AsyncTask<String, String, String> {

  @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditWatchListProducts.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    protected String doInBackground(String... params) {

           runOnUiThread(new Runnable() {
            public void run() {
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("product_id", pid));

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_product_detials, "GET", params);



                   success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        JSONArray productObj = json
                                .getJSONArray(TAG_PRODUCT); // JSON Array

                        JSONObject product = productObj.getJSONObject(0);
                        txtName = (EditText) findViewById(R.id.inputName);
                        txtPrice = (EditText) findViewById(R.id.inputPrice);
                        txtDesc = (EditText) findViewById(R.id.inputDesc);

                        txtName.setText(product.getString(TAG_NAME));
                        txtPrice.setText(product.getString(TAG_PRICE));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));

                    }else{
                        // product with pid not found
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
    }
}
class SaveProductDetails extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditWatchListProducts.this);
        pDialog.setMessage("Saving product ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args) {

        String name = txtName.getText().toString();
        String price = txtPrice.getText().toString();
        String description = txtDesc.getText().toString();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_ID, pid));
        params.add(new BasicNameValuePair(TAG_NAME, name));
        params.add(new BasicNameValuePair(TAG_PRICE, price));
        params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));

        JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                "POST", params);

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

            if (success == 1) {
                Intent in = new Intent(getApplicationContext(),
                        WatchListProducts.class);
                 startActivity(in);
            } else {
                // failed to update product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

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

class DeleteProduct extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditWatchListProducts.this);
        pDialog.setMessage("Deleting Product...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args) {

        int success;
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("product_id", pid));
            JSONObject json = jsonParser.makeHttpRequest(
                    url_delete_product, "POST", params);

            Log.d("Delete Product", json.toString());

            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
             Intent in = new Intent(getApplicationContext(),
                        WatchListProducts.class);
                 startActivity(in);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

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

    }

  }
 }

EDIT:

The same code is working well on separate project.when i have implemented with my project that time ly am getting following exceptions...

What's wrong in my code ???

Edit: updated log

     07-19 16:43:31.018: E/AndroidRuntime(3009): FATAL EXCEPTION: main
      07-19 16:43:31.018: E/AndroidRuntime(3009): android.os.NetworkOnMainThreadException
       07-19 16:43:31.018: E/AndroidRuntime(3009):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
    07-19 16:43:31.018: E/AndroidRuntime(3009):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
      07-19 16:43:31.018: E/AndroidRuntime(3009):   at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
     07-19 16:43:31.018: E/AndroidRuntime(3009):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
     07-19 16:43:31.018: E/AndroidRuntime(3009):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
     07-19 16:43:31.018: E/AndroidRuntime(3009):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    07-19 16:43:31.018: E/AndroidRuntime(3009):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    07-19 16:43:31.018: E/AndroidRuntime(3009):     at com.example.androidbestinuk.JSONParser.makeHttpRequest(JSONParser.java:60)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at com.example.androidbestinuk.EditWatchListProducts$GetProductDetails$1.run(EditWatchListProducts.java:131)
       07-19 16:43:31.018: E/AndroidRuntime(3009):  at android.os.Handler.handleCallback(Handler.java:605)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at android.os.Handler.dispatchMessage(Handler.java:92)
     07-19 16:43:31.018: E/AndroidRuntime(3009):    at android.os.Looper.loop(Looper.java:137)
      07-19 16:43:31.018: E/AndroidRuntime(3009):   at android.app.ActivityThread.main(ActivityThread.java:4340)
    07-19 16:43:31.018: E/AndroidRuntime(3009):     at java.lang.reflect.Method.invokeNative(Native Method)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at java.lang.reflect.Method.invoke(Method.java:511)
   07-19 16:43:31.018: E/AndroidRuntime(3009):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    07-19 16:43:31.018: E/AndroidRuntime(3009):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  07-19 16:43:31.018: E/AndroidRuntime(3009):   at dalvik.system.NativeStart.main(Native Method)

解决方案

You have runOnUiThread which runs on ui thread and you have this

  JSONObject json = jsonParser.makeHttpRequest(
                        url_product_detials, "GET", params);

From you comments above the code getting product details by making HTTP request. So you are making http request on the ui thread. You will get NetworkOnMainThreadException.

public final void runOnUiThread (Runnable action)

Added in API level 1

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Parameters

action the action to run on the UI thread

So remove the runOnUiThread and update ui in onPreExecute and onPostExecute. Make HTTp request in doInbackground.

这篇关于在JSON解析jsonParser.makeHtt prequest错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆