gpt4 book ai didi

java - Android 应用程序解析 JSON 数据错误?

转载 作者:行者123 更新时间:2023-12-02 06:45:56 24 4
gpt4 key购买 nike

我目前正在开发一个需要消耗大量 JSON 数据的应用程序,并且在使用 Jackson 解析器执行此操作时遇到问题。我的类中有以下代码,我需要解析数据:

HttpRequest request = HttpRequest.get("http://www.site.com/android/app/getAllUsers.php");

final Reader reader = request.reader();
final ObjectMapper mapper = new ObjectMapper();
final JsonFactory factory = mapper.getFactory();


class LoadAllUsers extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(VenuesListActivity.this);
pDialog.setMessage("Loading Users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

/**
* getting All products from url
* */
protected String doInBackground(String... args) {

try {
JsonParser jp = factory.createParser(reader);

while(jp.nextToken() == JsonToken.START_OBJECT) {

final User a = mapper.readValue(jp, User.class);

String fieldName = jp.getCurrentName();

if("users".equals(fieldName))
{

jp.nextToken();

while(jp.nextToken() != JsonToken.END_ARRAY)
{

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key => value
map.put(TAG_ID, a.ID);
map.put(TAG_DATA2, a.data1);
map.put(TAG_DATA3, a.data2);
...

// adding HashList to ArrayList
usersList.add(map);

}

}

}
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all venues
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
setListAdapter(adapter);
}
});

}

}

然后我在类中设置了 POJO,如下所示:

public class User {

String ID;
String data1;
String data2;
...

public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getData1() {
return data1;
}
public void setData1(String data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
...

}

下面我附上了我的 PHP 文件,该文件从我的数据库收集数据以在调用时传递:

<?php

// array for JSON response $response = array(); // include db connect class require_once __DIR__ . '/dbConnect.php'; // connecting to db $db = new DB_CONNECT(); // get all users from users table $result = mysql_query("SELECT * FROM accounts") or die(mysql_error()); // check for empty result if (mysql_num_rows($result) > 0) {
// looping through all results
// users node
$response["users"] = array();

while ($row = mysql_fetch_array($result)) {
// temp user array
$venue = array();
$venue["ID"] = $row["ID"];
$venue["data1"] = $row["data1"];
$venue["data2"] = $row["data2"];
...

// push single user into final response array
array_push($response["users"], $venue);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response); } else {
// no users found
$response["success"] = 0;
$response["message"] = "No users found";

// echo no users JSON
echo json_encode($response); } ?>

当我运行代码时,我希望一切正常,但是我收到以下错误消息:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.app.accs/com.app.accs.UsersListActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297)
at android.app.ActivityThread.access$700(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5328)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1125)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
at libcore.net.http.HttpURLConnectionImpl.getHeaderField(HttpURLConnectionImpl.java:139)
at com.github.kevinsawicki.http.HttpRequest.header(HttpRequest.java:2025)
at com.github.kevinsawicki.http.HttpRequest.parameter(HttpRequest.java:2120)
at com.github.kevinsawicki.http.HttpRequest.charset(HttpRequest.java:2230)
at com.github.kevinsawicki.http.HttpRequest.reader(HttpRequest.java:1822)
at com.app.accs.UsersListActivity.<init>(UsersListActivity.java:107)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)

我希望有人可以帮助我,因为 JSON 文件可能包含 15,000 个用户条目的数组,并且我想使用此流处理来提高性能。我也不确定,但这可能与目标 SDK 有关,因此下面是有关该应用程序的更多信息:

 android:minSdkVersion="11"
android:targetSdkVersion="17"

提前致谢。

<小时/>

****编辑* ****

<小时/>

您好,感谢您的回复,我一直在进一步研究这个问题,是的,这个 ASync 任务是通过下面的代码从 MainUI(onCreate) 执行的:

if(user == null || user.equals("All")){

// Loading users in Background Thread
new LoadAllUsers().execute();

}else{
// Load something else
}

这基本上查看传递到名为“user”的 View 的一条数据,如果用户对象为空或者其值为“All”,则我执行 LoadAllUsers 异步任务。如果我无法从主 UI 执行它,如何使用传递到此 View 的数据来执行此操作?

感谢您的帮助

最佳答案

您在崩溃报告中看到的 Caused by: android.os.NetworkOnMainThreadException 表明您正在主 UI 线程上执行此操作。不允许联网所以它正在杀死它。研究 AsycTasks 的正确使用。

此外,当您与对话框交互时,您应该位于主 UI 线程上。这也可能是一个失败点

请编辑您的问题以包含(或指定)您在 VenuesListActivity.java:107 中拥有的内容,因为崩溃报告也指出了这一点。

关于java - Android 应用程序解析 JSON 数据错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18638734/

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