1

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)
user2218667
  • 607
  • 6
  • 25
  • 46
  • what does this do `jsonParser.makeHttpRequest`? – Raghunandan Jul 19 '13 at 10:03
  • also post the stacktrace for clarity – Raghunandan Jul 19 '13 at 10:12
  • the exception is self explanatory. you get networkonmainthrexception. i have suggested the same below.http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception. seems you have not followed any of the suggestions in my post.http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html – Raghunandan Jul 19 '13 at 12:17

2 Answers2

2

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.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • @user2218667 what!. how can it be. you have `runOnUiThread` and you make http request inside it. you say i have done like these only!. wow! – Raghunandan Jul 19 '13 at 10:21
  • @user2218667 i have already suggested see the post again and read it full. – Raghunandan Jul 19 '13 at 10:42
  • yes now i have done ur way ly...but am getting the error:07-19 16:22:25.838: E/AndroidRuntime(2424): FATAL EXCEPTION: AsyncTask #5 07-19 16:22:25.838: E/AndroidRuntime(2424): java.lang.RuntimeException: An error occured while executing doInBackground() – user2218667 Jul 19 '13 at 10:55
  • post the whole stacktrace. – Raghunandan Jul 19 '13 at 10:55
  • @user2218667 you are updating/accessing ui from a background thread ie `doInbackground` which is not possible. return result in doinbackground and update ui in `onPostExecute`. or use `runOnUiThread` **only to update ui** not for making http request. – Raghunandan Jul 19 '13 at 11:05
  • @user2218667 where is your updated code. seems there is no change in your code posted. – Raghunandan Jul 19 '13 at 11:40
2

Here we are facing networkOnMainThreadException error ly .so we are using following 2 lines means getting the output successfully.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy); 

Hopefully it is helpful to all.

user2218667
  • 607
  • 6
  • 25
  • 46