1

Whats wrong with this class, I am getting error as "Can't create handler inside thread that has not called Looper.prepare()" and error is pointing at the pose Execution of MessageSend.

public class ComposeActivity extends Activity {
    String receiver,subject,message;
    TextView compose_to;
    EditText compose_subject;
    TextView compose_msg_label;
    EditText compose_message;
    TextView compose_error;
    Button send_pm;
    ConnectionDetector cd ;
    AlertDialogManager alert;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compose);
        getActionBar().setDisplayHomeAsUpEnabled(true); // Put the back button in title
        Bundle bundle = getIntent().getExtras();
        /*
         * Instantiate objects
         */
        cd = new ConnectionDetector(getApplicationContext()); // Connection Detector
        alert = new AlertDialogManager(); // Alert Dialog
        /* 
         * Assign view to variable
         */
        compose_to = (TextView)findViewById(R.id.compose_to);
        compose_subject = (EditText)findViewById(R.id.compose_subject);
        compose_msg_label = (TextView)findViewById(R.id.compose_message_label);
        compose_message = (EditText)findViewById(R.id.compose_message);
        compose_error = (TextView)findViewById(R.id.compose_error);
        send_pm = (Button)findViewById(R.id.send_pm);

    /*
     * Check for the passed receiver
     */
    if(bundle != null){
        receiver = bundle.getString("to");
        compose_to.setText(receiver);
    }

    /*
     * send_pm button click
     */
    send_pm.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View arg0) {
            subject = compose_subject.getText().toString();
            message = compose_message.getText().toString();
            /*
             * check emptyness
             */
            if(!subject.equals("") && !message.equals("")){
                if(cd.isConnectingToInternet()){
                    //Toast.makeText(getApplicationContext(),"Correct", Toast.LENGTH_SHORT).show();
                    new MessageSend().execute();
                }else{
                    alert.showAlertDialog(ComposeActivity.this, getResources().getString(R.string.connection_error_head), getResources().getString(R.string.connection_error), null);
                }
            }else if(subject.equals("")){
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.empty_subject), Toast.LENGTH_SHORT).show();
            }else if(message.equals("")){
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.empty_message), Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_blank_input), Toast.LENGTH_SHORT).show();
            }

        }

    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.compose, menu);
    return true;
}
/*
 * 
 */
private class MessageSend extends AsyncTask<String, String, JSONObject> {
     private ProgressDialog pDialog;
     String loc;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
             Bundle bundle = getIntent().getExtras();
             //id = bundle.getString("siteid");
             pDialog = new ProgressDialog(ComposeActivity.this);
             pDialog.setMessage("Sending Message ...");
             pDialog.setIndeterminate(false);
             pDialog.setCancelable(true);
             pDialog.show();
        }
        @Override
        protected JSONObject doInBackground(String... args) {
            //user = db.getUserDetails();

            UserFunctions userFunction = new UserFunctions();
            //JSONObject json = userFunction.deleteSite(id);
            return null;
        }
        @Override
        protected void onPostExecute(JSONObject json) {

                try {
                    if(json.has("success_msg")){
                        pDialog.dismiss();
                        Intent intent = new Intent(ComposeActivity.this,SitePage.class);
                        startActivity(intent);  
                        Toast.makeText(getApplicationContext(), json.getString("success_msg"), Toast.LENGTH_SHORT).show();
                    }else{
                        pDialog.dismiss();
                        String err = json.getString("error_msg");
                        Toast.makeText(getApplicationContext(), err, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


        }

}   

}

Here is my logcat

02-21 22:32:10.655: E/AndroidRuntime(2403): FATAL EXCEPTION: main
02-21 22:32:10.655: E/AndroidRuntime(2403): java.lang.NullPointerException
02-21 22:32:10.655: E/AndroidRuntime(2403):     at com.Creators.biotrack.ComposeActivity$MessageSend.onPostExecute(ComposeActivity.java:131)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at com.Creators.biotrack.ComposeActivity$MessageSend.onPostExecute(ComposeActivity.java:1)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at android.os.Looper.loop(Looper.java:137)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at android.app.ActivityThread.main(ActivityThread.java:5103)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at java.lang.reflect.Method.invokeNative(Native Method)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at java.lang.reflect.Method.invoke(Method.java:525)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-21 22:32:10.655: E/AndroidRuntime(2403):     at dalvik.system.NativeStart.main(Native Method)
OlivierLi
  • 2,798
  • 1
  • 23
  • 30
Nepal12
  • 583
  • 1
  • 12
  • 29
  • possible duplicate of [Can't create handler inside thread that has not called Looper.prepare()](http://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare) – Chris Stratton Feb 21 '14 at 21:49
  • on which line are you getting NullPointerException ? – Kakarot Feb 21 '14 at 22:08
  • Your `doInBackground()` is returning `null`. This is passed as the `json` parameter to `onPostExecute()`. In that method you do `if(json.has("success_msg"))...` which will throw a `NullPointerException`. – David Wasser Feb 21 '14 at 22:09
  • @sushil: I am getting nullpointer exception at `pDialog.setMessage(getResources().getString(R.string.progress_sending_message));` – Nepal12 Feb 21 '14 at 22:29
  • @david: I did as you asked me but still the same `protected JSONObject doInBackground(String... args) { user = db.getUserDetails(); UserFunctions userFunction = new UserFunctions(); JSONObject json = userFunction.sendMessage(user.get("uname"), receiver, subject, message); return json; }` – Nepal12 Feb 21 '14 at 22:30
  • I am doing exact on other class but there it is working perfectly. Why only on this class. I tried to delete the whole activity and recreate this, but still getting the same error. – Nepal12 Feb 21 '14 at 22:31
  • Its awkward but when I delete the whole onPreExecute block, I didnot get any error and my code runs perfectly as expected. What could be the reason for that. – Nepal12 Feb 21 '14 at 22:44
  • It's clear that what is happening is that the AsyncTask is being executed OFF the UI Thread, and by calling the dialog, it throws this exception. What you can do to confirm is Log.i("SomeTag", Thread.currentThread.getName()); in all of the callbacks. My guess is that the onClick is being called from something outside the UI, which is not normal. As of why this is happening is still unclear... – Toguard Feb 21 '14 at 23:37
  • @ErickGandara : Seriously , I am using exactly the same code on other classes where I am not getting any error. There I am using onPreExecute and not get any error. – Nepal12 Feb 22 '14 at 12:38

1 Answers1

0

After all . I did some small change in my code and it worked. I did following changes.

  • Declare the pDialog on top class i.e

    public class ComposeActivity extends Activity { public ProgressDialog pDialog; String receiver,subject,message; TextView compose_to; .................... .................

  • I used ComposeActivity.this instead of getApplicationContext() on the toast I used on protected void onPostExecute(JSONObject json)

And the problem is solved. But I still don't get why previous implementation does not work as it was working some other classes .

Nepal12
  • 583
  • 1
  • 12
  • 29