post ececute在异步tsask中显示空指针异常

时间:2016-10-04 03:49:08

标签: android nullpointerexception

我在类moviemodel中有getter和setter

我收到了这个错误

FATAL EXCEPTION: main Process: com.example.shailendra.fulljson, PID: 7251                                                                                  
    java.lang.NullPointerException
    at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
    at android.widget.ListView.setAdapter(ListView.java:480)
    at .MainActivity$JsonClass.onPostExecute(MainActivity)

MainActivity。的java

class MainActivity extends AppCompatActivity {

    Button clickMe;
    ListView listView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.listView);

        clickMe= (Button)findViewById(R.id.clickMe);
        clickMe.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new JsonClass().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
            }
        });
    }

    class JsonClass extends AsyncTask<String,Void,List<MovieModel>> {  

        ListView listView=(ListView)findViewById(R.id.listView);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<MovieModel> doInBackground(String... params) {
            HttpURLConnection connection=null;
            BufferedReader reader=null;
            MovieModel movieModel = new MovieModel();
            MovieModel.Cast cast= new MovieModel.Cast();

            try {
                URL url= new URL(params[0]);
                connection=(HttpURLConnection)url.openConnection();
                connection.connect();
                InputStream stream=connection.getInputStream();
                InputStreamReader isr= new InputStreamReader(stream);
                reader =new BufferedReader(isr);
                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("movies");
                List<MovieModel> movieModelList= new ArrayList<>();
                for(int i=0;i<parentArray.length();i++) {

                    JSONObject answerObject = parentArray.getJSONObject(i);
                    movieModel.setMovie(answerObject.getString("movie"));
                    movieModel.setYear(answerObject.getInt("year"));
                    movieModel.setRating((float) answerObject.getDouble("rating"));
                    movieModel.setDirector(answerObject.getString("director"));
                    movieModel.setDuration(answerObject.getInt("duration"));
                    movieModel.settagLine(answerObject.getString("tagline"));
                    movieModel.setImage(answerObject.getString("image"));
                    movieModel.setStory(answerObject.getString("story"));
                    List<MovieModel.Cast> castList= new ArrayList<>();
                    for(int j=0;j<answerObject.getJSONArray("cast").length();j++) {  
                        JSONObject castObject= answerObject.getJSONArray("cast").getJSONObject(j);

                         cast.setName(castObject.getString("name"));
                         castList.add(cast);

                    }
                    movieModel.setCastList(castList);
                    movieModelList.add(movieModel);

                }
                return movieModelList;

            } 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<MovieModel> s) {
            super.onPostExecute(s);

            MovieAdapter adapter = new MovieAdapter(getApplicationContext(),R.layout.row,s);
            listView.setAdapter(adapter);

        }

    }

    public class MovieAdapter extends ArrayAdapter { 
        public List<MovieModel> movieModelList;
        private  int resource;
        private LayoutInflater inflater;
        public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
            super(context, resource, objects);
            movieModelList=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 ivMovieIcon;
           TextView tvMovie;
           TextView tvTagLine;
           TextView tvYear;
           TextView tvDuration;
           TextView tvDirector;
           TextView tvCast;
           TextView tvStory;
           RatingBar rbMovieRating;
           ivMovieIcon =(ImageView)convertView.findViewById(R.id.ivicon);
           tvTagLine=(TextView)convertView.findViewById(R.id.tvTagLine);
           tvYear=(TextView)convertView.findViewById(R.id.tvYear);
           tvDuration=(TextView)convertView.findViewById(R.id.tvDuration);
           tvDirector=(TextView)convertView.findViewById(R.id.tvDirector);
           tvStory=(TextView)convertView.findViewById(R.id.tvStory);
           tvCast=(TextView)convertView.findViewById(R.id.tvCast);
           rbMovieRating=(RatingBar) convertView.findViewById(R.id.rbMovie);
           tvMovie=(TextView)convertView.findViewById(R.id.tvMovie);

           tvCast.setText(movieModelList.get(position).getDuration());
           tvDirector.setText(movieModelList.get(position).getDirector());
           tvYear.setText("Year: " + movieModelList.get(position).getYear());
           tvStory.setText(movieModelList.get(position).getStory());
           tvDuration.setText(movieModelList.get(position).getDuration());
           tvTagLine.setText(movieModelList.get(position).getTagLine());
           tvMovie.setText(movieModelList.get(position).getMovie());

           StringBuffer stringBuffer= new StringBuffer();

           for(MovieModel.Cast cast: movieModelList.get(position).getCastList()) {
               stringBuffer.append(cast.getName()+ ", ");
           }
           tvCast.setText(stringBuffer);
           rbMovieRating.setRating(movieModelList.get(position).getRating()/2);
           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) {

       int id = item.getItemId();

       //noinspection SimplifiableIfStatement
       if (id == R.id.action_settings) {
//            new JsonClass().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
//
//            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

4 个答案:

答案 0 :(得分:0)

好吧,这可能会发生,因为你在doInBackground结束时返回null。

要么

return movieModelList;

或者像这样初始化适配器。

MovieAdapter adapter = new  MovieAdapter(getApplicationContext(),R.layout.row,movieModelList);

我的建议是你在Adapter类中为ArrayList使用不同的变量名,这样你就不会被混淆。

快乐编码。

答案 1 :(得分:0)

此行可能正在创建例外。

convertView=inflater.inflate(resource,null);

您可以像这样替换此行。

convertView=inflater.inflate(resource,parent,false);

在“onPostExecute Method”

中检查“s”是否为空
@Override
protected void onPostExecute(List<MovieModel> s) {
    if(s!=null && s.size()>0) {       
        MovieAdapter adapter = new  MovieAdapter(getApplicationContext(),R.layout.row,s);
        listView.setAdapter(adapter);
    }
    super.onPostExecute(s);
}

答案 2 :(得分:0)

您在该列表视图中得到答案意味着s返回null,或者您的数据未从Web正确解析。从json好奇概念网站查看你的json,看看s是否返回null。

答案 3 :(得分:-1)

在Post方法中更改此内容:

 MovieAdapter adapter = new  MovieAdapter(getApplicationContext(),R.layout.row,movieModelList);
            listView.setAdapter(adapter);

让我知道它的作用与否?