如何在Fragment Android Recyclerview Volley中显示JSON数据?

时间:2018-08-02 07:21:38

标签: android android-fragments android-recyclerview android-volley

请帮助解决以下问题,问题是即使互联网条件开启,数据也不想出现在fragment家中

我的HomeFragment代码:

package untag.adproj.lestari.lestari.Home;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;

import untag.adproj.lestari.lestari.R;




public class HomeFragment extends Fragment {
    private String URL="http://pembuatanprogram.000webhostapp.com";
    private RecyclerAdapter recyclerAdapter;
    private RecyclerView recyclerView;
    private ArrayList<Data> listdata;

    private GridLayoutManager gridLayoutManager;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(gridLayoutManager);

        listdata = new ArrayList<Data>();

        AmbilData();



        recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
        recyclerView.setAdapter(recyclerAdapter);
        recyclerAdapter.notifyDataSetChanged();

        return view;
    }

    private void AmbilData() {
        JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response.length()>0){
                            for (int i =0 ; i<response.length();i++){
                                try {
                                    JSONObject data = response.getJSONObject(i);
                                    Data item = new Data();
                                    item.setId(data.getString("id"));
                                    item.setJudul(data.getString("judul"));
                                    item.setHarga(data.getString("harga"));
                                    item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
                                    listdata.add(item);
                                    recyclerAdapter.notifyDataSetChanged();
                                } catch (JSONException e) {
                                }
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){

        };
        Volley.newRequestQueue(getActivity()).add(aarRequest);
    }


}

我的RecyclerAdapter代码:

package untag.adproj.lestari.lestari.Home;


import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

import untag.adproj.lestari.lestari.R;


public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    private ArrayList<Data> listdata;
    private Activity activity;
    private Context context;

    public RecyclerAdapter(Activity activity, ArrayList<Data> listdata) {
        this.listdata = listdata;
        this.activity = activity;
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_home_list, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        //holder.mImage.setImageResource(listdata.get(position).getThubnail());
        holder.id.setText(listdata.get(position).getId());
        holder.judul.setText(listdata.get(position).getJudul());
        holder.harga.setText(listdata.get(position).getHarga());
        final ViewHolder x=holder;
        Glide.with(activity)
                .load(listdata.get(position).getThubnail())
                .into(holder.thumbnail);
        holder.id.setVisibility(View.GONE);
    }
    @Override
    public int getItemCount() {
        return listdata.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private CardView cv;
        private TextView id,judul,harga;
        private ImageView thumbnail;

        public ViewHolder(View v) {
            super(v);
            cv=(CardView)v.findViewById(R.id.card_view);
            id=(TextView)v.findViewById(R.id.id);
            judul=(TextView)v.findViewById(R.id.judul);
            harga=(TextView)v.findViewById(R.id.harga);
            thumbnail=(ImageView)v.findViewById(R.id.thumbnail);
        }
    }

}

我的数据代码:

package untag.adproj.lestari.lestari.Home;

public class Data {
    private String id;
    private String judul;
    private String harga;
    private String thubnail;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getJudul() {
        return judul;
    }
    public void setJudul(String judul) {
        this.judul = judul;
    }

    public String getHarga() {
        return harga;
    }
    public void setHarga(String harga) {
        this.harga = harga;
    }

    public String getThubnail() {
        return thubnail;
    }
    public void setThubnail(String thubnail) {
        this.thubnail = thubnail;
    }

}

我的代码刷新来自Youtube 但在本教程中它不使用片段,请任何人帮助我

3 个答案:

答案 0 :(得分:1)

您有一个错误的观点,那就是没有更新recycler view的列表,您在代码listdata.add(item);中添加值的列表属于您的片段

请在适配器中添加以下方法

   public void addData(List<Data> data) {
        listdata.addAll(data);
        notifyDataSetChanged();
    }

并按如下所示编辑AmbilData函数

