如何在Fragment中应用RecycleView

时间:2017-06-13 04:10:27

标签: android android-fragments

我有一个片段,名字是galery。在片段galery中,我将展示包含名称列表的recycleView。但是我在这个脚本中发现了一个错误:

LinearLayoutManager llm = new LinearLayoutManager(this);

这是我的完整代码:

public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;

ArrayList<HashMap<String, String>> list_data;

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
    String url = "http://bls.hol.es/read.php";

    lvhape = (RecyclerView) rootView.findViewById(R.id.lvhape);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    lvhape.setLayoutManager(llm);

    requestQueue = Volley.newRequestQueue(galery.this);
    list_data = new ArrayList<HashMap<String, String>>();

    stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("response", response);
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for (int a = 0; a < jsonArray.length(); a++) {
                    JSONObject json = jsonArray.getJSONObject(a);
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("id", json.getString("id"));
                    map.put("nama", json.getString("nama"));
                    map.put("alamat", json.getString("alamat"));
                    map.put("poto", json.getString("poto"));
                    list_data.add(map);
                    AdapterList adapter = new AdapterList(galery.this, list_data);
                    lvhape.setAdapter(adapter);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
    requestQueue.add(stringRequest);
    return rootView;
}

}

4 个答案:

答案 0 :(得分:1)

尝试使用片段在.xml类中创建适配器和模型类以及RecyclerView。

 public class Event extends Fragment {
    RecyclerView recyclerView;
    private Event_Adapter event_adapter;
    public Event_Model event_model;
    public static List<Event_Model> list;
    RecyclerView.LayoutManager mLayoutManager;
    private static final String FETCH_ID = "id";
    private static final String FETCH_NAME = "event_type";
    private static final String FETCH_MOBILE = "contact";
    private static final String FETCH_DATE = "date";
    private static final String FETCH_IMAGE = "uri";
    public static final String FETCH_DETAIL = "Your Url";
    String type,number,date,uri,id;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v= inflater.inflate(R.layout.fragment_event, container, false);

        list = new ArrayList<Event_Model>();
        recyclerView = (RecyclerView) v.findViewById(R.id.event_recycler);
        mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        fetchdetails();

         return v;
    }
    private void fetchdetails(){
        StringRequest jor = new StringRequest(Request.Method.POST, FETCH_DETAIL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
               /*       Toast.makeText(getActivity(),response,Toast.LENGTH_LONG).show();*/

                        try {
                            JSONArray ja = new JSONArray(response);
                            for (int i = 0; i < ja.length(); i++) {

                                JSONObject jsonObject = ja.getJSONObject(i);


               Integer.parseInt(jsonObject.optString("id").toString());
                                type =     jsonObject.getString(FETCH_NAME);
                                number = jsonObject.getString(FETCH_MOBILE);
                                date = jsonObject.getString(FETCH_DATE);
                                uri = jsonObject.getString(FETCH_IMAGE);
                                id =     jsonObject.getString(FETCH_ID);
                   event_model = new Event_Model(type,number,date,uri,id);
                                list.add(event_model);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        event_adapter= new Event_Adapter(getActivity(), list);
                        recyclerView.setAdapter(event_adapter);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {


                        Log.e("Volley", "Error");

                    }
                }

        );
        RetryPolicy retryPolicy=new DefaultRetryPolicy(60000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        jor.setRetryPolicy(retryPolicy);
        VolleySingleton.getInstance(getActivity()).addToRequestQueue(jor);
    }

}

答案 1 :(得分:1)

我做了一些更改,它在我的应用程序中正常运行,并且如果在评论中提到任何错误。

public class GalaryFragment extends Fragment {
private RecyclerView recyclerView;
private List<ProductModel> list1;
private ProductModel productMode;
private ProductAdapter productAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.frament_galary, container, false);
}   
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    String url = "http://bls.hol.es/read.php";
    mRecyclerView = (RecyclerView) view.findViewById(R.id.lvhape);
     list1 = new ArrayList<>();
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
    cashbackAdapter = new ProductAdapter(getActivity(), list1);
    mRecyclerView2.setAdapter(productAdapter); 
    final ProgressDialog dialog = new ProgressDialog(getActivity());
    dialog.setMessage("Loading......");
    dialog.show();
    StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //Toast.makeText(getActivity(),response+"",Toast.LENGTH_LONG).show();
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String id = jsonObject.getString("id");
                            String name = jsonObject.getString("name");
                            String image = jsonObject.getString("image");
                            productModel = new ProductModel(id, name, image);
                            list1.add(productModel);
                        }
                        productAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", "Error");
        }
    });
    VolleySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
     }
 }

ProductAdapter代码:

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {
private List<ProductModel> list;
private Context mContext;

public ProductAdapter(Context mContext, List<ProductModel> list) {
    this.mContext = mContext;
    this.list=list;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_galary, parent, false);
    return new MyViewHolder(itemView);
}


@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    final ProductModel productModel=list.get(position);
    holder.name.setText(productModel.getName());
    Picasso.with(mContext)
            .load(productModel.getImage())
            .placeholder(R.mipmap.ic_launcher)
            .error(R.mipmap.ic_launcher)
            .into(holder.iv);

}

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

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView name;
    public ImageView iv;
    public MyViewHolder(View view) {
        super(view);
        name = (TextView) view.findViewById(R.id.name);
        iv = (ImageView) view.findViewById(R.id.image);
        }
     }
   }

PoductModel代码:

  public class ProductModel {
  String id;
  String name;
  String image;

 public nameModel(String id, String name, String image) {
    this.id = id;
    this.name = name;
    this.image = image;
}

public String getId() {
    return id;
}

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

public String getname() {
    return name;
}

public void setname(String name) {
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
    }
}

VolleySingleton课程:

public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private VolleySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

public static synchronized VolleySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new VolleySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
   }
}

答案 2 :(得分:0)

onCreate()将在onCreateView()方法之前调用,因此getView()将返回null 试试这个

public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;

ArrayList<HashMap<String, String>> list_data;

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

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_galery, container, false);

    return rootView;
}


public void onViewCreated(View view, Bundle savedInstanceState) {
    String url = "http://bls.hol.es/read.php";

    lvhape = (RecyclerView) view.findViewById(R.id.lvhape);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    lvhape.setLayoutManager(llm);

    requestQueue = Volley.newRequestQueue(getActivity());
    list_data = new ArrayList<HashMap<String, String>>();

    stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("response", response);
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for (int a = 0; a < jsonArray.length(); a++) {
                    JSONObject json = jsonArray.getJSONObject(a);
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("id", json.getString("id"));
                    map.put("nama", json.getString("nama"));
                    map.put("alamat", json.getString("alamat"));
                    map.put("poto", json.getString("poto"));
                    list_data.add(map);
                    AdapterList adapter = new AdapterList(galery.this, list_data);
                    lvhape.setAdapter(adapter);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
    requestQueue.add(stringRequest);
}

答案 3 :(得分:0)

试试这个

LOC_IC  USERNAME   COMMENTS
5120    admin      administrator
5125    user3      n/a