【问题标题】:Can't post response from AsyncTask to MainActivity [closed]无法将 AsyncTask 的响应发布到 MainActivity [关闭]
【发布时间】:2013-09-10 15:39:47
【问题描述】:

我是 Android 应用程序开发的新手。请找到我的 AsyncTask 代码,用于在用户单击按钮时连接 URL。

    package in.mosto.geeglobiab2bmobile;

    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.StatusLine;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;

    import android.os.AsyncTask;

    public class OnbuttonclickHttpPost extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            byte[] result = null;
            String str = "";
           // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://URL_HERE/login.php");

            try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("mobile", params[0]));
                    nameValuePairs.add(new BasicNameValuePair("password", params[1]));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);
                    StatusLine statusLine = response.getStatusLine();
                    if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                    result = EntityUtils.toByteArray(response.getEntity());
                    str = new String(result, "UTF-8");
                }
              } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }  
            return str;
        }

        /**
         * on getting result
         */
        @Override
        protected void onPostExecute(String result) {
            // something with data retrieved from server in doInBackground
            //Log.v("Response ", result);

            MainActivity main = new MainActivity();

            if(result.equals("NO_USER_ERROR")){
                main.showNewDialog("There is no user existed with the given details.");
            }else if(result.equals("FIELDS_ERR")){
                main.showNewDialog("Please enter username and password.");
            }else{
                main.startRecharge(result);
            }
        }
    }

查看我的 MainActivity 方法:

    OnbuttonclickHttpPost t = new OnbuttonclickHttpPost();
    t.execute(mobile.getText().toString(),pass.getText().toString());

public void startRecharge(String param){
    Intent inte = new Intent(MainActivity.this.getBaseContext(), StartRecharge.class);
    startActivity(inte);
}

public void showNewDialog(String alert){
    new AlertDialog.Builder(this)
        .setTitle("Please correct following error")
        .setMessage(alert)
        .setPositiveButton("Okay", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        })
        .show();
}

这里我遇到了一个错误。我不知道我的代码有什么问题。谁能帮帮我?

【问题讨论】:

  • HttpClient、HttpPost (Apache) 被窃听。异步任务也可以。你应该看看“Volley”肯定更稳定,更容易使用!

标签: java android android-asynctask http-post


【解决方案1】:

这是错误的。您不应创建活动类的实例。

 MainActivity main = new MainActivity();

活动由startActivity 启动。

你可以让你的 asynctask 成为你的活动类的内部类,并在onPostExecute 中更新 ui

或者使用接口

How do I return a boolean from AsyncTask?

编辑

   new OnbuttonclickHttpPost(ActivityName.this).execute(params);

在你的 asyctask 中

  TheInterface listener;

在构造中

  public OnbuttonclickHttpPost(Context context)
{

    listener = (TheInterface) context;
    c= context;

}    

界面

  public interface TheInterface {

    public void theMethod(String result);

     }

在 onPostExecute 中

    if (listener != null) 
  {
      listener.theMethod(result);
      }

在你的活动类中实现接口

     implements OnbuttonclickHttpPos.TheInterface

实现方法

     @Override
     public void theMethod(STring result) {
   // update ui using result
     }

【讨论】:

  • 感谢您的帮助。最后我发现了新事物。如果你能把你的答案写得更简洁一些,它可能对其他人有用。
  • @RadhakrishnaRayidi 我应该详细说明哪一部分?
  • 不,不,没关系。如果您可以添加更多详细信息,那就太好了:)
【解决方案2】:

这是错误的做法。最好的方法是,如果您在其他任何地方都不需要 AsyncTask,则将其设为您的 Activity 的内部类。然后它将可以访问您的Activity 的成员变量和函数,以便它可以轻松地更新您的onPostExecute() 中的变量。

如果您想将其保存为单独的文件,则可以使用interface 来监听回调。

This answer has an interface example在答案的底部。

【讨论】:

    【解决方案3】:

    只需更改您的 onPostExecute()

    @Override
    protected void onPostExecute(String result) {
        parseResponse(result);      
    }
    

    然后你就有了

    private void parseResponse(String result) {
        if(result.equals("NO_USER_ERROR")){
            showNewDialog("There is no user existed with the given details.");
        }else if(result.equals("FIELDS_ERR")){
            showNewDialog("Please enter username and password.");
        }else{
            startRecharge(result);
        }
    }
    

    这不是什么都不做

    MainActivity main = new MainActivity();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2010-11-26
      • 1970-01-01
      相关资源
      最近更新 更多