gpt4 book ai didi

java - 安卓异步任务 : How to handle the return type

转载 作者:行者123 更新时间:2023-11-30 03:39:48 25 4
gpt4 key购买 nike

我正在开发一个执行 http POST 请求 的 Android 应用程序,我遵循的教程导致了 android.os.NetworkOnMainThreadException

原始代码是这样的。

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}

并且用这一行调用了这个类。

JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);

将其更改为 AsyncTask 类后,代码如下所示。

class JSONParser extends AsyncTask<String, Void, JSONObject>{

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// variables passed in:
String url;
List<NameValuePair> params;

// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}

@Override
protected JSONObject doInBackground(String... args) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();


} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;
}

@Override
protected void onPostExecute(JSONObject jObj) {
return;
}
}

我的问题是,如何从这个新的 AsyncTask 类返回一个 JSONObject?我可以看到 jObjdoInBackground(),但我不确定它返回到哪里。

我需要修改什么或者我需要如何调用我的新 JSONParser 类以便它返回 JSONObject

最佳答案

看看这段代码,它可能会让您深入了解如何处理 JSON 对象的解析。我现在只是发布 onPostExecute 函数,因为您似乎已经正确计算了所有其他函数。

至于您对 doInBackground 中的数据对象返回位置的疑问,它会自动发送到 onPostExecute,您可以在其中进一步解析它。

            @Override
protected void onPostExecute(JSONObject result)
{
try
{
JSONObject data = result.getJSONObject("data");
// whatever your JSON tag may be, in this case its data.

if (data.isNull("data"))
{
// action to handle null JSON object.
}
else
{
JSONArray jarray = data.getJSONArray("data");
int len=jarray.length();
for (int i = 0; i < jarray.length(); i++)
{
JSONObject obj = (JSONObject) jarray.get(i);

String instanceName = obj.getString("instanceName");
//extract data by whatever tag names you require, in this case instanceName.
}
}
}
catch (JSONException je)
{
je.printStackTrace();
Log.d(TAG, "Error: " + je.getMessage());
}
}
}

关于java - 安卓异步任务 : How to handle the return type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15963181/

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