我的 Android 应用程序需要一些基本数据才能运行。此数据是使用 JSON 从服务器下载的。在 Xcode 中,我只是使用了 sendsynchronous 请求,但我注意到当我在主 ui 上进行网络连接时,Eclipse 给了我一个错误。在 asynctask 上找到了很多东西,但我希望我的应用程序等到下载所需的数据(同步?)。
我尝试使用 asynctask .execute().get() 并在 onPostExecute 中设置变量,但是当我返回变量时,我得到了 NullPointerException。有人知道如何进行这项工作吗?在应用程序运行之前我真的需要这些数据,所以我希望我的应用程序等到数据下载完成。
MainActivity 调用这个:
SingletonClass appIDSingleton = SingletonClass.getInstance();
this.ID = appIDSingleton.getAppID();
单例类:
public String getAppID() {
try {
new DownloadAppID().execute(APP_ID_URL).get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return AppID; //AppID is still NULL (because the download isnt finished yet?)
}
private class DownloadAppID extends AsyncTask<String, Void, String> {
@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
protected void onPostExecute(String result) {
System.out.println(result);
AppID = result;
}
}