Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference

Tags:

java

android

Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference this Exception is thrown by JRE please help!!

here is the class

package com.example.MovieMania.fragmentTv;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;





import com.example.MovieMania.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

public class BackgroundTaskTv extends AsyncTask<String, Void, String[]> {

    final String DEF_BASE_URL = "http:api.themoviedb.org/3/tv/popular?[api_key]";

    private final Context context;

    public BackgroundTaskTv(Context context) {
        this.context = context;
    }

    public static String JsonStr;  // so that JSONstring can be used by other activities

    private String[] jsonParse(String movieJsonStr) throws JSONException {

        final String POSTER_PATH = "poster_path"; // JSON STRING PARSING AND
                                                    // RETURN
                                                    // POSTER PATHS

        JSONObject jsonObj = new JSONObject(movieJsonStr);
        JSONArray resultArray = jsonObj.getJSONArray("results");

        int len =resultArray.length();
        String[] posters = new String[len];
        for (int i = 0; i < len; i++) {
            posters[i] = resultArray.getJSONObject(i).getString(POSTER_PATH);
        }

        for (String res : posters)
            Log.v(POSTER_PATH, res);

        return posters;

    }

    @Override
    protected String[] doInBackground(String... params) {



        String movieJsonStr = null;
        InputStream inputStream = null;


        String FINAL_URL=DEF_BASE_URL;
        ImageAdapterTv.poster_paths.clear();

        BufferedReader reader = null;
        HttpURLConnection urlConnection = null; // READ THE INPUTSTREAM AND
                                                // GET THE JSONSTRING
        try {
            URL url = new URL(FINAL_URL);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it
                // won't affect parsing)
                // But it does make debugging a *lot* easier if you print
                // out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty. No point in parsing.
                return null;
            }

            movieJsonStr = buffer.toString();
            JsonStr=movieJsonStr;

            Log.v("Tv string: ", movieJsonStr);
        } catch (Throwable e) {
            Log.e("backgroundtask", "EXCEPTION", e);
        } finally {
            urlConnection.disconnect();
            try {
                reader.close();
                inputStream.close();
            } catch (IOException e) {
                Log.e("READER.CLOSE()", e.toString());
            }
        }

        try {
            return jsonParse(movieJsonStr);
        } catch (JSONException e) {
            Log.e("BACKGROUNDTASK", "EXCEPTION FROM jsonParse()", e);
        }

        return null;
    }

    @Override
    protected void onPostExecute(String[] result) {
        if (ImageAdapterTv.poster_paths.isEmpty()) {
            for (String s : result) {
                ImageAdapterTv.poster_paths.add(s);
            }
        }

        final Activity activity = (Activity) context;
        activity.runOnUiThread(new Runnable() {
            @Override
            // this code is written so that the grid view is populated after
            // backgroundTask
            public void run() { // produce results so that there is no blank
                                // screen on launch
                GridView grid = (GridView) activity.findViewById(R.id.gridview_tv);
                grid.setAdapter(new ImageAdapterTv(context));

                grid.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        String path=ImageAdapterTv.poster_paths.get(position);
                        Intent intent=new Intent(context,DetailActivityTv.class);
                        intent.putExtra("poster", path);
                        intent.putExtra("POSITION", position);
                        activity.startActivity(intent);
                        }
                });

                }
        });
    }

}

It is a background thread which is getting the json response from an api I dont know why this exception is thrown.

like image 500
Nitish Chopra Avatar asked Feb 08 '23 19:02

Nitish Chopra


1 Answers

if exception happened before initializing the reader it will lead to this error because reader.close() is placed in finally block. It's good practice to always check for null before closing resources in finally

if(reader != null)
    reader.close();
if(inputStream != null)
    inputStream.close();
like image 98
Ahmed Sayed Avatar answered Feb 11 '23 16:02

Ahmed Sayed