[英]How can i to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
I read and apply something from this link: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? 我从这个链接中读取并应用了一些东西: 如何将OnPostExecute()的结果导入主活动,因为AsyncTask是一个单独的类? but I get an error NullPointerException onPostExecute on the line delegate.processFinish(result);
但是我在行delegate.processFinish(result)上得到一个错误NullPointerException onPostExecute; What is the problem in my code?
我的代码有什么问题? Here is the code:
这是代码:
public class MainActivity extends Activity implements AsyncResponse{
ProductConnect asyncTask =new ProductConnect();
public void processFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
Log.v(TAG, output);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
final Intent i=new Intent(MainActivity.this, second.class);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new ProductConnect().execute(true);
startActivity(i);
//startActivity(new Intent(MainActivity.this, second.class));
}
});
}
// START DATABASE CONNECTION
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
@Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
@Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(result);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Lütfen Bekleyiniz");
pd.setMessage("Authenticating..");
pd.show();
}
}
You initialize your variable to null
您将变量初始化为
null
public AsyncResponse delegate=null;
so naturally it will give NPE
when you try to use it. 所以当你尝试使用它时,它会自然地给出
NPE
。 You give it a value in your Activity
so you could pass that to the constructor of your AsyncTask
and initialize it to that object. 您在
Activity
为它赋值,这样您就可以将它传递给AsyncTask
的构造函数并将其初始化为该对象。
Your are starting a new AsyncTask in this line: 您正在此行中启动一个新的AsyncTask:
new ProductConnect().execute(true);
you should execute your asyncTask change that line with this: 你应该执行你的asyncTask更改:
asyncTask.execute(true);
I think the best way to do this is using interfaces.. Create a listener for this. 我认为最好的方法是使用接口..为此创建一个监听器。
[]'s []的
you can access asynctask() method when creating new object from it. 从中创建新对象时,可以访问asynctask()方法。 sample:
样品:
LoginSyncProvider syncProvider = (LoginSyncProvider) new LoginSyncProvider(){
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//TODO write something here
}
}
}.execute();
You've to pass context to that AsyncTask. 您必须将上下文传递给AsyncTask。
Then, on postExecute, cast context to your Activity. 然后,在postExecute上,将上下文转换为您的Activity。
Example: 例:
((MyActivity)context).doSomethingWithResults(resultOfAsyncTask);
Edit: 编辑:
Your Activity: 你的活动:
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
new MyAsyncTask(this).execute();
}
public void sayHello(String name){
Log.d("log","hello "+name+"!!!");
}
}
Your asynctask: 你的asynctask:
class MyAsyncTask extends AsyncTask<String,String,String>{
Context context;
public AutoPassarImatges(Context cont) {
super();
this.context = cont;
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... params) {
[.......]
return null;
}
@Override
protected void onPostExecute(String result) {
((MyActivity)context).sayHello(result);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.