FATAL EXCEPTION : AsyncTask#5

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

They have mentionned that the ERROR was occured while excecuting doInBackground()

public class NewClientActivity extends Activity {  // Progress Dialog private ProgressDialog pDialog;  JSONParser jsonParser = new JSONParser(); EditText name; EditText login; EditText password; EditText rePassword; EditText email; EditText adresse; EditText tel;  // url to create new product private static String url_add_client = "http://192.168.1.3/android_connect/add_client.php";  // JSON Node names private static final String TAG_SUCCESS = "success";  @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main_activity1);      // Edit Text     name = (EditText) findViewById(R.id.textViewNom);     login = (EditText) findViewById(R.id.textViewLogin);     password = (EditText) findViewById(R.id.textViewPassword);     rePassword = (EditText) findViewById(R.id.textViewPassword1);     email = (EditText) findViewById(R.id.textViewEmail);     adresse = (EditText) findViewById(R.id.textViewAdresse);     tel = (EditText) findViewById(R.id.textViewTel);      // Create button     Button btnAddClient = (Button) findViewById(R.id.connect);      // button click event     btnAddClient.setOnClickListener(new View.OnClickListener() {          @Override         public void onClick(View view) {             // creating new product in background thread             new CreateNewProduct().execute();         }     }); }  /**  * Background Async Task to Create new product  * */ class CreateNewProduct extends AsyncTask<String, String, String> {      /**      * Before starting background thread Show Progress Dialog      * */     @Override     protected void onPreExecute() {         super.onPreExecute();         pDialog = new ProgressDialog(NewClientActivity.this);         pDialog.setMessage("Adding Customer to DataBase..");         pDialog.setIndeterminate(false);         pDialog.setCancelable(true);         pDialog.show();     }      /**      * Creating product      * */     protected String doInBackground(String... args) {         String Name = name.getText().toString();         String Login = login.getText().toString();         String Password = password.getText().toString();     //  String RePassword = rePassword.getText().toString();         String Email = email.getText().toString();         String Adresse = adresse.getText().toString();         String Tel = tel.getText().toString();          // Building Parameters         List<NameValuePair> params = new ArrayList<NameValuePair>();         params.add(new BasicNameValuePair("Name", Name));         params.add(new BasicNameValuePair("Login", Login));         params.add(new BasicNameValuePair("Password", Password));         params.add(new BasicNameValuePair("Email", Email));         params.add(new BasicNameValuePair("Adresse", Adresse));         params.add(new BasicNameValuePair("Tel", Tel));           // getting JSON Object         // Note that create product url accepts POST method         JSONObject json = jsonParser.makeHttpRequest(url_add_client,                 "POST", params);          // check log cat fro response         Log.d("Create Response", json.toString());          // check for success tag         try {             int success = json.getInt(TAG_SUCCESS);              if (success == 1) {                 // successfully created product             //  Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);             //  startActivity(i);                  // closing this screen             //  finish();             } else {              Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show();             }         } catch (JSONException e) {             e.printStackTrace();         }          return null;     }      /**      * After completing background task Dismiss the progress dialog      * **/     protected void onPostExecute(String file_url) {         // dismiss the dialog once done         pDialog.dismiss();     }  } } 

Please if you can check it out and tell me where the ERROR is ?? thank you in advance !!

回答1:

just override into your AsyncTask the method onProgressUpdate

class CreateNewProduct extends AsyncTask<String, String, String> {     ...     ...     @Override     protected void onProgressUpdate(String... values) {        Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();     }      /**      * Creating product      * */     protected String doInBackground(String... args) {        ...        // check for success tag        try {            int success = json.getInt(TAG_SUCCESS);             if (success == 1) {                // successfully created product                //  Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);                //  startActivity(i);                // closing this screen               //  finish();            } else {               publishProgress("L'inscription n'a pas été éfectuée correctement");            }         } catch (JSONException e) {             e.printStackTrace();         }         ...     } } 


回答2:

I believe the error is because you are trying to update the UI in the doInBackground method of the AsyncTask.

    Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show();  

Move the above code to postExecute.

Also the following code in doInBackground wouldn't possibly cause an error to occur

    String Name = name.getText().toString();     String Login = login.getText().toString();     String Password = password.getText().toString();      String Email = email.getText().toString();     String Adresse = adresse.getText().toString();     String Tel = tel.getText().toString(); 


回答3:

Forget ASyncTask, Android Annotations is the better solution!

Look this: https://github.com/excilys/androidannotations/wiki



回答4:

Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show();   

You are trying to update ui from the background thread ie displaying toast.

Display toast in onPostExecute() or use runonuithread

    runOnUiThread(new Runnable() //run on ui thread         {          public void run()           {            Toast.makeText(NewClientActivity.this,"mymessage", 1000).show();         }         }); 

Use a activity context in place of getApplicationContext()

When to call activity context OR application context?

For more information check the link below .

http://developer.android.com/reference/android/os/AsyncTask.html



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!