Элемент RecyclerView для загрузки другого RecyclerView с помощью вложенного JSON

Я разрабатываю приложение, показывающееСписок кинотеатров а такжеСписок показа фильмов в каждом кинотеатре. Я хочу использовать 2 RecyclerViews,Один Первые списки имен кинотеатров, а такжевторой Приходит после нажатия наФильмы Элемент первого RecyclerView.

Я используюВложенный JSON чтобы получить информацию, и я успешно получил список кинотеатров, но я не получаю соответствующие фильмы во втором RecyclerView.

КлассыCinema а такжеCinemaAdapter несут ответственность за получение CinemaNames и фильмов с использованиемJSONArray, но я хочу, чтобы фильмы отображались во втором RecyclerView (LoadingMovies.java класс иLoadingMoviesAdapter.java Ответственны за Второй RecyclerView). КлассыLoadingMovies.java а такжеLoadingMovies.java несут ответственность за получение данных из CinemaAdapter после нажатия наПоказать список фильмов, (Как правило, я хочу, чтобы каждый кинотеатр обновлял свои фильмы в соответствии с JSON.). В настоящее время я получаю два фильма во всех кинотеатрах, а остальные не отображаются.

Ниже мой вложенный JSON:

 [
  {
    "Cinemax": "Blue Ray",
    "Contacts": "0704594180",
    "CinemaxPhoto": "huzy.jpg",
    "Longitude": "32.89577584",
    "Latitude": "0.46378484",
    "Movie": [
      {
        "MovieName": "Ice Age 3",
        "Synopsis": "Manny, Diego and sid",
        "photo": "ice_age_3.jpg",
        "others": null,
        "ShowTime": {
          "Monday": "1:30 p.m , 3:40 p.m",
          "Tuesday": "1:30 pm , 3:40 p.m",
          "Wednesday": "1:30 p.m., 3:40 p.m",
          "Thursday": "1:30 p.m., 3:40 p.m",
          "Friday": "1:30 p.m., 3:40 p.m",
          "Saturday": "1:30 p.m., 3:40 p.m",
          "Sunday": "1:30 p.m., 3:40 p.m"
        }
      },
      {
        "MovieName": "Zootopia",
        "Synopsis": "Manny, Diego and sid",
        "photo": "zootopia.jpg",
        "others": null,
        "ShowTime": {
          "Monday": "4:30 p.m , 6:30 p.m",
          "Tuesday": "4:30 p.m , 6:30 p.m",
          "Wednesday": "4:30 p.m , 6:30 p.m",
          "Thursday": "4:30 p.m , 6:30 p.m",
          "Friday": "4:30 p.m , 6:30 p.m",
          "Saturday": "4:30 p.m , 6:30 p.m",
          "Sunday": "4:30 p.m , 6:30 p.m"
        }
      },
      {
        "MovieName": "Madaari",
        "Synopsis": "Nirmal loses his family in a man-made disaster, he starts the journey of seeking answers asking for accountabilty, for sure am a genius , lets try out and see whether this will work out, horaay , i dont know , me am confused ",
        "photo": "madaari.jpg",
        "others": null,
        "ShowTime": {
          "Monday": "6:30 p.m , 8:30 p.m",
          "Tuesday": "6:30 p.m , 8:30 p.m",
          "Wednesday": "6:30 p.m , 8:30 p.m",
          "Thursday": "6:30 p.m , 8:30 p.m",
          "Friday": "6:30 p.m , 8:30 p.m",
          "Saturday": "6:30 p.m , 8:30 p.m",
          "Sunday": "6:30 p.m , 8:30 p.m"
        }
      },
      {
        "MovieName": "Me Before You",
        "Synopsis": "A girl in a small town forms an unlikely bond with a recently paralyzed man she is taking care of.",
        "photo": "me_before_you.jpg",
        "others": null,
        "ShowTime": {
          "Monday": "8:30 p.m , 11:30 p.m",
          "Tuesday": "8:30 p.m , 11:30 p.m",
          "Wednesday": "8:30 p.m , 11:30 p.m",
          "Thursday": "8:30 p.m , 11:30 p.m",
          "Friday": "8:30 p.m , 11:30 p.m",
          "Saturday": "8:30 p.m , 11:30 p.m",
          "Sunday": "8:30 p.m , 11:30 p.m"
        }
      },
      {
        "MovieName": "Ghostbusters",
        "Synopsis": "Following a ghost invasion of Manhattan, paranormal enthusiasts Erin Gilbert and Abby Yates , nuclear engineer jillian Holtzmann",
        "photo": "ghost_busters.jpg",
        "others": null,
        "ShowTime": {
          "Monday": "11:30 p.m , 1:30 a.m",
          "Tuesday": "11:30 p.m , 1:30 a.m",
          "Wednesday": "11:30 p.m , 1:30 a.m",
          "Thursday": "11:30 p.m , 1:30 a.m",
          "Friday": "11:30 p.m , 1:30 a.m",
          "Saturday": "11:30 p.m , 1:30 a.m",
          "Sunday": "11:30 p.m , 1:30 a.m"
        }
      }
    ]
  },
  {
    "Cinemax": "White Down",
    "Contacts": "0700304850",
    "CinemaxPhoto": "hello.jpg",
    "Longitude": "32.89577584",
    "Latitude": "0.46378484",
    "Movie": [
      {
        "MovieName": "The Legend Of Tarzan",
        "Synopsis": "Tarzan , having acclimated to life in London, is called back to his former home in the jungle to investigate",
        "photo": "legend_of_tarzan.jpg",
        "others": null,
        "ShowTime": {
          "Monday": "11:30 p.m , 1:30 a.m",
          "Tuesday": "11:30 p.m , 1:30 a.m",
          "Wednesday": "11:30 p.m , 1:30 a.m",
          "Thursday": "11:30 p.m , 1:30 a.m",
          "Friday": "11:30 p.m , 1:30 a.m",
          "Saturday": "11:30 p.m , 1:30 a.m",
          "Sunday": "11:30 p.m , 1:30 a.m"
        }
      }
    ]
  }
]

