-4

I have a JSON file and uploaded it on my server, then I fetch it in my android app. But every time i try to debug my app, it crashes with Null Pointer Exception in the AsyncTask class and gives me this error:

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) 

I am assured that my devices is connected to the internet. I adopt in url which may be built wrongly, it may requires question mark ? or any other symbols, or my json file may be hasn't constructed correctly. Please review my url : https://yourbest-online.com/images/xml_files/Desires.json and my json code:

{"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}

This is all of my AsyncTask Class including doInBackground method where the problem always occur :

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

Note , Connection now is running on the best way, but JSON Exception appear says : "No Value for id" and the json String variable value in android studio looks like that : "{"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} " the value looks like to include multiple \n\t\t\t symbols for each space, i think this my causing the problem, any advise for this purpose please.

your help will be appreciated. thank you

Mohamed Atef
  • 69
  • 13
  • Are you getting the null pointer exception because you are not getting any data from the url? or the reason is different!! – Wasi Ahmad Oct 30 '16 at 02:49
  • what does the Null Pointer Exception say? – Gino Mempin Oct 30 '16 at 03:05
  • @ginomempin review edit for Null Pointer exception – Mohamed Atef Oct 30 '16 at 03:41
  • @WasiAhmad yes the null pointer exception reason is that there are no data coming via url – Mohamed Atef Oct 30 '16 at 03:44
  • Since your url is working fine, there should not be any problem. Can you check the first answer from here http://stackoverflow.com/questions/7467568/parsing-json-from-url to read the url as text? then try to parse the json object. – Wasi Ahmad Oct 30 '16 at 03:55
  • I think your json is invalid, it's missing a closing `}` before the closing `]` (to match the opening `{` in `"Desires": [{`. I don't know what's at "androidlistviewactivity.java:159" that's throwing the NPE, but it could be that your parsed JSON is null. – Gino Mempin Oct 30 '16 at 04:24
  • It's nice that you gave the logcat, but we have to see a [mcve] in order to help you. We can't see your code at all. – OneCricketeer Oct 30 '16 at 08:03
  • 1
    And, no, your JSON [is not valid](http://jsonlint.com/) – OneCricketeer Oct 30 '16 at 08:04
  • @ginomempin you can review my AsyncTask Class and doInbackground method again after my recent edit – Mohamed Atef Oct 30 '16 at 13:20
  • @cricket_007 you can review my AsyncTask Class and doInbackground method again after my recent edi – Mohamed Atef Oct 30 '16 at 13:20
  • 1
    You didn't edit your JSON.. Did you? It's still invalid. Here's a suggestion: Use Retrofit with the Gson converter or OkHttp, or Volley, to do your network requests. There's not much reason to use HttpURLConnection in my opinion. Especially if you are having lots of JSON files to deal with – OneCricketeer Oct 30 '16 at 14:00
  • can you mark lines 159 and 84 in `androidlistviewactivity.java` (edit the question and put some mark next to the lines – Yazan Oct 30 '16 at 14:26
  • @cricket_007 after editing json file, it successfully connected, but gave me JSON Exception "No value for id" at the hotels node. please, Review my post edit at this point – Mohamed Atef Oct 30 '16 at 14:45

1 Answers1

1

Check out the value of oneOptionData here. It doesn't have an ID key. It has either hotels or aviation.

ID_STRING = oneOptionData .getString(ID) ;

So, that's going to crash with a JSON parsing exception. Your parsing exception causes you to return null.

You should never return a null list from an AsyncTask meant to return a list of data. You should instead return an empty list, and appropriately log the parsing error if/when it occurs

Get a better json format.

 "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"
    }

Aside: a JSON file is in a directory called xml_files? And there is a directory called xml_files under images? If this is your server, I'd suggest also reorganization of your overall code, and instead use an actual REST API to generate your JSON instead of hosting plain text files

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245