{
"movies": [
{
"movie": "Avengers",
"year": 2012,
"rating": 7.8,
"duration": "141 min",
"director": "Joss Whedon",
"tagline": "A new age begins",
"cast": [
{
"name": "Robert Downey Jr."
},
{
"name": "Chris Evans"
},
{
"name": "Mark Ruffalo"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/avengers.jpg",
"story": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's Mightiest Heroes to stop the villainous Ultron from enacting his terrible plans."
},
{
"movie": "Interstellar",
"year": 2014,
"rating": 8.7,
"duration": "169 min",
"director": "Christopher Nolan",
"tagline": "Mankind was born on Earth. It was never meant to die here.",
"cast": [
{
"name": "Matthew McConaughey"
},
{
"name": "Anne Hathaway"
},
{
"name": "Jessica Chastain"
},
{
"name": "Wes Bentley"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/interstellar.jpg",
"story": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival."
},
{
"movie": "Fantastic Four",
"year": 2015,
"rating": 4.0,
"duration": "100 min",
"director": "Josh Trank",
"tagline": "Change is coming.",
"cast": [
{
"name": "Miles Teller"
},
{
"name": "Kate Mara"
},
{
"name": "Michael B. Jordan"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/four.jpg",
"story": "Four young outsiders teleport to an alternate and dangerous universe which alters their physical form in shocking ways. The four must learn to harness their new abilities and work together to save Earth from a former friend turned enemy."
},
{
"movie": "The Dark Knight",
"year": 2008,
"rating": 9.0,
"duration": "152 min",
"director": "Christopher Nolan",
"tagline": "Why So Serious?",
"cast": [
{
"name": "Christian Bale"
},
{
"name": "Heath Ledger"
},
{
"name": "Aaron Eckhart"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/batman.jpg",
"story": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice."
},
{
"movie": "The Lord of the Rings: The Return of the King",
"year": 2003,
"rating": 8.9,
"duration": "201 min",
"director": "Peter Jackson",
"tagline": "This Christmas the journey ends.",
"cast": [
{
"name": "Viggo Mortensen"
},
{
"name": "Ian McKellen"
},
{
"name": "Elijah Wood"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/rings.jpg",
"story": "Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring."
},
{
"movie": "Life Is Beautiful",
"year": 1997,
"rating": 8.6,
"duration": "116 min",
"director": "Roberto Benigni",
"tagline": "An unforgettable fable that proves love, family and imagination conquer all.",
"cast": [
{
"name": "Roberto Benigni"
},
{
"name": "Nicoletta Braschi"
},
{
"name": "Giorgio Cantarini"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/life.jpg",
"story": "When an open-minded Jewish librarian and his son become victims of the Holocaust, he uses a perfect mixture of will, humor and imagination to protect his son from the dangers around their camp."
},
{
"movie": "Gladiator",
"year": 2000,
"rating": 8.5,
"duration": "155 min",
"director": "Ridley Scott",
"tagline": "Father of a murdered son, husband to a murdered wife and I shall have my vengeance in this life or the next",
"cast": [
{
"name": "Russell Crowe"
},
{
"name": "Joaquin Phoenix"
},
{
"name": "Connie Nielsen"
},
{
"name": "Oliver Reed"
},
{
"name": "Tommy Flanagan"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/gladiator.jpg",
"story": "When a Roman general is betrayed and his family murdered by an emperor's corrupt son, he comes to Rome as a gladiator to seek revenge."
},
{
"movie": "The Lion King",
"year": 1994,
"rating": 8.5,
"duration": "89 min",
"director": "Roger Allers",
"tagline": "The King Has Returned.",
"cast": [
{
"name": "James Earl Jones"
},
{
"name": "Jeremy Irons"
},
{
"name": "Matthew Broderick"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/lionking.jpg",
"story": "Lion cub and future king Simba searches for his identity. His eagerness to please others and penchant for testing his boundaries sometimes gets him into trouble."
},
{
"movie": "WALL-E",
"year": 2008,
"rating": 8.4,
"duration": "98 min",
"director": "Andrew Stanton",
"tagline": "He's got a lot of time on his hands.",
"cast": [
{
"name": "Ben Burtt"
},
{
"name": "Elissa Knight"
},
{
"name": "Jeff Garlin"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/walle.jpg",
"story": "In the distant future, a small waste collecting robot inadvertently embarks on a space journey that will ultimately decide the fate of mankind."
},
{
"movie": "Saving Private Ryan",
"year": 1998,
"rating": 8.6,
"duration": "169 min",
"director": "Steven Spielberg",
"tagline": "There was only one man left in the family, and the mission was to save him",
"cast": [
{
"name": "Tom Hanks"
},
{
"name": "Matt Damon"
}
],
"image": "http://jsonparsing.parseapp.com/jsonData/images/ryan.jpg",
"story": "Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action."
}
]
}
@Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
MovieAdapter Adapter=new MovieAdapter(getContext(),R.layout.row,result);
lvmovies.setAdapter(Adapter);
}
这是我的全部代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="maxwell.jsonsample.SecondFragment">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ok"
android:id="@+id/ok"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="437dp"
android:id="@+id/lvmovies"
android:layout_below="@+id/ok"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</FrameLayout>
<ImageView
android:layout_width="120dp"
android:layout_height="160dp"
android:id="@+id/movieicon"
android:src="@mipmap/ic_launcher" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Movie Name"
android:id="@+id/tvmovie" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tagline"
android:id="@+id/tvtagline" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="year"
android:id="@+id/tvyear" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="duration"
android:id="@+id/tvduration" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="dirctor"
android:id="@+id/tvdirector" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/ratingBar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Cast"
android:id="@+id/tvcast" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Story"
android:id="@+id/tvstory" />
</LinearLayout>
</LinearLayout>
package maxwell.jsonsample;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
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.RatingBar;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
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 maxwell.jsonsample.model.MovieModel;
/**
* A simple {@link Fragment} subclass.
*/
public class SecondFragment extends Fragment {
TextView tv;
private TextView viwejson;
HttpURLConnection connection;
BufferedReader reader;
InputStream stream;
Button ok;
private ListView lvmovies;
public SecondFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
lvmovies=(ListView)view.findViewById(R.id.lvmovies);
ok=(Button)view.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JsonTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
}
});
return view;
}
public class JsonTask extends AsyncTask<String,String,List<MovieModel>> {
@Override
protected List<MovieModel> doInBackground(String... params) {
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
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 jsonObject=new JSONObject(finalJson);
JSONArray jsonArray=jsonObject.getJSONArray("movies");
List<MovieModel> movieModelslist=new ArrayList<>();
for (int i=0; i<jsonArray.length();i++) {
JSONObject finaljsonobject = jsonArray.getJSONObject(i);
MovieModel movieModel=new MovieModel();
movieModel.setMovie(finaljsonobject.getString("movie"));
movieModel.setYear(finaljsonobject.getInt("year"));
movieModel.setRating((float) finaljsonobject.getDouble("rating"));
movieModel.setDuration(finaljsonobject.getString("duration"));
movieModel.setDirector(finaljsonobject.getString("director"));
movieModel.setTagline(finaljsonobject.getString("tagline"));
movieModel.setImage(finaljsonobject.getString("image"));
movieModel.setStory(finaljsonobject.getString("story"));
List<MovieModel.Cast> castList=new ArrayList<>();
for (int j=0; j<jsonObject.getJSONArray("cast").length(); j++)
{
MovieModel.Cast cast=new MovieModel.Cast();
cast.setName(finaljsonobject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
movieModel.setCastlist(castList);
movieModelslist.add(movieModel);
}
return movieModelslist;
} 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> result) {
super.onPostExecute(result);
MovieAdapter Adapter=new MovieAdapter(getContext(),R.layout.row,result);
lvmovies.setAdapter(Adapter);
}
}
public class MovieAdapter extends ArrayAdapter
{
private List<MovieModel> movieModelslist;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
inflater=(LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView=inflater.inflate(resource,null);
}
ImageView movieicon;
TextView tvmovie;
TextView tvtagline;
TextView tvyear;
TextView tvduration;
TextView tvdirctor;
RatingBar tvrating;
TextView tvcast;
TextView tvstory;
movieicon=(ImageView)convertView.findViewById(R.id.movieicon);
tvmovie=(TextView)convertView.findViewById(R.id.tvmovie);
tvtagline=(TextView)convertView.findViewById(R.id.tvtagline);
tvyear=(TextView)convertView.findViewById(R.id.tvyear);
tvduration=(TextView)convertView.findViewById(R.id.tvduration);
tvdirctor=(TextView)convertView.findViewById(R.id.tvdirector);
tvcast=(TextView)convertView.findViewById(R.id.tvcast);
tvstory=(TextView)convertView.findViewById(R.id.tvstory);
tvrating=(RatingBar)convertView.findViewById(R.id.ratingBar);
ImageLoader.getInstance().displayImage(movieModelslist.get(position).getImage(), movieicon);
tvmovie.setText(movieModelslist.get(position).getMovie());
tvtagline.setText("TagLine -"+movieModelslist.get(position).getTagline());
tvyear.setText("Year -"+movieModelslist.get(position).getYear());
tvduration.setText("Duration -"+movieModelslist.get(position).getDuration());
tvdirctor.setText("Dircetor -"+movieModelslist.get(position).getDirector());
tvrating.setRating(movieModelslist.get(position).getRating()/2);
StringBuffer stringBuffer=new StringBuffer();
for (MovieModel.Cast cast : movieModelslist.get(position).getCastlist())
{
stringBuffer.append(cast.getName()+ ", ");
}
tvcast.setText(stringBuffer);
tvstory.setText(movieModelslist.get(position).getMovie());
return convertView;
}
}
}
答案 0 :(得分:0)
你得到了一个NullPointerException,因为http连接或json解析引发了一些异常,你最终在
return null
哪个传递给onPostExecute,然后作为空列表放入适配器,然后你得到你看到的异常。
因此,通过不返回null来解决紧急问题。将列表移动到范围内,以便在出现错误时将其作为空列表返回
@Override
protected List<MovieModel> doInBackground(String... params) {
List<MovieModel> movieModelslist=new ArrayList<>();
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
// blah blah... catch, finally
return movieModelslist; // instead of null
其他选项:忘记AsyncTask并学习Retrofit