我从这个链接阅读并应用了一些东西:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? 但我在delegate.processFinish(result); 线上收到一个错误NullPointerException onPostExecute;我的代码有什么问题?这是代码:
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();
}
}