2017-03-26 3 views
0

Android Studio의 프로젝트에서 RecyclerView에 여러 영화를 나열해야 했으므로 이 경우에는 RESTful API에서 여러 가지 방법으로 20). 이제 모든 것을 설정했고 정적 더미 컨텐츠는 cardview를 사용하여 recyclerview에 표시됩니다. 그럼에도 불구하고, 전환 할 때 실제 데이터 (RESTful API로부터)에 문제가 있습니다. 영화 모델RecyclerView는 수동으로 목록에 추가 할 때 사용자 지정 개체와 함께 작동하지만 RESTful 서비스의 데이터로 인스턴스화 할 때는 작동하지 않습니다.

public class MainActivity extends RecyclerViewActivity { 

private static List<Film> listFilm; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setLayoutManager(new LinearLayoutManager(this)); 
    setAdapter(new FilmAdapter()); 

    listFilm = new ArrayList<>(); 

    listFilm.add(new Film("Star Wars", "Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire.")); 
    listFilm.add(new Film("E.T. the Extra-Terrestrial", "A science fiction fairytale about an extra-terrestrial who is left behind on Earth and is found by a young boy who befriends him. This heart-warming fantasy from Director Steven Spielberg became one of the most commercially successful films of all time.")); 
    listFilm.add(new Film("Jurassic Park", "A wealthy entrepreneur secretly creates a theme park featuring living dinosaurs drawn from prehistoric DNA. Before opening day, he invites a team of experts and his two eager grandchildren to experience the park and help calm anxious investors. However, the park is anything but amusing as the security systems go off-line and the dinosaurs escape.")); 
    listFilm.add(new Film("The Lion King", "A young lion cub named Simba can't wait to be king. But his uncle craves the title for himself and will stop at nothing to get it.")); 
    listFilm.add(new Film("Independence Day", "On July 2, a giant alien mothership enters orbit around Earth and deploys several dozen saucer-shaped 'destroyer' spacecraft that quickly lay waste to major cities around the planet. On July 3, the United States conducts a coordinated counterattack that fails. On July 4 the a plan is devised to gain access to the interior of the alien mothership in space in order to plant a nuclear missile.")); 
    listFilm.add(new Film("Titanic", "84 years later, a 101-year-old woman named Rose DeWitt Bukater tells the story to her granddaughter Lizzy Calvert, Brock Lovett, Lewis Bodine, Bobby Buell and Anatoly Mikailavich on the Keldysh about her life set in April 10th 1912, on a ship called Titanic when young Rose boards the departing ship with the upper-class passengers and her mother, Ruth DeWitt Bukater, and her fiancé, Caledon Hockley. Meanwhile, a drifter and artist named Jack Dawson and his best friend Fabrizio De Rossi win third-class tickets to the ship in a game. And she explains the whole story from departure until the death of Titanic on its first and last voyage April 15th, 1912 at 2:20 in the morning.")); 
    listFilm.add(new Film("Star Wars: Episode I - The Phantom Menace", "Anakin Skywalker, a young slave strong with the Force, is discovered on Tatooine. Meanwhile, the evil Sith have returned, enacting their plot for revenge against the Jedi.")); 
    listFilm.add(new Film("Harry Potter and the Philosopher's Stone", "Harry Potter has lived under the stairs at his aunt and uncle's house his whole life. But on his 11th birthday, he learns he's a powerful wizard -- with a place waiting for him at the Hogwarts School of Witchcraft and Wizardry. As he learns to harness his newfound powers with the help of the school's kindly headmaster, Harry uncovers the truth about his parents' deaths -- and about the villain who's to blame.")); 
    listFilm.add(new Film("The Lord of the Rings: The Fellowship of the Ring", "Young hobbit Frodo Baggins, after inheriting a mysterious ring from his uncle Bilbo, must leave his home in order to keep it from falling into the hands of its evil creator. Along the way, a fellowship is formed to protect the ringbearer and make sure that the ring arrives at its final destination: Mt. Doom, the only place where it can be destroyed.")); 
    listFilm.add(new Film("Spider-Man", "After being bitten by a genetically altered spider, nerdy high school student Peter Parker is endowed with amazing powers.")); 

} 

어댑터는 다음과 같습니다 :

private class FilmAdapter extends RecyclerView.Adapter<RowHolder> { 

    Context context; 

    public Context getContext() { 
     return this.context; 
    } 

