从URL

时间:2016-10-30 02:47:53

标签: android json listview android-asynctask nullpointerexception

我有一个JSON文件并将其上传到我的服务器上,然后我在我的Android应用程序中获取它。但每次我尝试调试我的应用程序时,它都会在AsyncTask类中与空指针异常崩溃,并给我这个错误:

10-30 05:07:46.268 8710-9073/com.example.prof_mohamedatef.listview E/AndroidRuntime: 
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
  at android.os.AsyncTask$3.done(AsyncTask.java:299)
  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
  at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
  at com.example.prof_mohamedatef.listview.androidlistviewactivity$FetchUsersDesires.doInBackground(androidlistviewactivity.java:159)
  at com.example.prof_mohamedatef.listview.androidlistviewactivity$FetchUsersDesires.doInBackground(androidlistviewactivity.java:84)
  at android.os.AsyncTask$2.call(AsyncTask.java:287)
  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
  at java.lang.Thread.run(Thread.java:856) 

我确信我的设备已连接到互联网。我采用 url ,可能是错误构建的,可能需要问号或任何其他符号,或者我的json文件可能是hasn'正确构造。请查看我的网址:https://yourbest-online.com/images/xml_files/Desires.json和我的json代码:

{"page":1,"Desires": [{
        "hotels": {
            "id": "1",
            "title": "hotels booking",
            "thumb_url": "https://yourbest-online.com/images/xml_files/hotels.png"
        },
        "Aviation": {
            "id": "2",
            "title": "Aviation Tickets Booking",
            "thumb_url": "https://yourbest-online.com/images/xml_files/aviation.png"
        }
],"total_results":2,"total_pages":1}

这是我的所有AsyncTask类,包括总是出现问题的doInBackground方法:

    public class FetchUsersDesires extends AsyncTask<String, Void, ArrayList<OptionsEntity>> {

    private final String LOG_TAG = FetchUsersDesires.class.getSimpleName();

    private ArrayList<OptionsEntity> getUsersDesiresFromJson(String UsersDesires)
            throws JSONException {

        UsersDesiresJson = new JSONObject(UsersDesires);
        UsersDesiresJsonAray = UsersDesiresJson.getJSONArray(main_List);

        list.clear();
        for (int i = 0; i < UsersDesiresJsonAray.length(); i++) {

            // Get the JSON object representing a movie per each loop
            oneOptionData = UsersDesiresJsonAray.getJSONObject(i);

            ID_STRING = oneOptionData .getString(ID);
            TITLE_STRING = oneOptionData .getString(TITLE);
            Image_URL_STRING = oneOptionData .getString(Image_URL);

            mAdapter=null;
            OptionsEntity entity = new OptionsEntity(Image_URL_STRING, TITLE_STRING);
            list.add(entity);
        }

        return list;
    }

    @Override
    protected ArrayList<OptionsEntity> doInBackground(String... params) {

        String UsersDesires_JsonSTR = null;

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        if (params.length == 0) {
            return null;
        }
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                UsersDesires_JsonSTR = null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }
            if (buffer.length() == 0) {
                return null;
            }

            UsersDesires_JsonSTR = buffer.toString();

            Log.v(LOG_TAG, "Users Desires String: " + UsersDesires_JsonSTR);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error here Exactly ", e);

            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }
        try {
            return getUsersDesiresFromJson(UsersDesires_JsonSTR);
        } catch (JSONException e) {
            Log.e(LOG_TAG, "didn't got Users Desires from getJsonData method", e);

            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onPostExecute(ArrayList<OptionsEntity> result) {
        if (result != null&& getApplicationContext()!=null) {
            mAdapter = new LazyAdapter(getApplicationContext(),R.layout.list_row, result);
            listView.setAdapter(mAdapter);
        }
    }
}

注意,现在Connection正在以最佳方式运行,但 JSON异常会显示:“ ID无值”和json android studio中的字符串变量值如下所示:“{”page“:1,”Desires“:[{         “酒店”:{             “id”:“1”,             “title”:“酒店预订”,             “thumb_url”:“https://yourbest-online.com/images/xml_files/hotels.png”         },         “航空”:{             “id”:“2”,             “标题”:“航空门票预订”,             “thumb_url”:“https://yourbest-online.com/images/xml_files/aviation.png”         } }], “TOTAL_RESULTS”:2 “TOTAL_PAGES”:1} “ 该值看起来包含每个空格的多个\ n \ t \ t \ t符号,我认为这是导致问题的原因,请为此目的提供任何建议。

您的帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

在此处查看oneOptionData的值。它没有ID密钥。它有酒店或航空。

ID_STRING = oneOptionData .getString(ID) ;

所以,这会因JSON解析异常而崩溃。您的解析异常会导致您返回null。

您永远不应该从AsyncTask返回空列表来返回数据列表。您应该返回一个空列表,并在/出现时适当地记录解析错误

获得更好的json格式。

 "Desires": [{
        "id": "1",
        "category":"hotels",
        "title": "hotels booking",
        "thumb_url": "https://yourbest-online.com/images/xml_files/hotels.png"
    },
    {
        "id": "2",
        "category":" Aviation", 
        "title": "Aviation Tickets Booking",
        "thumb_url": "https://yourbest-online.com/images/xml_files/aviation.png"
    }

除此之外:JSON文件位于名为xml_files的目录中?在xml_files下有一个名为images的目录?如果这是您的服务器,我建议您重新组织整个代码,而是使用实际的REST API生成JSON而不是托管纯文本文件