不能发表回应的AsyncTask到MainActivity [英] Can't post response from AsyncTask to MainActivity

查看:96
本文介绍了不能发表回应的AsyncTask到MainActivity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid应用程序的开发。请找我的$ C $下AsyncTask的用于连接一个网址,当用户点击了一个按钮。

I'm new to Android application development. Please find my code for AsyncTask for connecting a URL when a user clicked on a button.

    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方法:

See my MainActivity Methods:

    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();
}

在这里,我得到一个错误。我不知道什么是错我的code。任何一个可以帮帮我吗?

Here i'm getting an error. I don't know whats wrong with my code. Can any one please help me ?

推荐答案

这是错误的。你不应该创建活动类的一个实例。

This is wrong. You should not create an instance of your activity class.

 MainActivity main = new MainActivity();

活动是由 startActivity 启动。

您可以让您的AsyncTask在 onPostExecute

You can make your asynctask an inner class of your activity class and update ui in onPostExecute

或者使用一个接口

我如何返回一个布尔值从AsyncTask的?

修改

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

在你asyctask

In your asyctask

  TheInterface listener;

在construcotr

In the construcotr

  public OnbuttonclickHttpPost(Context context)
{

    listener = (TheInterface) context;
    c= context;

}    

接口

  public interface TheInterface {

    public void theMethod(String result);

     }

在onPostExecute

In onPostExecute

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

在您的活动类实现接口

     implements OnbuttonclickHttpPos.TheInterface

实施办法

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

这篇关于不能发表回应的AsyncTask到MainActivity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