private void AmbilData() {
        JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response.length()>0){
                            for (int i =0 ; i<response.length();i++){
                                try {
                                    JSONObject data = response.getJSONObject(i);
                                    Data item = new Data();
                                    item.setId(data.getString("id"));
                                    item.setJudul(data.getString("judul"));
                                    item.setHarga(data.getString("harga"));
                                    item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
                                    listdata.add(item);
                                } catch (JSONException e) {
                                }
                            }

                            recyclerAdapter.addData(listdata);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){

        };
        Volley.newRequestQueue(getActivity()).add(aarRequest);
    }

答案 1 :(得分:1)

   package untag.adproj.lestari.lestari.Home;

    import android.content.Context;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;

    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonArrayRequest;
    import com.android.volley.toolbox.Volley;

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

    import java.util.ArrayList;

    import untag.adproj.lestari.lestari.R;




    public class HomeFragment extends Fragment {
        private String URL="http://pembuatanprogram.000webhostapp.com";
        private RecyclerAdapter recyclerAdapter;
        private RecyclerView recyclerView;
        private ArrayList<Data> listdata;
        private ArrayList<Data> tempList;
        private GridLayoutManager gridLayoutManager;

        // TODO: Rename parameter arguments, choose names that match
        // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
        public HomeFragment() {
            // Required empty public constructor
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_home, container, false);

            recyclerView = view.findViewById(R.id.recyclerView);
            recyclerView.setHasFixedSize(true);
            gridLayoutManager = new GridLayoutManager(getActivity(), 2);
            gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(gridLayoutManager);
            tempList = new ArrayList<Data>();
            listdata = new ArrayList<Data>();

            AmbilData();



            recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
            recyclerView.setAdapter(recyclerAdapter);
            recyclerAdapter.notifyDataSetChanged();

            return view;
        }

        private void AmbilData() {
            JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            if (response.length()>0){
                                for (int i =0 ; i<response.length();i++){
                                    try {
                                        JSONObject data = response.getJSONObject(i);
                                        Data item = new Data();
                                        item.setId(data.getString("id"));
                                        item.setJudul(data.getString("judul"));
                                        item.setHarga(data.getString("harga"));
                                        item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
                                        tempList.add(item);
                                        recyclerAdapter.notifyDataSetChanged();
                                    } catch (JSONException e) {
                                    }
                                }
                              listdata.clear();
                              listdata.addAll(tempList);
                              recyclerAdapter.notifyDataSetChanged();

                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    }){

            };
            Volley.newRequestQueue(getActivity()).add(aarRequest);
        }


    }

使用临时列表,然后使用addAll()方法,然后调用notifyDataSetChanged()方法。

答案 2 :(得分:0)

如果您想从循环中通知适配器,则应该进行notifyItemInserted()的操作,否则将notifyDataSetChanged()留在循环之外。

喜欢这个

    for (int i =0 ; i<response.length();i++){
                                        try {
                                            JSONObject data = response.getJSONObject(i);
                                            Data item = new Data();
                                            item.setId(data.getString("id"));
                                            item.setJudul(data.getString("judul"));
                                            item.setHarga(data.getString("harga"));
                                            item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
                                            listdata.add(item);
                recyclerAdapter.notifyItemInserted(listdata.size()-1); //To update the recyclerview one by one from a loop.
                                        } catch (JSONException e) {
                                        }
                                    }


    // OR


for (int i =0 ; i<response.length();i++){
                                        try {
                                            JSONObject data = response.getJSONObject(i);
                                            Data item = new Data();
                                            item.setId(data.getString("id"));
                                            item.setJudul(data.getString("judul"));
                                            item.setHarga(data.getString("harga"));
                                            item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
                                            listdata.add(item);
                                        } catch (JSONException e) {
                                        }
                                    }
recyclerAdapter.notifyDataSetChanged(); //To update the whole recyclerview in one shot