Заполнение RecyclerView с использованием залпа во фрагментах - PullRequest
0 голосов
/ 14 января 2019

Я использую залп для анализа Json и заполнения моего Recyclerview во фрагменте. Я обнаружил похожие потоки, где решения включали размещение адаптера в методе onResponse или размещение setAdapter перед setLayoutManager, которые у меня не работали. Я попытался зарегистрировать Json, который сработал, поэтому я уверен, что проблема связана с адаптером.

Я включил код в свой фрагмент, а также класс адаптера.

Я пробовал разные эмуляторы, настраивал адаптер разными способами и уведомлял адаптер об изменении набора данных.

private RequestQueue mQueue;


@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mlayoutManager = new LinearLayoutManager(getContext());

    final RecyclerView.Adapter adapter = new WatchListAdapter(names, names, names, names, names);

    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(mlayoutManager);


    mQueue = Volley.newRequestQueue(getContext());
    String url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=gbp";
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {



            for(int i = 0; i<response.length();i++){
                JSONObject obj = null;
                try {
                    obj = response.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                String name = null;
                try {
                    name = obj.getString("id");
                    names.add(name);

                    adapter.notifyDataSetChanged();


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



            }


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("Volley in Tab4", "not working");

        }
    });
    mQueue.add(request);

Это используемый адаптер.

открытый класс WatchList_CustomRow расширяет ArrayAdapter {

ArrayList<String> ranks = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
ArrayList<String> prices = new ArrayList<>();
ArrayList<String> caps= new ArrayList<>();
ArrayList<String> changes = new ArrayList<>();

public WatchList_CustomRow(@NonNull Context context,ArrayList<String> rank1, ArrayList<String> names1, ArrayList<String> prices1, ArrayList<String> caps1, ArrayList<String> changes1) {
    super(context, R.layout.activity_watch_list__custom_row,rank1);
     names = names1;
    prices = prices1;
    caps=caps1;
    changes=changes1;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View customView = inflater.inflate(R.layout.activity_watch_list__custom_row, parent, false);

    String singleRank = getItem(position);
    String singleName = names.get(position);
    String singlePrice = prices.get(position);
    String singleCap= caps.get(position);
    String singleChange = changes.get(position);


    TextView rankTextView = customView.findViewById(R.id.rankTextView);
    TextView nameTextView = customView.findViewById(R.id.WatchedCoinName);
    TextView priceTextView = customView.findViewById(R.id.WatchedCoinPrice);
    TextView capTextView = customView.findViewById(R.id.WatchedcoinMarket);
    TextView changeTextView = customView.findViewById(R.id.WatchCoin24Change);


    rankTextView.setText(singleRank);
    //bodyTextView.setText(singleBody);
    nameTextView.setText(singleName);
    priceTextView.setText(singlePrice);
    capTextView.setText(singleCap);
    changeTextView.setText(singleChange);


    return customView;    }

}

Ответы [ 2 ]

0 голосов
/ 15 января 2019

вы даже не передаете данные в Adapter после получения ответа и звоните notifyDatasetChanged. и для лучшего анализа JSON используйте GSON и сопоставьте ваш объект классу Model / Pojo , получите из них arrayList и передайте его адаптеру.

любезно опубликуйте ответ JSON, а затем сможете ответить с лучшим решением для вас.

0 голосов
/ 15 января 2019

Используйте RecyclerView.Adapter и соответствующие методы onCreateViewHolder и onBindViewHolder для привязки вида и данных

...