我使用以下代码从json获取版本
webservice.java
public void getSingleResponse(final String url) {
class task extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String resp;
resp = "";
HttpClient httpClient = new DefaultHttpClient();
try {
Log.d("URL", "" + params[0]);
HttpResponse response = httpClient.execute(new HttpGet(
params[0]));
HttpEntity entity = response.getEntity();
Log.d("Entity ", "" + entity);
String responseString = EntityUtils.toString(entity,
"UTF-8");
resp = responseString;
GlobalVar.Version = resp;
Log.v("Global Version", "" + GlobalVar.Version);
} catch (Exception e) {
// TODO: handle exception
Log.v("HTTP:::::", "error" + e.getCause());
}
return GlobalVar.Version;
}
}
new task().execute(url);
}
MainActivity.java
public static String getMarketVersion() throws JSONException {
String version = "";
try {
webservice ws = new webservice();
String serverUrl = SERVER_URL + "/GetVersion";
Log.i(TAG, "Server URL" + serverUrl);
ws.getSingleResponse(serverUrl);
String response = GlobalVar.Version;
Log.v("Response :: ", "Version ::" + response);
JSONArray jArry = new JSONArray(response);
JSONObject jObj = jArry.getJSONObject(0);
version = jObj.getString("Version");
Log.v("Parsing ", "Version :: " + version);
return version;
} catch (Exception e) {
e.printStackTrace();
}
return version;
}
当我运行我得到版本空白的应用程序时,请参阅下面的日志
07-24 12:27:42.309: V/Response ::(4268): Version ::
07-24 12:27:43.389: V/Global Version(4268): [{"Version":"1.1.3"}]
但是当我调试时,我能够获得回复
07-24 12:06:01.699: V/Global Version(3122): [{"Version":"1.1.3"}]
07-24 12:06:07.349: V/Response ::(3122): Version ::[{"Version":"1.1.3"}]
07-24 12:08:12.019: V/Parsing(3122): Version :: 1.1.3
我不知道最近发生了什么 提前谢谢
答案 0 :(得分:1)
首先尝试了解,asyncTask如何工作? doInBackground
在您的UI线程的不同线程中工作,并且在执行asynctask后您必须等到它完成,意味着您需要覆盖asynctask的OnPostExecute
方法,然后您将获得您的版本,并且BTW你不应该在android中使用静态变量分享东西,android提供了各种方法来做到这一点
答案 1 :(得分:1)
正如Kapil Vats所说,你应该采取不同的方式。
例如,创建自己的类并扩展它
YourHttpGetter extends AsyncTask<String, Void, String>
使用某种方法创建一个接口
public void onTaskComplete(T result);
在YourHttpGetter类的构造函数中,传递将要实现该接口的ur类(Activity)的引用。
覆盖doInBackground
和onPostExecute
,在最后一个中,执行activityImplementingInterface.onTaskComplete(result);
当然,在你的活动实现界面的方法
@Override
public void onTaskComplete(String json) { do whatever you need }
答案 2 :(得分:0)
在AsyncTask类中添加方法。
protected void onPostExecute(String result){
GlobalVar.Version = result;
}