Android解析服务器Json数据实例
Json数据信息如下:
{
"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."
}
]
}
以下为Android源码:
1、activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|top"> <LinearLayout
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="match_parent"
android:layout_height="wrap_content"> <ImageView
android:id="@+id/ivIcon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/avengers" /> <ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout> </LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="@drawable/rounded_bg"> <RatingBar
android:id="@+id/rbMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:stepSize=".5" /> <TextView
android:id="@+id/tvMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MovieName"
android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView
android:id="@+id/tvTagline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tagline"
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView
android:id="@+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Year"
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView
android:id="@+id/tvDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Duration"
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView
android:id="@+id/tvDirector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Director"
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView
android:id="@+id/tvCast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cast"
android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView
android:id="@+id/tvStory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Story" />
</LinearLayout>
</LinearLayout>
</ScrollView>
2、activity_main.xml
<LinearLayout 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=".MainActivity"> <ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lvMovies" />
</LinearLayout>
3、row.xml
<?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:clickable="false"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
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"> <ImageView
android:id="@+id/ivIcon"
android:layout_width="120dp"
android:layout_height="160dp" /> <ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_gravity="center" />
</FrameLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <TextView
android:id="@+id/tvMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MovieName"
android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView
android:id="@+id/tvTagline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tagline"
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView
android:id="@+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Year"
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView
android:id="@+id/tvDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Duration"
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView
android:id="@+id/tvDirector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Director"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout> <LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"> <RatingBar
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/rbMovie"
android:stepSize=".5" /> <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:text="Story"
android:id="@+id/tvStory" />
</LinearLayout>
</LinearLayout>
4、res/drawable/rounded_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="1dp"
android:shape="rectangle">
<solid android:color="@android:color/darker_gray" />
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" /> </shape>
5、MovieModel.java
package com.hisham.jsonparsingdemo.models; import com.google.gson.annotations.SerializedName; import java.util.List; /**
* Created by hisham on 9/6/2015.
*/
public class MovieModel {
private String movie;
private int year;
private float rating;
private String duration;
private String director;
private String tagline;
@SerializedName("cast")
private List<Cast> castList;
private String image;
private String story; 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 getTagline() {
return tagline;
} public void setTagline(String tagline) {
this.tagline = tagline;
} public List<Cast> getCastList() {
return castList;
} public void setCastList(List<Cast> castList) {
this.castList = castList;
} 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 static class Cast {
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
}
6、DetailActivity.java
package com.hisham.jsonparsingdemo; import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView; import com.google.gson.Gson;
import com.hisham.jsonparsingdemo.models.MovieModel;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; public class DetailActivity extends ActionBarActivity { private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
private ProgressBar progressBar; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail); // Showing and Enabling clicks on the Home/Up button
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} // setting up text views and stuff
setUpUIViews(); // recovering data from MainActivity, sent via intent
Bundle bundle = getIntent().getExtras();
if(bundle != null){
String json = bundle.getString("movieModel");
MovieModel movieModel = new Gson().fromJson(json, MovieModel.class); // Then later, when you want to display image
ImageLoader.getInstance().displayImage(movieModel.getImage(), ivMovieIcon, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
} @Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
} @Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
} @Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
}); tvMovie.setText(movieModel.getMovie());
tvTagline.setText(movieModel.getTagline());
tvYear.setText("Year: " + movieModel.getYear());
tvDuration.setText("Duration:" + movieModel.getDuration());
tvDirector.setText("Director:" + movieModel.getDirector()); // rating bar
rbMovieRating.setRating(movieModel.getRating() / 2); StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModel.getCastList()){
stringBuffer.append(cast.getName() + ", ");
} tvCast.setText("Cast:" + stringBuffer);
tvStory.setText(movieModel.getStory()); } } private void setUpUIViews() {
ivMovieIcon = (ImageView)findViewById(R.id.ivIcon);
tvMovie = (TextView)findViewById(R.id.tvMovie);
tvTagline = (TextView)findViewById(R.id.tvTagline);
tvYear = (TextView)findViewById(R.id.tvYear);
tvDuration = (TextView)findViewById(R.id.tvDuration);
tvDirector = (TextView)findViewById(R.id.tvDirector);
rbMovieRating = (RatingBar)findViewById(R.id.rbMovie);
tvCast = (TextView)findViewById(R.id.tvCast);
tvStory = (TextView)findViewById(R.id.tvStory);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
} @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(); if (id == android.R.id.home) {
finish();
} return super.onOptionsItemSelected(item);
} }
7、MainActivity.java
package com.hisham.jsonparsingdemo; import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast; import com.google.gson.Gson;
import com.hisham.jsonparsingdemo.models.MovieModel;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; 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 ActionBarActivity { private final String URL_TO_HIT = "http://jsonparsing.parseapp.com/jsonData/moviesData.txt";
private TextView tvData;
private ListView lvMovies;
private ProgressDialog dialog; // Git error fix - http://stackoverflow.com/questions/16614410/android-studio-checkout-github-error-createprocess-2-windows @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading. Please wait...");
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start lvMovies = (ListView)findViewById(R.id.lvMovies); // To start fetching the data when app start, uncomment below line to start the async task.
new JSONTask().execute(URL_TO_HIT);
} public class JSONTask extends AsyncTask<String,String, List<MovieModel> >{ @Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
} @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 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("movies"); List<MovieModel> movieModelList = new ArrayList<>(); Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
MovieModel movieModel = gson.fromJson(finalObject.toString(), MovieModel.class);
// movieModel.setMovie(finalObject.getString("movie"));
// movieModel.setYear(finalObject.getInt("year"));
// movieModel.setRating((float) finalObject.getDouble("rating"));
// movieModel.setDirector(finalObject.getString("director"));
//
// movieModel.setDuration(finalObject.getString("duration"));
// movieModel.setTagline(finalObject.getString("tagline"));
// movieModel.setImage(finalObject.getString("image"));
// movieModel.setStory(finalObject.getString("story"));
//
// List<MovieModel.Cast> castList = new ArrayList<>();
// for(int j=0; j<finalObject.getJSONArray("cast").length(); j++){
// MovieModel.Cast cast = new MovieModel.Cast();
// cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
// castList.add(cast);
// }
// movieModel.setCastList(castList);
// adding the final object in the list
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(final List<MovieModel> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result != null) {
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result);
lvMovies.setAdapter(adapter);
lvMovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MovieModel movieModel = result.get(position);
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("movieModel", new Gson().toJson(movieModel));
startActivity(intent);
}
});
} else {
Toast.makeText(getApplicationContext(), "Not able to fetch data from server, please check url.", Toast.LENGTH_SHORT).show();
}
}
} public class MovieAdapter extends ArrayAdapter{ private 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) { ViewHolder holder = null; if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.ivMovieIcon = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tvMovie = (TextView)convertView.findViewById(R.id.tvMovie);
holder.tvTagline = (TextView)convertView.findViewById(R.id.tvTagline);
holder.tvYear = (TextView)convertView.findViewById(R.id.tvYear);
holder.tvDuration = (TextView)convertView.findViewById(R.id.tvDuration);
holder.tvDirector = (TextView)convertView.findViewById(R.id.tvDirector);
holder.rbMovieRating = (RatingBar)convertView.findViewById(R.id.rbMovie);
holder.tvCast = (TextView)convertView.findViewById(R.id.tvCast);
holder.tvStory = (TextView)convertView.findViewById(R.id.tvStory);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
} final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar); // Then later, when you want to display image
ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
} @Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
} @Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
} @Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
}); holder.tvMovie.setText(movieModelList.get(position).getMovie());
holder.tvTagline.setText(movieModelList.get(position).getTagline());
holder.tvYear.setText("Year: " + movieModelList.get(position).getYear());
holder.tvDuration.setText("Duration:" + movieModelList.get(position).getDuration());
holder.tvDirector.setText("Director:" + movieModelList.get(position).getDirector()); // rating bar
holder.rbMovieRating.setRating(movieModelList.get(position).getRating()/2); StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
stringBuffer.append(cast.getName() + ", ");
} holder.tvCast.setText("Cast:" + stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());
return convertView;
} class ViewHolder{
private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
} } @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_refresh) {
new JSONTask().execute(URL_TO_HIT);
return true;
} return super.onOptionsItemSelected(item);
}
}
Android解析服务器Json数据实例的更多相关文章
- android解析网络json数据(1)
1.首先获得url,传入URL类,利用URL的openconnection方法,获得URLConnection,去的输入流,进行操作,具体代码如下: public class NetConnectio ...
- json-lib-2.4-jdk15.jar所需全部JAR包.rar java jsoup解析开彩网api接口json数据实例
json-lib-2.4-jdk15.jar所需全部JAR包.rar java jsoup解析开彩网api接口json数据实例 json-lib-2.4-jdk15.jar所需全部JAR包.rar ...
- android 复杂的json数据解析
1.通过谷歌的Gson来进行解析: json数据:sTotalString = {"message":"success","result": ...
- Gson解析复杂Json数据
背景 json是一种数据格式,便于数据传输.存储.交换. gson是 ...
- Android - 向服务器发送数据(POST) - HTTPClient.
该篇文章主要说明使用Apache提供的HTTPClient,通过post方式,向服务器发送数据.由于有些东西在 Android - 向服务器发送数据(GET)中提到过,就不再重复. 一,Android ...
- 解析天气预报JSON数据
解析天气预报JSON数据 JSON字符串 constjson2 = '{' + #13#10 +'"error":0,' + #13#10 +'"status" ...
- mormot解析天气预报JSON数据
mormot解析天气预报JSON数据 uses SynCommons; constjson2 = '{' + #13#10 +'"error":0,' + #13#10 +'&qu ...
- android 解析服务器数据使用json还是xml方式
整理自百度搜索: 现在的Android应用程序,几乎没有不与服务端交换数据的了!那么,android应用在与服务端交换数据的时候,我们有哪些选择呢?哪种数据交换格式要更好吗?下面文章简单为 andro ...
- Android - 服务器json数据交互.
一,服务器端 服务器端使用的是Servlet,封装json对象使用的 'json-lib-2.2.2-jdk15.jar,ezmorph-1.0.4.jar,commons-logging-1.1.j ...
随机推荐
- docker image重命名
use docker tag command tag Tag an image into a repository
- Jasper(物联网网络支撑平台公司)的技术为什么这么牛逼?
Jasper在这个行业积累了十几年,合作的运营商超过30个,合作的行业大咖包括了通用.空客.宝马.特斯拉等几千个行业龙头,还是有很多积累下来的优势的. 一是,Jasper通过积累下来的行业应用经验,针 ...
- IM即时通讯
即时通讯,由于项目需求和不可抗力因素用的融云 当然我更倾向于用环信亲加等 使用融云遇到的那些坑: 1.集成时的坑: ,编译环境要求太高 项目中有很多旧的东西 达不到其标准 直接用最新版,出错, ...
- OBJ Loader Source Code
https://github.com/ChrisJansson/ObjLoader http://www.codeproject.com/Articles/798054/SimpleScene-d-s ...
- MIME类型(JSP中)
什么是MIME类型-在把输出结果传送到浏览器上的时候,浏览器必须启动是党的应用程序来处理这个输出文档.这可以通过多种类型MIME(多功能网际邮件扩充协议)来完成.在HTTP中,MIME类型被定义在Co ...
- spring 容器技术入门
官方文档 翻译 https://waylau.gitbooks.io/spring-framework-4-reference/content/III.%20Core%20Technologies/C ...
- LSM存储模型
LSM存储模型 数据库有3种基本的存储引擎: 哈希表,支持增.删.改以及随机读取操作,但不支持顺序扫描,对应的存储系统为key-value存储系统.对于key-value的插入以及查询,哈希表的复杂度 ...
- SCWS分词扩展在UNIX/LINUX下的安装方法
<?php/** * 中文分词处理方法 *+--------------------------------- * @param stirng $string 要处理的字符串 * @param ...
- Python之路【第七篇续】:I/O多路复用
回顾原生Socket 一.Socket起源: socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用[打开][读写][关闭]模式来操作. socket就是该模式的 ...
- BAT command
http://www.cnblogs.com/SunShineYPH/archive/2011/12/13/2285570.html BAT常用命令 1.@ 它的作用是隐藏它后面这一行的命令本身(只能 ...