码迷,mamicode.com
首页 > 移动开发 > 详细

Android解析服务器Json数据实例

时间:2016-08-24 00:58:13      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

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数据实例

标签:

原文地址:http://www.cnblogs.com/newcaoguo/p/5801253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!