необходимо выполнить «onPostExecute» в асинхронной задаче

#android #android-asynctask

#Android #android-asynctask

Вопрос:

у меня есть фрагмент кода, работающий в асинхронной задаче с поддержкой php-скрипта. я просто хочу проверить наличие идентификатора электронной почты в моей базе данных. я хочу отобразить всплывающее сообщение: «электронная почта уже существует», если она есть в базе данных. в противном случае еще один тост: «Успешно зарегистрирован».способ, который я привел ниже, работает только с условием else.как бы мне этого добиться?пожалуйста, помогите мне.

вот мой .java

 class SummaryAsyncTask extends AsyncTask<Void, Boolean, String> {

            private void postData(String fname,String lname,String email,String pass,String cpass,String mobile) {

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://xxxx/registration.php");

                try {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);


                    nameValuePairs.add(new BasicNameValuePair("fname", fname));
                    nameValuePairs.add(new BasicNameValuePair("lname", lname));
                    nameValuePairs.add(new BasicNameValuePair("email", email));
                    nameValuePairs.add(new BasicNameValuePair("pass", pass));
                    nameValuePairs.add(new BasicNameValuePair("cpass", cpass));
                    nameValuePairs.add(new BasicNameValuePair("mobile", mobile));


                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    response = httpclient.execute(httppost);
                    httpEntity = response.getEntity();

                    InputStream is = httpEntity.getContent();

                     BufferedReader reader = new BufferedReader(new InputStreamReader(
                                      is, "iso-8859-1"), 8); // From here you can extract the data that you get from your php file..

                          StringBuilder builder = new StringBuilder();

                          String line = null;

                          while ((line = reader.readLine()) != null) {
                              builder.append(line   "n");
                          }

                          is.close();

                           json = new JSONObject(builder.toString());// Here you are converting again the string into json object. So that you can get values with the help of keys that you send from the php side.

                             message = json.getString("message");

                         }

                catch(Exception e)
                {
                    Log.e("log_tag", "Error:  " e.toString());

                }

            }
            @Override
            protected void onPostExecute(final String message) {
                super.onPostExecute(message);
                 runOnUiThread(new Runnable() {
                      public void run() {
                          if (message!=null) {
                     Toast.makeText(Response.this,"Email Id already exist", Toast.LENGTH_LONG).show();
                }
                else{
                    Toast.makeText(Response.this, "Thank You!You have registered successfully", Toast.LENGTH_LONG).show();
                }
                     }
                });
            }
            @Override
            protected String doInBackground(Void... params) {
                postData(first,last,eid,pword,conp,mob);
                return null;
            }


        }
  

мой файл .php

 <?php
$con=mysql_connect("localhost","root","");
$sel=mysql_select_db("xxx",$con);
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$email=$_POST['email'];
$pass=$_POST['pass'];
$cpass=$_POST['cpass'];
$mobile=$_POST['mobile'];

$query=mysql_query("SELECT * FROM user WHERE email='$email'");
if(mysql_num_rows($query)>0){
    $response["message"] = "Email Id already exist.";
   echo json_encode($response);
}

else{
mysql_query("insert into member(fname,lname,email,pass,cpass,mobile) values ('$fname','$lname', '$email', '$pass','$cpass','$mobile')", $con);
}
?>
  

Ответ №1:

Потому что ваш message in onPostExecute всегда null так старается

 protected String doInBackground(Void... params) {
      return postData(first,last,eid,pword,conp,mob);
}
  

и postData метод должен вернуть String . т.е. переписать postData функцию как

  private String postData(String fname,String lname,String email,String pass,String cpass,String mobile) {

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://xxxx/registration.php");

                try {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);


                    nameValuePairs.add(new BasicNameValuePair("fname", fname));
                    nameValuePairs.add(new BasicNameValuePair("lname", lname));
                    nameValuePairs.add(new BasicNameValuePair("email", email));
                    nameValuePairs.add(new BasicNameValuePair("pass", pass));
                    nameValuePairs.add(new BasicNameValuePair("cpass", cpass));
                    nameValuePairs.add(new BasicNameValuePair("mobile", mobile));


                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    response = httpclient.execute(httppost);
                    httpEntity = response.getEntity();

                    InputStream is = httpEntity.getContent();

                     BufferedReader reader = new BufferedReader(new InputStreamReader(
                                      is, "iso-8859-1"), 8); // From here you can extract the data that you get from your php file..

                          StringBuilder builder = new StringBuilder();

                          String line = null;

                          while ((line = reader.readLine()) != null) {
                              builder.append(line   "n");
                          }

                          is.close();

                           json = new JSONObject(builder.toString());// Here you are converting again the string into json object. So that you can get values with the help of keys that you send from the php side.

                             message = json.getString("message");

                         }

                catch(Exception e)
                {
                    Log.e("log_tag", "Error:  " e.toString());

                }

            return message;

            }
  

И onPostExcute метод как

 @Override
            protected void onPostExecute(final String message) {
                super.onPostExecute(message);
                          if (message!=null) {
                     Toast.makeText(Response.this,"Email Id already exist", Toast.LENGTH_LONG).show();
                }
                else{
                    Toast.makeText(Response.this, "Thank You!You have registered successfully", Toast.LENGTH_LONG).show();
                }
               }
  

Комментарии:

1. Спасибо за ваши быстрые ответы. позвольте мне попробовать ваш ответ. @Nermeen @Giru Bhai

2. @user3588920 добро пожаловать, проверьте это и ответьте, работает ли это?

3. @user3588920 Рад помочь, приятного кодирования.

Ответ №2:

Потому что вы всегда возвращаетесь null doInBackground … это должно быть похоже:

 protected String doInBackground(Void... params) {
      return postData(first,last,eid,pword,conp,mob);
}
  

Итак, вам нужно изменить postData метод, чтобы вернуть String

Обратите внимание, вам не нужно вызывать runOnUiThread , onPostExecute поскольку он уже вызван в потоке пользовательского интерфейса