0

So I've been working on an app(following this Tutorial)

Now when I change minSdkVersion from 8 to 11 the action bar works and everything is fine on all but one activity. While I'm in the allproducts activity and select one of the products to edit it crashes, I believe that it means the problem is in the editproductsactivity but I'm pretty new to programming on android so I'm lost. It works when I have minSdkVersion set to 8 but for some reason when I set it to 11 only this activity stops working. Can anyone help me?

EDIT: The errors I get in logcat are

01-15 13:16:14.314: W/dalvikvm(13431): threadid=1: thread exiting with uncaught exception (group=0x416e2d28)
01-15 13:16:14.317: E/AndroidRuntime(13431): FATAL EXCEPTION: main
01-15 13:16:14.317: E/AndroidRuntime(13431): Process: com.example.androidhive, PID: 13431
01-15 13:16:14.317: E/AndroidRuntime(13431): android.os.NetworkOnMainThreadException
01-15 13:16:14.317: E/AndroidRuntime(13431):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at libcore.io.IoBridge.connect(IoBridge.java:112)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at java.net.Socket.connect(Socket.java:833)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at com.example.androidhive.JSONParser.makeHttpRequest(JSONParser.java:62)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at com.example.androidhive.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:143)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at android.os.Handler.handleCallback(Handler.java:733)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at android.os.Looper.loop(Looper.java:137)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at android.app.ActivityThread.main(ActivityThread.java:5083)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at java.lang.reflect.Method.invokeNative(Native Method)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at java.lang.reflect.Method.invoke(Method.java:515)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-15 13:16:14.317: E/AndroidRuntime(13431):    at dalvik.system.NativeStart.main(Native Method)

Thank you in advance,

Tyler Moskov

greg-449
  • 109,219
  • 232
  • 102
  • 145
TylerM
  • 153
  • 17
  • NetworkOnMainThreadException occurs when you do some communication with server in main thread not in doInBackground of asyctask so find that samething – vipul mittal Jan 15 '14 at 18:29

2 Answers2

1

Older versions of android allowed to run Network related tasks on main thread but they changed this because network related tasks could take more time than usual blocking a main thread. So in newer versions its mandatory to run such tasks on a different thread and not main thread (also known as UI thread).

Check this page for code to solve this page

Community
  • 1
  • 1
rutulPatel
  • 320
  • 5
  • 12
  • So take the code involving the network connection from OnCreate and put it into DoInBackground? – TylerM Jan 15 '14 at 18:41
  • Nevermind, I see that it's JSONParser jsonParser = new JSONParser(); in the main thread, so I need to move that out of the main thread and put it into a DoInBackground? – TylerM Jan 15 '14 at 18:47
  • And That Fixed it. Thank you for your help. Nevermind, putting it in the doinbackground did not help, I just forgot to change it back to 11 instead of 8. – TylerM Jan 15 '14 at 18:48
  • Okay so taking out JSONParser jsonParser = new JSONParser(); and putting it into DoInBackground did not work. Anymore hints at what to do? because I'm completely lost... – TylerM Jan 15 '14 at 19:44
  • I am not sure how you are trying to achieve. Can you post your code here? NOTE: doInBackground() runs in background and onPostExecute() runs on main thread. So if you wanna populate the result in UI components use onPostExecute() because only main thread can touch UI components such as TextView, ListView, etc. – rutulPatel Jan 15 '14 at 19:56
  • It started out as the same code as this: ]http://stackoverflow.com/questions/19623771/how-to-fix-fatal-exceptionmain-android-os-networkonmainthreadexception but the answer there did not seem to work. I don't really know how I would move the network tasks to a new/different thread. – TylerM Jan 15 '14 at 19:57
  • From what I understand of the code, the network tasks come from JSONParser jsonParser = new JSONParser(); in public class EditProductActivity extends Activity {...} But it can't be there because it is a main thread, so I need to put that somewhere else? – TylerM Jan 15 '14 at 20:11
  • exactly, you have to use different thread than main to implement such tasks. – rutulPatel Jan 15 '14 at 20:24
1

Try this. i changed data type to JSONObject and as i said, use onPostExecute() while interacting with User interface components. The problem in your code was you were calling main thread "runOnUIthread()" from different thread "doInBackgroud()".

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProductActivity.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected JSONObject doInBackground(String... params) {

                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("pid", 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);

                    // check your log for json response
                    Log.d("Single Product Details", json.toString());

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray productObj = json
                                .getJSONArray(TAG_PRODUCT); // JSON Array

                        // get first product object from JSON Array
                        JSONObject product = productObj.getJSONObject(0);


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

        return null;
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(JSONObject result) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
        JSONObject product = result;

        setContentView(R.layout.edit_product);

        // product with this pid found
        // Edit Text
        txtName = (EditText) findViewById(R.id.inputName);
        txtPrice = (EditText) findViewById(R.id.inputPrice);
        txtDesc = (EditText) findViewById(R.id.inputDesc);

        // display product data in EditText
        txtName.setText(product.getString(TAG_NAME));
        txtPrice.setText(product.getString(TAG_PRICE));
        txtDesc.setText(product.getString(TAG_DESCRIPTION));
    }
}
rutulPatel
  • 320
  • 5
  • 12
  • it says that params is already declared and puts the mark next to List params = new ArrayList(); and unhandled exceptiontype JSONException for txtName.setText(product.getString(TAG_NAME)); – TylerM Jan 15 '14 at 20:22
  • sorry, i edited it in notepad. Change variable name here --> protected JSONObject doInBackground(String... string) ; surround with try catch--> try { JSONObject product = result; ......txtDesc.setText(product....) } – rutulPatel Jan 15 '14 at 20:37
  • Okay that worked but now a new error comes up: 01-15 17:11:49.412: E/AndroidRuntime(25485): java.lang.NullPointerException . It looks like it is in the onPostExecutable. So the Name is coming back Null? – TylerM Jan 15 '14 at 22:16
  • Yea it is definitely the name is come back null. I'm not sure why though. – TylerM Jan 16 '14 at 02:56