Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法将响应从AsyncTask发布到MainActivity_Java_Android_Android Asynctask_Http Post - Fatal编程技术网

Java 无法将响应从AsyncTask发布到MainActivity

Java 无法将响应从AsyncTask发布到MainActivity,java,android,android-asynctask,http-post,Java,Android,Android Asynctask,Http Post,我是Android应用程序开发新手。请查找用户单击按钮时用于连接URL的AsyncTask的代码 package in.mosto.geeglobiab2bmobile; import java.io.IOException; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.List; import org.apache.http.H

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

    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 main = new MainActivity();
活动由startActivity启动

您可以将asynctask设置为活动类的内部类,并在onPostExecute中更新ui

或者使用一个接口

     implements OnbuttonclickHttpPos.TheInterface
编辑

在你的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);
      }
@Override
protected void onPostExecute(String result) {
    parseResponse(result);      
}
在活动类中实现接口

     implements OnbuttonclickHttpPos.TheInterface
实施该方法

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

这是错误的做法。最好的方法是,如果您在其他任何地方都不需要该异步任务,那么将其作为活动的内部类。然后,它可以访问活动和函数的成员变量,以便在onPostExecute中轻松更新变量

如果你想把它作为一个单独的文件保存,那么你可以使用一个接口来监听回调


在答案的底部。

只需更改onPostExecute即可

    if (listener != null) 
  {
      listener.theMethod(result);
      }
@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=新的MainActivity


HttpClient、HttpPost和Apache都有错误。异步任务也可以是。你应该看看凌空截击,绝对更稳定,更容易使用!!谢谢你的帮助。最后我发现了新的东西。如果你能把你的答案说得更简短一些,它对其他人会很有用。@RadhakrishnaRayidi我应该详细说明哪一部分?不,不,很好。如果您可以添加更多细节,那将非常好: