我在MainActivity中从服务器下载JSON内容,并将JSON从MainActivity传递到ListActivity,这里的问题是我在后端服务器(即从中获取数据的Php)中添加了10秒的睡眠时间。因为,响应将延迟,我希望屏幕打开并等待,直到响应到来并移动到下一个屏幕。
但现在的情况是,屏幕完全变白/变黑,直到收到响应并加载ListActivity,这里的问题是MainActivity永远不可见。以下是相同的代码:
主要活动
JSONData jsonData = new JSONData();
String jsonList = jsonData.fetchList();
Intent intent = new Intent(getApplicationContext(),ListActivity.class);
intent.putExtra("jsonList",jsonList);
startActivity(intent);
finish();
JSON数据类
public String fetchList() {
try {
String list = new DownloadJSONData().execute(listURL).get().toString();
return list;
} catch (Exception e) {
return "";
}
}
private class DownloadJSONData extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}