Android的解析JSON停留在获取任务 [英] Android Parse JSON stuck on get task
问题描述
我试图解析一些JSON数据。我的code是工作一段时间,我不知道我改成突然打破code。当我运行我的code我没有收到任何运行时错误或警告。我创建了一个新的AsyncTask和执行这一点。当我打电话获得()
在这个新的任务,在这条线的调试器和档位时间超过30分钟。我一直没能得到调试器或运行过程中来完成这个任务。
I am trying to parse some JSON data. My code was working for awhile, and I am not sure what I changed to suddenly break the code. When I run my code I am not receiving any runtime errors or warnings. I create a new AsyncTask and execute this. When I call .get()
on this new task, the debugger stalls on this line and takes more than 30 minutes. I have not been able to get the debugger or during run to complete this task.
JSON:
protected void setUp(Context context) {
_context = context;
getConfig();
}
// get config file
protected void getConfig() {
if (config != null)
return;
config = new Config();
String url = configURL;
AsyncTask<String, Integer, JSONObject> jsonTask = new DownloadJSONTask()
.execute(url);
JSONObject configItem = null;
try {
configItem = jsonTask.get(); //debugger pauses here
if (configItem == null)
return;
config.configVersion = configItem.getString("field_configversion");
config.currentAppVersion = configItem
.getString("field_currentappversion");
config.getSupportURL = configItem.getString("field_getsupporturl");
config.getCatalogURL = configItem.getString("field_getcatalogurl");
config.getDataVersion = configItem.getString("field_dataversion");
config.getDataUrl = configItem.getString("field_dataurl");
config.getDataApiKey = configItem.getString("field_dataapikey");
} catch (InterruptedException e) {
e.printStackTrace();
System.err.println("Download of config interrupted");
} catch (ExecutionException e) {
e.printStackTrace();
System.err.println("Download of config failed to execute");
} catch (JSONException e) {
e.printStackTrace();
}
cacheStaticData(_context);
}
DownloadJSONTask.java
DownloadJSONTask.java
package com.example.simplegraph;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
public class DownloadJSONTask extends AsyncTask<String, Integer, JSONObject> {
private HttpClient client = new DefaultHttpClient();
private HttpGet request;
private HttpResponse response;
DownloadJSONTask() {
super();
}
// tries to grab the data for a JSONObject
@Override
protected JSONObject doInBackground(String... urls) {
request = new HttpGet(urls[0]);
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
JSONObject json = new JSONObject(result);
instream.close();
return json;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// converts the InputStream to a string and add nl
private String convertStreamToString(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return sb.toString();
}
}
和HomeActivity.java
And HomeActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
new AddStringTask().execute();
}
class AddStringTask extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... unused) {
app = (EconApplication) getApplication();
getApp().setUp(HomeActivity.this);
HomeActivity.this.setUpDrawer();
return (null);
}
@Override
protected void onPostExecute(Void unused) {
setUpDataDisplay();
setUpGraphRange();
createTable();
createGraph(-1);
}
}
问题:为什么我的code被陷在获得()
QUESTION: Why is my code getting stuck on .get()?
推荐答案
AsyncTask.get()
阻塞调用者线程。使用 AsyncTask.execute()
代替。
AsyncTask.get()
blocks the caller thread. Use AsyncTask.execute()
instead.
公众最终结果的get()
在API级别3
如有必要,等待计算完成,然后检索
其结果。
Waits if necessary for the computation to complete, and then retrieves its result.
返回计算结果。
从
请尝试以下
new DownloadJSONTask(ActivityName.this).execute(url);
在您的DownloadJSONTask
In your DownloadJSONTask
在construcotr
In the construcotr
TheInterface listener;
public DownloadJSONTask(Context context)
{
listener = (TheInterface) context;
}
接口
public interface TheInterface {
public void theMethod(ArrayList<String> result); // your result type
}
在你的 doInbackground
返回结果。我假设其类型为String的ArrayList。更改数组列表,以什么适合您的要求。
In your doInbackground
return the result. I am assuming its ArrayList of type String. Change the arraylist to what suits your requirement.
在你的 onPostExecute
if (listener != null)
{
listener.theMethod(result); // result is the ArrayList<String>
// result returned in doInbackground
// result of doInbackground computation is a parameter to onPostExecute
}
在您的活动类实现接口
public class ActivityName implements DownloadJSONTask.TheInterface
然后
@Override
public void theMethod(ArrayList<String> result) { // change the type of result according yo your requirement
// use the arraylist here
}
编辑:另类
您可以让您的AsyncTask的一个内部类的活动类的。在 doInbackground结果
计算对 onPostExecute
的参数。返回结果 doInbackground
。更新UI在 onPostExecute
。
You can makes your asynctask an inner class of your activity class. The result on doInbackground
computation is a parameter to onPostExecute
. Return result in doInbackground
. Update ui in onPostExecute
.
这篇关于Android的解析JSON停留在获取任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!