Это моеCinema.java учебный класс

public class Cinemas
        extends AppCompatActivity {
    private static final String TAG = "RecyclerViewExample";
    private List<ItemObjects> feedsList;
    private RecyclerView mRecyclerView;
    private CinemaAdapter adapter;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cinemas);
        Bundle bundle = new Bundle();
        //
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Cinemax List");

        // Initialize recycler view
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        progressBar.setVisibility(View.VISIBLE);

        // Downloading data from below url
        // internet connectivity........
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        final String url = "http://10.0.2.2/UgandaEntertainment/Cinema/fetch.php";
        if(netInfo != null && netInfo.isConnectedOrConnecting()) {
            new AsyncHttpTask().execute(url);
        } else {
            Toast.makeText(this, "No network connection! , please check your connectivity", Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public class AsyncHttpTask
            extends AsyncTask<String, Void, Integer> {

        @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();
                // 200 represents HTTP OK
                if(statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = r.readLine()) != null) {
                        response.append(line);
                    }
                    parseResult(response.toString());
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
                }
            } catch(Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {
            // Download complete. Let us update UI
            progressBar.setVisibility(View.GONE);
            if(result == 1) {
                adapter = new CinemaAdapter(Cinemas.this, feedsList);
                mRecyclerView.setAdapter(adapter);
            } else {
                Toast.makeText(Cinemas.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void parseResult(String result) {
        try {
            JSONArray ar = new JSONArray(result);
            feedsList = new ArrayList<>();
            for(int i = 0; i < ar.length(); i++) {
                JSONObject obj = ar.getJSONObject(i);
                ItemObjects item = new ItemObjects();

                item.setCinemaName(obj.optString("Cinemax"));
                item.setContact(obj.optString("Contacts"));
                item.setCinemaxPhoto(obj.optString("CinemaxPhoto"));
                item.setLongitude(obj.optString("Longitude"));
                item.setLatitude(obj.optString("Latitude"));
                //Here you have another Movie Json Array so get it in JSONArray
                JSONArray movieArray = obj.getJSONArray("Movie");
                //get the first object of Movie  JSONArray and use it.
                JSONObject movieObject = movieArray.getJSONObject(0);
                item.setMovieName(movieObject.optString("MovieName"));
                //This JSOn object to get SHOWTIME object
                JSONObject showTime = movieObject.getJSONObject("ShowTime");
                item.setMonday(showTime.optString("Monday"));
                item.setTuesday(showTime.optString("Tuesday"));
                item.setWednesday(showTime.optString("Wednesday"));
                item.setThursday(showTime.optString("Thursday"));
                item.setFriday(showTime.optString("Friday"));
                item.setSaturday(showTime.optString("Saturday"));
                item.setSunday(showTime.optString("Sunday"));
                item.setSynopsis(movieObject.optString("Synopsis"));
                item.setPhoto(movieObject.optString("photo"));
                feedsList.add(item);
            }
        } catch(JSONException e) {
            e.printStackTrace();
        }
    }
}

Это моеCinemaAdapter.java Учебный класс. вonBindViewHolder() метод, я пытаюсь отправитьMovieName,MovieImage,... отправить их во 2-й RecyclerView, который проводитсяLoadingMovies.java класс для перезагрузки списка фильмов в 2ndRecyclerView.

public class CinemaAdapter
        extends RecyclerView.Adapter<CinemaViewHolders> {
    String url = "http://10.0.2.2/UgandaEntertainment/CinemaPics/";
    private List<ItemObjects> itemList = null;
    private Context context;

    private ArrayList<ItemObjects> arraylist;

    public CinemaAdapter(Context context, List<ItemObjects> itemList) {
        this.itemList = itemList;
        this.context = context;
    }

    @Override
    public CinemaViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cinema_list, parent, false);
        CinemaViewHolders rcv = new CinemaViewHolders(layoutView, context);
        return rcv;
    }

    public static String encodeTobase64(Bitmap image) {
        Bitmap immagex = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immagex.compress(Bitmap.CompressFormat.JPEG, 90, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
        // Log.e("LOOK", imageEncoded);
        return imageEncoded;
    }

    @Override
    public void onBindViewHolder(final CinemaViewHolders holder, final int position) {
        final ItemObjects feedItems = itemList.get(position);

        holder.root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                Intent intent = new Intent(CinemaAdapter.this.context, LoadingMovies.class);
                intent.putExtra(CinemaViewHolders.KEY_MOVIE_NAME, feedItems.getMovieName());
                intent.putExtra(CinemaViewHolders.KEY_MOVIE_IMAGE, feedItems.getPhoto());
                intent.putExtra(CinemaViewHolders.KEY_CINEMA_NAME, feedItems.getCinemaName());
                //
                context.startActivity(intent);
            }
        });

        //Download image using picasso library
        Picasso.with(context).load(url + feedItems.getCinemaxPhoto()).error(R.drawable.placeholder).
                resize(500, 500).placeholder(R.drawable.placeholder).into(holder.countryPhoto);
        holder.countryName.setText(itemList.get(position).getCinemaName());
    }

    @Override
    public int getItemCount() {
        return (null != itemList ? itemList.size() : 0);
    }
}

