1

I am trying to display JSON data, in a ListView, that I have parsed but I get the following error when I try to run the app.

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

Here is the stack trace.

 05-14 22:06:30.169  14034-14034/com.example.jsonparsing_v2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jsonparsing_v2, PID: 14034
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337)
    at android.widget.ListView.setAdapter(ListView.java:491)
    at com.example.jsonparsing_v2.MainActivity$JSONTask.onPostExecute(MainActivity.java:131)
    at com.example.jsonparsing_v2.MainActivity$JSONTask.onPostExecute(MainActivity.java:49)
    at android.os.AsyncTask.finish(AsyncTask.java:651)
    at android.os.AsyncTask.-wrap1(AsyncTask.java)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

My code.

package com.example.jsonparsing_v2;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.jsonparsing_v2.models.ArticleModel;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView lvArticles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lvArticles = (ListView)findViewById(R.id.lvArticles);
    }

    public class JSONTask extends AsyncTask<String,String,List<ArticleModel>>{
        @Override
        protected List<ArticleModel> doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                connection =(HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));
                StringBuffer buffer = new StringBuffer();

                String line = "";
                while ((line = reader.readLine())!= null){
                    buffer.append(line);
                }

                String finalJson = buffer.toString();

                JSONObject parentObject = new JSONObject(finalJson);
                JSONArray parentArray =  parentObject.getJSONArray("");

                List<ArticleModel> articleModelList = new ArrayList<>();

                for (int i=0;i<parentArray.length(); i++) {
                    JSONObject finalObject = parentArray.getJSONObject(i);
                    ArticleModel articleModel = new ArticleModel();
                    articleModel.setId(finalObject.getString("id"));
                    articleModel.setSectionId(finalObject.getString("sectionId"));
                    articleModel.setWebPublicationDate(finalObject.getInt("webPublicationDate"));
                    articleModel.setWebTitle(finalObject.getString("webTitle"));
                    articleModel.setWebUrl(finalObject.getString("webUrl"));
                    articleModel.setApiUrl(finalObject.getString("apiUrl"));
                    articleModel.setSectionName(finalObject.getString("sectionName"));
                    articleModel.setHeadline(finalObject.getString("headline"));
                    articleModel.setThumbnail(finalObject.getString("thumbnail"));

                    // adding the final object in the list
                    articleModelList.add(articleModel);
                }
                return articleModelList;
            }
            catch(MalformedURLException e) {
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
                try {
                    if (reader != null){
                        reader.close();
                    }
                }
                catch (IOException e){
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<ArticleModel> result) {
            super.onPostExecute(result);
            ArticleAdapter adapter = new ArticleAdapter(getApplicationContext(), R.layout.row, result);
            lvArticles.setAdapter(adapter);
        }
    }

    public class ArticleAdapter extends ArrayAdapter{
        private List<ArticleModel> articleModelList;
        private int resource;
        private LayoutInflater inflater;

        public ArticleAdapter(Context context, int resource, List<ArticleModel> objects) {
            super(context, resource, objects);
            articleModelList = objects;
            this.resource = resource;
            inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if(convertView == null){
                convertView = inflater.inflate(resource, null);
            }

            ImageView ivArticleIcon;
            TextView tvDate;
            TextView tvSummary;

            ivArticleIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
            tvDate = (TextView) convertView.findViewById(R.id.tvDate);
            tvSummary = (TextView) convertView.findViewById(R.id.tvSummary);

            tvDate.setText(articleModelList.get(position).getWebPublicationDate()+":");
            tvSummary.setText(articleModelList.get(position).getHeadline());

            return convertView;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_refresh) {
            new JSONTask().execute("http://public.ocito.com/m/test/guardian.html");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
George Mulligan
  • 11,813
  • 6
  • 37
  • 50
A.Briois
  • 31
  • 1
  • 1
  • 3
  • You are most likely getting an error inside the try block in `doInBackground()` that is causing you to `return null;`. That is then what is passed into `onPostExecute()` and since you do not properly handle `null` you get the `NullPointerException`. You should `Log.e(...)` the error messages in the catch blocks to see what is going wrong, if anything. Also by default you should either return an empty list or properly handle null to avoid the exception. – George Mulligan May 14 '16 at 20:38
  • I totally agree with @george...it look like you are parsing wrong the json... it's time to get in touch with the logcat – ΦXocę 웃 Пepeúpa ツ May 14 '16 at 21:03
  • Thank you for your comments I will try to fix it. – A.Briois May 14 '16 at 21:13

1 Answers1

-1

You forgot to pass the object reference

List<ArticleModel> articleModelList = new ArrayList<ArticleModel>();

try this i hope it will work for you