我的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 });
}
}
每次运行代码时,System.out.println(getFetchedJSON());
都不会返回任何内容,这意味着我的onPostExecute
根本没有实际更改任何变量的内容,是吗?
答案 0 :(得分:0)
我修改了我的代码。此代码将从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;
}
}
在Android Manifest中添加此行: -
<uses-permission android:name="android.permission.INTERNET" />
答案 1 :(得分:0)
方法downloadPage()
启动您的任务。此任务在其他线程中执行,并在您启动任务后立即打印结果,但任务尚未结束。试试这段代码:
公共类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 }); }
}