如何显示Json的数据

时间:2016-01-10 21:04:52

标签: java android json android-volley android-adapter

package comeagain.materialdesign.fragments;


import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.xml.transform.ErrorListener;

import comeagain.materialdesign.Log.L;
import comeagain.materialdesign.R;
import comeagain.materialdesign.adapters.AdapterBoxOffice;
import comeagain.materialdesign.extras.Keys;
import comeagain.materialdesign.extras.UrlEndpoints;
import comeagain.materialdesign.materialTest.MyApplication;
import comeagain.materialdesign.network.VollleySingleton;
import comeagain.materialdesign.pojo.Movie;

import static comeagain.materialdesign.extras.Keys.EndpointBoxOffice.*;
import static comeagain.materialdesign.extras.UrlEndpoints.*;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FragmentBoxOffice#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentBoxOffice extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String URL_ROTTEN_TOMATOES_BOX_OFFICE = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=54wzfswsa4qmjg8hjwa64d4c";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private VollleySingleton vollleySingleton;
    private ImageLoader imageLoader;
    private RequestQueue requestQueue;
    private ArrayList<Movie> listMovies = new ArrayList<>();
    private DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
    private RecyclerView listMovieHits;
    private AdapterBoxOffice adapterBoxOffice;

    public FragmentBoxOffice() {

    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragmentBoxOffice.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentBoxOffice newInstance(String param1, String param2) {
        FragmentBoxOffice fragment = new FragmentBoxOffice();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public static String getRequestUrl(int limit) {
        return URL_ROTTEN_TOMATOES_BOX_OFFICE+"&=10";
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        vollleySingleton = VollleySingleton.getsInstance();
        requestQueue = vollleySingleton.getmRequestQueue();

    }

    private void sendJsonRequest() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10),
                (String) null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        listMovies = parseJSONResponse(response);


                        adapterBoxOffice.setMovieList(listMovies);
                        Log.i("The Movie list: ", listMovies.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestQueue.add(request);
    }

    private ArrayList<Movie> parseJSONResponse(JSONObject response) {
        ArrayList<Movie> listMovies = new ArrayList<>();
        if (response == null || response.length() == 0) {


            try {
                StringBuilder data = new StringBuilder();
                JSONArray arrayMovies = response.getJSONArray(KEY_MOVIES);

                for (int i = 0; i < arrayMovies.length(); i++) {
                    JSONObject currentMovie = arrayMovies.getJSONObject(i);
                    //get the currentMovie id
                    long id = currentMovie.getLong(KEY_ID);
                    //get the title of the current movie
                    String title = currentMovie.getString(KEY_TITLE);
                    //get the date in theater for the current movie
                    JSONObject objectReleaseDates = currentMovie.getJSONObject(KEY_RELEASE_DATES);
                    String releaseDate = null;
                    if (objectReleaseDates.has(KEY_THEATER)) {
                        releaseDate = objectReleaseDates.getString(KEY_THEATER);
                    } else {
                        releaseDate = "N/A";
                    }
                    //get the audience score for the current movie
                    JSONObject objectRatings = currentMovie.getJSONObject(KEY_RATINGS);
                    int audienceScore = -1;
                    if (objectRatings.has(KEY_AUDIENCE_SCORE)) {
                        audienceScore = objectRatings.getInt(KEY_AUDIENCE_SCORE);
                    }
                    //get the synopsis of the current movie
                    String synopsis = currentMovie.getString(KEY_SYNOPSIS);
                    JSONObject objectPosters = currentMovie.getJSONObject(KEY_POSTERS);
                    String urlThumnail = null;
                    if (objectPosters.has(KEY_THUMBNAIL)) {
                        urlThumnail = objectPosters.getString(KEY_THUMBNAIL);
                    }
                    Movie movie = new Movie();
                    movie.setTitle(title);
                    Date date = null;
                    date = dateformat.parse(releaseDate);

                    movie.setReleaseDateTheater(date);
                    movie.setAudienceScore(audienceScore);
                    movie.setSynopsis(synopsis);
                    movie.setUrlThumbnail(urlThumnail);
                    listMovies.add(movie);

                /*data.append(id + " " + title + " " + releaseDate + " " + audienceScore + "\n");*/
                }


                /*L.T(getActivity(), listMovies.toString());*/

            } catch (JSONException e) {

            } catch (ParseException e) {
                e.printStackTrace();
            }
            Log.i("The myListofMovies: ", listMovies.toString());
        }
        return listMovies;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_box_office, container, false);
        listMovieHits = (RecyclerView) view.findViewById(R.id.listMovieHits);
        listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapterBoxOffice = new AdapterBoxOffice(getActivity());
        listMovieHits.setAdapter(adapterBoxOffice);

        sendJsonRequest();
        return view;
    }

}

我的问题在于parseJSONResponse。此方法未执行。它应该解析listMovies。我在sendJsonRequest enter code here方法中尝试了Logging(Log.i(“The Movie list:”,listMovies.toString());),它在日志文件中没有返回任何内容。

1 个答案:

答案 0 :(得分:0)

只要null或length为0,您的响应就会被解析。这条线不应该是这样吗?

if (response != null && response.length() > 0)