rishav rishav - 1 month ago 19
Android Question

list view size error, says virtual method interface

I created an app which shows data from json object from web to my movie list view.
The error is that it says there is

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


Here is my full code that i have taken to load the movie parameters from web and display it as list.

MainActivity.java

package com.example.shailendra.jsonmovies;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

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;

import model.MovieModel;

public class MainActivity extends AppCompatActivity {
ListView listView;

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

// new JsonTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoList.txt");



Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}


public class JsonTask extends AsyncTask<String,String,List<MovieModel>>
{ MovieAdapter adapter=null;
@Override
protected void onPostExecute(List<MovieModel> s) {
try{
super.onPostExecute(s);
adapter= new MovieAdapter(getApplicationContext(),R.layout.row,s);
listView.setAdapter(adapter);}
catch (Exception e)
{
e.printStackTrace();
}




}

@Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url= new URL(params[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
InputStream is= connection.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
reader= new BufferedReader(isr);
StringBuffer buffer= new StringBuffer();

String line=null;

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<>();
MovieModel movieModel= new MovieModel();
for(int i=0;i<parentArray.length();i++)
{

JSONObject finalObject= parentArray.getJSONObject(i);
String movieName= finalObject.getString("movie");
movieModel.setMovie(finalObject.getString("movie"));
int year= finalObject.getInt("year");
movieModel.setYear(finalObject.getInt("year"));
movieModel.setRating((float)finalObject.getDouble("year"));
movieModel.setDirector(finalObject.getString("director"));
movieModel.setDuration(finalObject.getString("duration"));
movieModel.setTaglline(finalObject.getString("tagline"));
movieModel.setStory(finalObject.getString("story"));
movieModel.setImage(finalObject.getString("image"));

List<MovieModel.Cast> castList = new ArrayList<>();
for(int j=0;j<finalObject.getJSONArray("cast").length();j++)
{
JSONObject castObject= finalObject.getJSONArray("cast").getJSONObject(j);

MovieModel.Cast cast= new MovieModel.Cast();
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
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_settings) {
new JsonTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoList.txt");
return true;
}

return super.onOptionsItemSelected(item);
}
}


movieAdapter.java

package com.example.shailendra.jsonmovies;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import java.util.List;

import model.MovieModel;

/**
* Created by Shailendra on 10/21/2016.
*/
public class MovieAdapter extends ArrayAdapter{
public List<MovieModel> movieModelList;
int resource;
LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList=objects;
this.resource=resource;


}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater=LayoutInflater.from(getContext());
View customView=inflater.inflate(R.layout.row,parent,false);
ImageView ivMovieIcon=(ImageView)customView.findViewById(R.id.ivIcon);
TextView tvMovie=(TextView)customView.findViewById(R.id.tvMovie);
TextView tvTagLine=(TextView)customView.findViewById(R.id.tvTagline);
TextView tvYear=(TextView)customView.findViewById(R.id.tvYear);
TextView tvDuration=(TextView)customView.findViewById(R.id.tvDuration);
TextView tvDirector=(TextView)customView.findViewById(R.id.tvDirector);
TextView tvCast=(TextView)customView.findViewById(R.id.tvCast);
TextView tvStory=(TextView)customView.findViewById(R.id.tvStory);
RatingBar ratingBare=(RatingBar) customView.findViewById(R.id.ratingBar);

tvMovie.setText(movieModelList.get(position).getMovie());
tvTagLine.setText(movieModelList.get(position).getTaglline());
tvYear.setText("Year: "+movieModelList.get(position).getYear());
tvDuration.setText(movieModelList.get(position).getDuration());
tvDirector.setText(movieModelList.get(position).getDirector());
StringBuffer stringBuffer= new StringBuffer();
for(MovieModel.Cast cast:movieModelList.get(position).getCastList())
{
stringBuffer.append(cast.getName() +", ");}
tvCast.setText(stringBuffer);
tvStory.setText(movieModelList.get(position).getStory());
ratingBare.setRating(movieModelList.get(position).getRating()/2);

return customView;
}
}


MovieModel.java

package model;

import java.util.List;

/**
* Created by Shailendra on 10/21/2016.
*/
public class MovieModel {

private String movie;
private int year;
private float rating;
private String duration;
private String director;
private String taglline;
private String image;
private String story;
private List<Cast> castList;

public static class Cast {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


public String getMovie() {
return movie;
}

public void setMovie(String movie) {
this.movie = movie;
}

public int getYear() {
return year;
}

public void setYear(int year) {
this.year = year;
}

public float getRating() {
return rating;
}

public void setRating(float rating) {
this.rating = rating;
}

public String getDuration() {
return duration;
}

public void setDuration(String duration) {
this.duration = duration;
}

public String getDirector() {
return director;
}

public void setDirector(String director) {
this.director = director;
}

public String getTaglline() {
return taglline;
}

public void setTaglline(String taglline) {
this.taglline = taglline;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

public String getStory() {
return story;
}

public void setStory(String story) {
this.story = story;
}

public List<Cast> getCastList() {
return castList;
}

public void setCastList(List<Cast> castList) {
this.castList = castList;
}
}

Answer

Check out the json link if it is correct and you can check the format if json is correct or not in www.jsonlint.com ---> point 1) Have to kept method getCount? put get Count and see what it returns

@Override
public int getCount() {
    if (movieModelList == null)
        return (0);
   movieModelList.size();
}

For array just define it globally --->point 2 After your app starts working you may get white text as if text is behind your current layout. For that use getBaseContext(); instead of getApplicationContext();