0

我目前正在开发一个需要消耗大量 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"

提前致谢。


** * *编辑* ** * *


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

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

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

}else{
       // Load something else
}

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

谢谢您的帮助

4

3 回答 3

2

您在Caused by: android.os.NetworkOnMainThreadException该崩溃报告中看到的内容指向您在主 UI 线程上执行此操作的事实.. 不允许联网,所以它正在杀死它。查看正确使用 AsycTasks。

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

请编辑您的问题以包含(或指定)您所拥有的内容,VenuesListActivity.java:107因为这也是崩溃报告所指向的内容。

于 2013-09-05T14:18:04.510 回答
0

就像 MrTristan 所说,您正在 UI 上运行网络任务Thread。网络任务往往很长,因此 Android 要求您在后台线程上执行它们。您的代码似乎用于AsyncTask解析 JSON 数据,但不用于执行网络任务。此外,您不需要使用runOnUiThread()ononPostExecute()因为onPostExecute()已经在 UI 上运行Thread

于 2013-09-05T14:33:24.070 回答
0

更改这行代码:

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(UsersListActivity.this);
        ......
    }
......


除此之外,不要在 UI 线程上进行网络调用并单独进行Async ClassesServices执行与网络调用相关的所有任务。

于 2013-09-05T15:14:40.510 回答