Can#39;t post response from AsyncTask to MainActivity(无法将响应从 AsyncTask 发布到 MainActivity)
问题描述
我是 Android 应用程序开发的新手.请找到我的 AsyncTask 代码,用于在用户单击按钮时连接 URL.
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();
}
这里出现错误.我不知道我的代码有什么问题.有人可以帮我吗?
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();
Activity 由 startActivity
启动.
Activity is started by startActivity
.
你可以让你的异步任务成为你活动类的内部类并在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);
在你的异步任务中
TheInterface listener;
在构造器中
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);
}
在你的活动类中实现接口
In your activity class implement the interface
implements OnbuttonclickHttpPos.TheInterface
实现方法
@Override
public void theMethod(STring result) {
// update ui using result
}
这篇关于无法将响应从 AsyncTask 发布到 MainActivity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法将响应从 AsyncTask 发布到 MainActivity
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01