ЭтоLoadingMovies.java класс, где я пыталсяget() Список фильмов в соответствующих кинотеатрах.

public class LoadingMovies
        extends AppCompatActivity {
    private static final String TAG = "RecyclerViewExample";
    private List<ItemObjects> feedsList;
    private RecyclerView mRecyclerView;
    private LoadingMoviesAdapter adapter;
    private ProgressBar progressBar;
    private String moviename = "MovieName";
    private String moviepic = "photo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ntinda);
        //
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Now Showing Ntinda ");
        Bundle bundle = getIntent().getExtras();
        Bundle extras = getIntent().getExtras();
        String imageString = extras.getString(NtindaCinemaViewHolders.KEY_MOVIE_IMAGE);
        // Initialize recycler view
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view1);
      /*  mRecyclerView.setLayoutManager(new LinearLayoutManager(this));*/
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return (3 - position % 4);
            }
        });
        mRecyclerView.setLayoutManager(manager);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar1);
        progressBar.setVisibility(View.VISIBLE);
        // Downloading data from below url
        // internet connectivity........
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        final String url = "http://10.0.2.2/UgandaEntertainment/Cinema/fetch.php";
        if(netInfo != null && netInfo.isConnectedOrConnecting()) {
            new AsyncHttpTask().execute(url);
        } else {
            Toast.makeText(this, "No network connection! , please check your connectivity", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public class AsyncHttpTask
            extends AsyncTask<String, Void, Integer> {
        @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();
                // 200 represents HTTP OK
                if(statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = r.readLine()) != null) {
                        response.append(line);
                    }
                    parseResult(response.toString());
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
                }
            } catch(Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {
            // Download complete. Let us update UI
            progressBar.setVisibility(View.GONE);
            if(result == 1) {
                adapter = new LoadingMoviesAdapter(LoadingMovies.this, feedsList);
                mRecyclerView.setAdapter(adapter);
            } else {
                Toast.makeText(LoadingMovies.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void parseResult(String result) {
        try {
            JSONArray ar = new JSONArray(result);
            feedsList = new ArrayList<>();
            for(int i = 0; i < ar.length(); i++) {
                JSONObject obj = ar.getJSONObject(i);
                ItemObjects item = new ItemObjects();
                // declaring bundle
                // what should i put here to access the movies and showTime????
                Bundle bundle = getIntent().getExtras();
                //      moviename = bundle.getString(CinemaViewHolders.KEY_MOVIE_NAME);
                //   moviepic = bundle.getString(CinemaViewHolders.KEY_MOVIE_IMAGE);
                ItemObjects huxy = new ItemObjects();
                JSONArray movieArray = obj.getJSONArray("Movie");
                //get the first object of Movie  JSONArray and use it.
                JSONObject movieObject = movieArray.getJSONObject(0);
                item.setMovieName(movieObject.optString(huxy.getMovieName()));
                //This JSON object to get SHOWTIME object
                JSONObject showTime = movieObject.getJSONObject("ShowTime");
                item.setPhoto(movieObject.optString("photo"));
                feedsList.add(item);
            }
        } catch(JSONException e) {
            e.printStackTrace();
        }
    }
}

Это адаптерLoadingMoviesAdapter.java

public class LoadingMoviesAdapter
        extends RecyclerView.Adapter<NtindaCinemaViewHolders> {
    private String url = "http://10.0.2.2/UgandaEntertainment/Ntinda/NtindaPics/";
    private List<ItemObjects> itemList = null;
    private Context context;
    public View root = null;

    private ArrayList<ItemObjects> arraylist;

    public LoadingMoviesAdapter(Context context, List<ItemObjects> itemList) {
        this.itemList = itemList;
        this.context = context;
    }

    @Override
    public NtindaCinemaViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.ntinda_cinema_list, parent, false);
        NtindaCinemaViewHolders rcv = new NtindaCinemaViewHolders(layoutView, context);
        return rcv;
    }

    public static String encodeTobase64(Bitmap image) {
        Bitmap immagex = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immagex.compress(Bitmap.CompressFormat.JPEG, 90, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
        // Log.e("LOOK", imageEncoded);
        return imageEncoded;
    }

    @Override
    public void onBindViewHolder(final NtindaCinemaViewHolders holder, final int position) {
        final ItemObjects feedItem = itemList.get(position);
        holder.root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap attachedbitmap = ((BitmapDrawable) holder.moviepic.getDrawable()).getBitmap();
                Intent intent = new Intent(LoadingMoviesAdapter.this.context, MovieScrollingActivity.class);
                intent.putExtra(NtindaCinemaViewHolders.KEY_SYNOPSIS, feedItem.getSynopsis());
                intent.putExtra(NtindaCinemaViewHolders.KEY_MOVIE_IMAGE, encodeTobase64(attachedbitmap));
                context.startActivity(intent);
            }
        });
        //Download image using picasso library
        Picasso.with(context).load(url + feedItem.getPhoto()).error(R.drawable.placeholder).
                resize(500, 500).placeholder(R.drawable.placeholder)
                .into(holder.moviepic);
        holder.moviename.setText(itemList.get(position).getMovieName());
    }

    @Override
    public int getItemCount() {
        return (null != itemList ? itemList.size() : 0);
    }
}

Я думаю, что я должен настроитьLoadingMovies класс, особенно вParseResult () Метод. Какие-либо предложения?

 EpicPandaForce10 авг. 2016 г., 21:10
Не пишите ту же логику десериализации вдва разных местаразве ты не слышалDRY (Не повторяй себя)?
 Prune11 авг. 2016 г., 02:03
Пожалуйста, прочтите и соблюдайте правила публикации в справочной документации.Минимальный, полный, проверяемый пример применяется здесь. Похоже, это весь ваш код, а не минимальный набор для воспроизведения проблемы.

Ответы на вопрос(0)

Ваш ответ на вопрос