在主UI上执行网络进程



我的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;
}
}

您需要了解getAppID方法不能返回异步计算的结果。

例如,您可以为异步任务提供一个监听器,以便在应用程序ID可用时发出通知:

SingletonClass appIDSingleton = SingletonClass.getInstance();
appIDSingleton.getAppID(new AppIdDownloadListener() {
@Override
public void appIDAvailable(String appId) {
this.ID = appId; 
}
});

public void getAppID(AppIdDownloadListener listener) {
try {
new DownloadAppID(listener).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();
}
}
public interface AppIdDownloadListener {
public void appIDAvailable(String appId);
}
private class DownloadAppID extends AsyncTask<String, Void, String> {
private AppIdDownloadListener listener;
public DownloadAppID(AppIdDownloadListener listener) {
this.listener = listener;
}
@Override
protected String doInBackground(String... params) {
/* Your stuff here */
}
@Override
protected void onPostExecute(String result) {
System.out.println(result);
listener.appIDAvailable(result);
}
}

最新更新