-3
private Uri mImageCaptureUri;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
public String image="dffd";
EditText et1;
EditText et2;
 String phone_number;

    private ImageView imageview;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_photo);
       Intent i=getIntent();
        phone_number=i.getStringExtra("phone");
        imageview = (ImageView) findViewById(R.id.profile_pic);
        et1=(EditText)findViewById(R.id.name);
        et2=(EditText)findViewById(R.id.status);

        final String [] items           = new String [] {"Take from camera", "Select from gallery"};                
        ArrayAdapter<String> adapter    = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
        AlertDialog.Builder builder     = new AlertDialog.Builder(this);

        builder.setTitle("Select Image");
        builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick( DialogInterface dialog, int item ) { //pick from camera
                if (item == 0) {
                    Intent intent    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                       "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

                    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

                    try {
                        intent.putExtra("return-data", true);

                        startActivityForResult(intent, PICK_FROM_CAMERA);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                } else { //pick from file
                    Intent intent = new Intent();

                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                }
            }
        } );

        final AlertDialog dialog = builder.create();




        imageview.setOnClickListener(new View.OnClickListener() {   
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });

        Button b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {

                String name=et1.getText().toString();
                String status=et2.getText().toString();

                    Log.d("Name", name);
                    Log.d("Status", status);
                    Log.d("Image", image);
                    Log.d("Phone_number", phone_number);
                    UserFunctions userFunction = new UserFunctions();
                    JSONObject json = userFunction.registerUser("1214","Apoorv","status","image");
                    // check for login response
                    try {
                        if (json.getString(KEY_SUCCESS) != null) {

                            String res = json.getString(KEY_SUCCESS); 
                            if(Integer.parseInt(res) == 1){


                                Log.d("E", "S");

                            }else{
                            Log.d("Eroor", "erro");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                Intent i=new Intent(getApplicationContext(),DashBoardActivity.class);
                startActivity(i);

            }
        });


    }

This is giving the exception i used the async task still non happenning please help me with the hhtp req error. please be clear

07-05 08:00:34.545: E/AndroidRuntime(1648): FATAL EXCEPTION: main
07-05 08:00:34.545: E/AndroidRuntime(1648): android.os.NetworkOnMainThreadException
07-05 08:00:34.545: E/AndroidRuntime(1648):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at libcore.io.IoBridge.connect(IoBridge.java:112)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at java.net.Socket.connect(Socket.java:842)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at com.fluke.library.JSONParser.getJSONFromUrl(JSONParser.java:42)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at com.fluke.library.UserFunctions.registerUser(UserFunctions.java:37)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at com.chit.RegisterActivity2$3.onClick(RegisterActivity2.java:122)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at android.view.View.performClick(View.java:4204)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at android.view.View$PerformClick.run(View.java:17355)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at android.os.Handler.handleCallback(Handler.java:725)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at android.os.Looper.loop(Looper.java:137)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at java.lang.reflect.Method.invokeNative(Native Method)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at java.lang.reflect.Method.invoke(Method.java:511)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-05 08:00:34.545: E/AndroidRuntime(1648):     at dalvik.system.NativeStart.main(Native Method)
Lal
  • 14,726
  • 4
  • 45
  • 70
joshapoorva
  • 11
  • 2
  • 10

2 Answers2

2

NetworkOnMainThread exception occurs if your trying to do network related operation on the main UI Thread. So all network related operation should be done on the background thread.

You can not call webservice directly from main thread.

user AsyncTask or Handler to call a service.

class serviceTask extends AsyncTask<String, Void, String> {

    private Exception exception;

    protected String doInBackground(String... urls) {
        try {
            // call service
            return result;
        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(String feed) {
        // TODO: check this.exception 
        // TODO: do something with the feed
    }
}

to call AsyncTask

new serviceTask().execute("url")
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
0

When you attach to a widget a clicklistener the code you write in the onClick() method will run on the UIthread.

What you can do is the following, create the following class in your activity:

private class LongOperation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        //start of your code
        UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser("1214","Apoorv","status","image");
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        String res = json.getString(KEY_SUCCESS); 
                        if(Integer.parseInt(res) == 1){
                            Log.d("E", "S");
                        }else{
                        Log.d("Eroor", "erro");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //end of yor code
    }

    @Override
    protected void onPostExecute(String result) {
          //pass the result to your activity
          YourActivity.callBack(result);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

In your activity create the method callback (eventually using the result):

void callBack(String result) {
     Intent i=new Intent(getApplicationContext(),DashBoardActivity.class);
     startActivity(i);
}

then substitute this:

    UserFunctions userFunction = new UserFunctions();
                JSONObject json =   userFunction.registerUser("1214","Apoorv","status","image");
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {

                        String res = json.getString(KEY_SUCCESS); 
                        if(Integer.parseInt(res) == 1){


                            Log.d("E", "S");

                        }else{
                        Log.d("Eroor", "erro");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

Whit this:

   (new LongOperation()).execute(""))
AMC
  • 130
  • 8