    @Override 
    public RowHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     return new RowHolder(getLayoutInflater().inflate(R.layout.row, parent, false)); 
    } 

    @Override 
    public void onBindViewHolder(RowHolder holder, int position) { 
     Film movie = listFilm.get(position); 

     TextView title = holder.title; 
     title.setText(movie.getTitle()); 
     TextView desc = holder.desc; 
     desc.setText(movie.getDescription()); 
     ImageView poster = holder.poster; 
     Picasso.with(getApplicationContext()).load("http://cdn2-www.comingsoon.net/assets/uploads/2015/03/avengersorder5.jpg").into(poster); 
    } 

    @Override 
    public int getItemCount() { 
     return listFilm.size(); 
    } 
} 

그리고 ViewHolder 클래스는 다음과 같습니다

private class RowHolder extends RecyclerView.ViewHolder { 

    TextView title = null; 
    TextView desc = null; 
    ImageView poster = null; 

    public RowHolder(View itemView) { 
     super(itemView); 

     title = (TextView) itemView.findViewById(R.id.title); 
     desc = (TextView) itemView.findViewById(R.id.desc); 
     poster = (ImageView) itemView.findViewById(R.id.poster); 
    } 

} 

때 여기 (데이터가 표시됩니다) 수동으로 데이터를 내 MainActivity.java 코드 내 RESTful API MainActivity.java에 문의하면 다음과 같이 보입니다.

public class MainActivity extends R ecyclerViewActivity는 {

private static List<Film> listFilm; 
public static final String apiURL = "https://api.themoviedb.org/4/list/10?page=1&api_key=8e20230f25939a349c2e37680cdaff95&sort_by=release_date.asc"; 
private JSONObject jsonObject; 
private JSONArray jsonArray; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setLayoutManager(new LinearLayoutManager(this)); 
    setAdapter(new FilmAdapter()); 

    listFilm = new ArrayList<>(); 

    RequestQueue queue = Volley.newRequestQueue(this); 

    StringRequest stringRequest = new StringRequest(Method.GET, apiURL, 
      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        Toast.makeText(getApplicationContext(), "RADI", Toast.LENGTH_SHORT).show(); 

        try { 


         jsonObject = new JSONObject(response); 
         jsonArray = jsonObject.getJSONArray("results"); 
         int i = 0; 

         while(i < jsonArray.length()) { 
          JSONObject movie = jsonArray.getJSONObject(i); 

          Film movieInstance = new Film(movie.getString("original_title"), movie.getString("overview"), "https://image.tmdb.org/t/p/w500" + movie.getString("backdrop_path")); 
          listFilm.add(movieInstance); 
          i ++ ; 
         } 

        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
      }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Toast.makeText(getApplicationContext(), "NE RADI", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

}

나머지 두 경우 모두 동일합니다. 나는 여러 번 모든 것을 기록했다. 데이터는 유효하다. 모든 것이 괜찮은 목록은 API에서 상응하는 20 개의 영화로 채워진다. 그래서 어떤 생각? 요약하면 첫 번째 경우에는 앱이 정상적으로 작동하고 후자에서는 데이터가 표시되지 않습니다. 누구든지 알고 있거나 비슷한 문제가 있습니까? 미리 감사드립니다.

답변

0

데이터를 변경했다는 것을 어댑터에 알려야합니다. 첨부 된 리사이클러에이를 알리고 뷰를 업데이트합니다.

당신이 API에서 항목을 추가 루프 후,이 추가

adapter.notifyDataSetChanged(); 

당신이 있기 때문에 리사이클 (에서 onCreate 후) 초기 배치를 수행하는 시간이 필요하지 않은 첫 번째 예에서, 내용은 이미 있습니다.

+0

감사합니다. 그것을 시도, 매력처럼 작동합니다. 이걸 몰랐어. 다시 한번 감사드립니다. – nikjov92

+0

물론 문제는 없습니다. 시작하면 [공식 문서] (https://developer.android.com/guide/index.html)에서 볼 수 있습니다 (예 : [이 페이지] (https://developer.android.com)). /guide/topics/ui/layout/recyclerview.html)을 참조하십시오. 또한 문제를 해결할 때 대답을 수락해야합니다. – RobCo

+0

나는 시험을 보았다. 그러나 내가 여기에서 새로운 이래로 명백하게 투표 할 수 없다. 나는 즉시 그 화살 열쇠를 밀었다. 나는 1 개의 명성을 가지고있다. (현재) – nikjov92