-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

13
  • Are you getting the null pointer exception because you are not getting any data from the url? or the reason is different!! Commented Oct 30, 2016 at 2:49
  • what does the Null Pointer Exception say? Commented Oct 30, 2016 at 3:05
  • @ginomempin review edit for Null Pointer exception Commented Oct 30, 2016 at 3:41
  • 1
    And, no, your JSON is not valid Commented Oct 30, 2016 at 8:04
  • 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 Commented Oct 30, 2016 at 14:00

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.