gpt4 book ai didi

java - Android Parse JSON 卡在获取任务上

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:05 29 4
gpt4 key购买 nike

我正在尝试解析一些 JSON 数据。我的代码工作了一段时间,但我不确定我更改了什么突然破坏了代码。当我运行我的代码时,我没有收到任何运行时错误或警告。我创建一个新的 AsyncTask 并执行它。当我在这个新任务上调用 .get() 时,调试器停在这条线上并花费了 30 多分钟。我无法获得调试器或在运行期间完成此任务。

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);
}

下载JSONTask.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

@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);
}
}

问题:为什么我的代码卡在 .get() 上?

最佳答案

AsyncTask.get() 阻塞调用线程。请改用 AsyncTask.execute()

public final Result get ()

在 API 级别 3 中添加

Waits if necessary for the computation to complete, and then retrieves its result.

Returns The computed result.

绘图自

How do I return a boolean from AsyncTask?

试试下面的

  new DownloadJSONTask(ActivityName.this).execute(url);

在你的 DownloadJSONTask 中

在构造函数中

    TheInterface listener;
public DownloadJSONTask(Context context)
{

listener = (TheInterface) context;

}

界面

   public interface TheInterface {

public void theMethod(ArrayList<String> result); // your result type

}

在您的doInbackground 中返回结果。我假设它的 ArrayList 类型为 String。将数组列表更改为适合您要求的内容。

在你的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
}

在你的 Activity 类中实现接口(interface)

 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
}

编辑:替代

您可以使异步任务成为 Activity 类的内部类。 doInbackground 计算的结果是 onPostExecute 的参数。在 doInbackground 中返回结果。在 onPostExecute 中更新 ui。

关于java - Android Parse JSON 卡在获取任务上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18129191/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com