java.lang.NullPointerException:尝试在空对象引用4上调用接口方法'int java.util.List.size()'

时间:2016-05-14 20:26:11

标签: java android nullpointerexception

我正在尝试在ListView中显示我已解析的JSON数据,但是当我尝试运行该应用时出现以下错误。

  

java.lang.NullPointerException:尝试调用接口方法   空对象引用上的'int java.util.List.size()'

这是堆栈跟踪。

 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)

我的代码。

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

1 个答案:

答案 0 :(得分:-1)

您忘记传递对象引用

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

尝试这个我希望它能为你效用