Can't create handler inside thread that has not called Looper.prepare()3

5.1k views Asked by At
public class AddStudentActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_student);
}

public void add2(View view){
    //create 3 editText  ,  1 Textview
    EditText et_name, et_age;
    RadioButton rb_male;
    TextView tv_msg;

    //bind with xml widget
    et_name = (EditText)findViewById(R.id.et_name);
    et_age = (EditText)findViewById(R.id.et_age);
    rb_male = (RadioButton)findViewById(R.id.rb_male);
    tv_msg = (TextView)findViewById(R.id.tv_msg);
    //retrieve values
    String name = et_name.getText().toString();
    String age = et_age.getText().toString();
    String gender = "";
    if (rb_male.isChecked())
        gender = "male";
    else
        gender = "female";
    //call php
    new AddStudent(this, tv_msg).execute(name, age, gender);
   }
}

class AddStudent extends AsyncTask<String, Void, String> {
private Context context;
//CHANGE HERE....ADD PARAMATER
TextView tv_msg;

public AddStudent(Context context,TextView tv_msg) {
    this.context = context;
    this.tv_msg = tv_msg;

}

@Override
protected String doInBackground(String[] arg) {
    //CHANGE HERE ...... RETRIEVE STRING ARGUMENTS
   String name = arg[0];
    String age = arg[1];
    String gender = arg[2];

    String link;
    String data;
    BufferedReader bufferedReader;
    String result;

    try {
        //CHANGE HERE .... PARAMETERS
          data = "?name=" + URLEncoder.encode(name, "UTF-8");
        data += "&age="+ URLEncoder.encode(age, "UTF-8");
        data += "&gender="+ URLEncoder.encode(gender, "UTF-8");
        //CHANGE HERE .... PHP PAGE
          link = "http://10.0.2.2/fashionstudio/ADD3.php" + data;

        URL url = new URL(link);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        result = bufferedReader.readLine();

        return result;
    } catch (Exception e) {
        Log.d("msg here", e.getMessage());
        Toast.makeText(context, "Error Exception", Toast.LENGTH_SHORT).show();
        return new String("Exception: " + e.getMessage());

    }
}

@Override
protected void onPostExecute(String result) {
    if (result != null) {
        try {
            JSONObject reader = new JSONObject(result);
            //CHANGE HERE... RETRIEVE VALUES
            String msg = reader.getString("msg");
            tv_msg.setText(msg);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("msg here", e.getMessage());
            Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
    }
  }
}

i got a error when i click add student in android

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process: com.example.lenovo.yuwilson, PID: 22199 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.(Handler.java:208) at android.os.Handler.(Handler.java:122) at android.widget.Toast$TN.(Toast.java:341) at android.widget.Toast.(Toast.java:96) at android.widget.Toast.makeText(Toast.java:245) at com.example.lenovo.yuwilson.AddStudent.doInBackground(AddStudentActivity.java:94) at com.example.lenovo.yuwilson.AddStudent.doInBackground(AddStudentActivity.java:54) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:841)

Someone help me to solve please?

2

There are 2 answers

0
Lino On BEST ANSWER

You can't have

Toast.makeText(context, "Error Exception", Toast.LENGTH_SHORT).show();

inside the doInBackground method. Toast.makeText(...) must be executed in a UI thread.

0
rafsanahmad007 On

try this:

runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(context, "Error Exception", Toast.LENGTH_SHORT).show();
  }
});

You need to call Toast.makeText(...) from the UI thread: because UI thread deals with the UI related function not worker thread