我创建了一个应用程序,显示从json对象从web到我的电影列表视图的数据。 错误是它说有
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference.
这是我用来从web加载电影参数并将其显示为列表的完整代码。
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;
}
}
答案 0 :(得分:0)
首先将您的MovieModel
定义为全局。然后在将适配器设置为ListView
之前将其初始化。在您的情况下,您不会初始化ArrayList
。
这样做。
全球宣言:
private ArrayList<MovieModel> movieModel;
然后在OnCreate
方法内部初始化它。
movie = new ArrayList<MovieModel>();
示例:
见这个例子:
答案 1 :(得分:0)
在适配器类中重写getCount()方法
@Override
public int getCount() {
if (movieModelList == null)
return 0;
movieModelList.size()
}
还要检查从AsyncTask的doInBackground()返回的值。
答案 2 :(得分:0)
如果json链接正确,请查看json链接,如果json是否正确,您可以在www.jsonlint.com查看格式。 ---&GT; 1) 必须保留方法getCount? put get Count并查看它返回的内容
@Override
public int getCount() {
if (movieModelList == null)
return (0);
movieModelList.size();
}
对于数组,只需全局定义它 ---&gt;第2点 应用程序开始工作后,您可能会获得白色文本,就好像文本位于当前布局之后。为此使用getBaseContext();而不是getApplicationContext();