簡體   English   中英

如何顯示來自Json的數據

[英]How can I display data from Json

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中記錄日志(Log.i(“電影列表:”,listMovies.toString());),在enter code here方法中enter code here並且在記錄文件中不返回任何內容。

只要它為null或length為0,就會解析您的響應。 這行不應該是這樣嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM