[英]Using setter method in AsyncTask onPostExecute
My onPostExecute
method needs to return a result back to onCreate()
so it can do stuff with it but I'm struggling to get there. 我的onPostExecute
方法需要将结果返回给onCreate()
以便它可以做一些事情,但是我正努力到达那里。
public class ScheduleList extends Activity {
public String url = "http://www.bbc.co.uk/bbcnews/programmes/schedules/today.json";
private DownloadJSON mTask = null;
public static String fetchedJSON = "";
public static String getFetchedJSON() {
return fetchedJSON;
}
public static void setFetchedJSON(String fetchedJSON) {
ScheduleList.fetchedJSON = fetchedJSON;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_list);
// Show the Up button in the action bar.
setupActionBar();
TextView tvNotice = (TextView) findViewById(R.id.schedulePreamble);
tvNotice.setText("Well, hello there...");
System.out.println("Hello");
downloadPage();
System.out.println(getFetchedJSON());
}
public class DownloadJSON extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(
content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
public void onPostExecute(String result) {
setFetchedJSON(result);
}
}
private void downloadPage() {
if (mTask != null && mTask.getStatus() != DownloadJSON.Status.FINISHED) {
mTask.cancel(true);
}
mTask = (DownloadJSON) new DownloadJSON().execute(new String[] { url });
}
}
Every time I run the code, System.out.println(getFetchedJSON());
每次我运行代码时, System.out.println(getFetchedJSON());
returns nothing which means my onPostExecute
hasn't actually changed the contents of any variable at all, has it? 什么都不返回,这意味着我的onPostExecute
实际上根本没有更改任何变量的内容,对吗?
I have modified my code.This code will get your JSON from Url and convert it into a String and a Json Objecct This will work now 我已经修改了代码,该代码将从Url获取JSON并将其转换为String和Json Objecct
public class MainActivity extends Activity {
InputStream is = null;
JSONObject jObj = null;
String json = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
String url = "http://api.androidhive.info/contacts/";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Add this line in Android Manifest :- 在Android清单中添加以下行:
<uses-permission android:name="android.permission.INTERNET" />
The method downloadPage()
launch your task. 方法downloadPage()
启动您的任务。 This task is executed in other thread and immediately after you launch your task you want to print the result but the task is not over yet. 此任务在其他线程中执行,并且在启动任务后立即要打印结果,但任务尚未结束。 Try this code : 试试这个代码:
public class ScheduleList extends Activity { 公共类ScheduleList扩展Activity {
public String url = "http://www.bbc.co.uk/bbcnews/programmes/schedules/today.json"; private DownloadJSON mTask = null; public static String fetchedJSON = ""; public static String getFetchedJSON() { return fetchedJSON; } public static void setFetchedJSON(String fetchedJSON) { ScheduleList.fetchedJSON = fetchedJSON; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule_list); // Show the Up button in the action bar. setupActionBar(); TextView tvNotice = (TextView) findViewById(R.id.schedulePreamble); tvNotice.setText("Well, hello there..."); System.out.println("Hello"); downloadPage(); } public void printFetchedJSON() { System.out.println(getFetchedJSON()); } public class DownloadJSON extends AsyncTask<String, Integer, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } @Override protected String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader( content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } @Override public void onPostExecute(String result) { setFetchedJSON(result); printFetchedJSON(); } } private void downloadPage() { if (mTask != null && mTask.getStatus() != DownloadJSON.Status.FINISHED) { mTask.cancel(true); } mTask = (DownloadJSON) new DownloadJSON().execute(new String[] { url }); }
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.