【发布时间】:2016-03-11 06:27:02
【问题描述】:
我想将 3 个字符串从 doInBackground 发送到 onPostExecute。
我设法获取了数据,并且可以在日志中看到它们。现在如何在 doInBackground 完成执行后使用存储在 Strings 中的数据。
这是我的代码。
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://example.com/test.php";
// JSON Node names
private static final String tag_info = "info";
private static final String tag_success = "Success";
private static final String tag_message = "message";
private static final String tag_output = "output";
// contacts JSONArray
JSONArray info = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling async task to get json
new fetchInfo().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class fetchInfo extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
String success = c.getString(tag_success);
String message = c.getString(tag_message);
String output = c.getString(tag_output);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(success + " " + message + " " + output); // I want to print them here
}
}
}
【问题讨论】:
-
制作模型类并通过
-
你能把代码改成在这里贴出来