使用凌空json数据在fragmnet中的Recyclerview?

时间:2016-07-02 05:58:00

标签: android android-fragments fragment android-recyclerview android-adapter

请任何人使用volley来解释片段中的RecyclerView以获取json数据。 我已经在链接编码Google recyclerview in fragment

下面提到了

这是我在android中的第一个项目,所以我无法理解编码。 请任何人帮助我。

我的网络编码:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View drawer = inflater.inflate(R.layout.fragment_progress, container, false);
    orderLists = new ArrayList<>();

    getProgressData();

    recyclerView = (RecyclerView) drawer.findViewById(R.id.progress);
    adapter = new ProgressOrderListAdapter(orderLists, this);
    adapter.clearAdaptor();
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return recyclerView;
}

private void getProgressData(){
    String mobilecustomertoken = SharedPreferencesManager.readPreferenceString("MobileCustomerToken", "D/N");
    JSONObject progressData = new JSONObject();
    try{
        progressData.put("mobilecustomertoken", mobilecustomertoken);
        JsonObjectRequest progressObject = new JsonObjectRequest(1, Common.OrderDetails + "progress", progressData, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject progressResponse) {
                Log.d("Responseprogress", progressResponse.toString());
                try {
                    int status = progressResponse.getInt("status");
                    if(status == 1) {
                        progressOrderProgress(progressResponse);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("Response", "PROGRESS ERROR");
            }
        });
        progressObject.setShouldCache(false);
        ServiceBellApp.getInstance().addToRequestQueue(progressObject);
    }
    catch (JSONException localJSONException){
        localJSONException.printStackTrace();
        return;
    }
}

private void progressOrderProgress(JSONObject progressResponse) throws JSONException {
    JSONArray result = progressResponse.getJSONArray("orderdata");
    OrderList orderListModule = new OrderList();
    for(int i=0; i<result.length(); i++){
        JSONObject orderData = result.getJSONObject(i);
        orderListModule.setPackage_name(orderData.getString("package_name"));
        orderListModule.setOrderdate(orderData.getString("orderdate"));
        orderListModule.setServicedate(orderData.getString("servicedate"));
        orderListModule.setServicetime(orderData.getString("servicetime"));
        orderListModule.setOrderid(orderData.getString("orderid"));
        orderListModule.setOrdstatus(orderData.getString("ordstatus"));
        orderListModule.setOrderamount(orderData.getInt("orderamount"));
    }
    orderLists.add(orderListModule);
}

我的适配器代码:

public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.ViewHolder> {
List<OrderList> List;
private FragmentPending mContext;

public OrderListAdapter(List<OrderList> List, FragmentPending context) {
    this.mContext = context;
    this.List = List;

}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_list_view, null);
    ViewHolder holder = new ViewHolder(view);
    // this is where the each item is inflated.

    return holder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    OrderList orderListsPos = List.get(position);
    // this is where the data for each item is assigned
    holder.textViewPackageName.setText(orderListsPos.getPackage_name());
    holder.textOrderdate.setText(orderListsPos.getOrderdate());
    holder.textServicedate.setText(orderListsPos.getServicedate());
    holder.textServicetime.setText(orderListsPos.getServicetime());
    holder.textOrderid.setText(orderListsPos.getOrderid());
    holder.textOrderamount.setText("Rs." + orderListsPos.getOrderamount());
    holder.textStatus.setText(orderListsPos.getOrdstatus());

}

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

public void clearAdaptor() {
    List.clear();
}


public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView textViewPackageName;
    public TextView textServicedate;
    public TextView textServicetime;
    public TextView textOrderdate;
    public TextView textOrderid;
    public TextView textOrderamount;
    public TextView textStatus;

    public ViewHolder(View itemView) {
        super(itemView);
        textViewPackageName = (TextView) itemView.findViewById(R.id.productName);
        textOrderdate = (TextView) itemView.findViewById(R.id.orderdate);
        textOrderid = (TextView) itemView.findViewById(R.id.orderno);
        textOrderamount = (TextView) itemView.findViewById(R.id.orderprice);
        textStatus = (TextView) itemView.findViewById(R.id.orderstatus);

    }
}}

3 个答案:

答案 0 :(得分:2)

首先你需要四件事

  

1)包含每个回收站视图布局项的布局

     

2)用于创建每个布局的视图持有者

     

3)用于保存数据的模型类

     

4)Recycler Adapter,处理每个布局项目的数据

首先创建一个布局项

for eample允许创建一个仅包含TextView的视图

<强> XML

each_item.xml

   <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:gravity="start|center_vertical"
        android:textColor="@color/white"
        android:textSize="18sp" />

现在让我们创建一个视图持有者 我将发布视图持有者的代码和RecyclerAdaptor

public class Adaptor extends RecyclerView.Adapter<Adaptor.ViewHolder> {
  List<Model> List = Collections.emptyList();
  private Context mContext;
  private LayoutInflater inflater;

  public Adaptor(Context context, List<Model> List) {
    inflater = LayoutInflater.from(context);
    this.mContext = context;
    this.List = List;

 }


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.each_item, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    // this is where the each item is inflated.

    return holder;
}

@Override
public void onBindViewHolder(WinnersViewHolder holder, int position) {
    Model mModel = List.get(position); 
    // this is where the data for each item is assigned
    holder.nameView.setText("" + mModel.getName());

}

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

public void clearAdaptor() {
    List.clear();
}


public class ViewHolder extends RecyclerView.ViewHolder {
    protected TextView nameView;

    public ViewHolder(View itemView) {
        super(itemView);
        this.nameView = (TextView) itemView.findViewById(R.id.name);

    }
 }
}

现在是模型类

public class Model {

private String name;

public String getName() {
    return name;
}

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

现在后端已完成,让我们在Fragment上实现它

List<Model> List = new ArrayList<>();
private RecyclerView mRecyclerView;
private Adaptor adaptor;

public Fragment() {
    // constructor of fragment
    // Required empty public constructor
}

onCreatView()中获取recyclerView的ID

 View fragmentView = inflater.inflate(R.layout.fragment_layout, container, false);
 mRecyclerView = (RecyclerView) fragmentView .findViewById(R.id.recycler_view);

然后通过创建对象

将数据传递给Adaptor
    adaptor = new Adaptor(getContext(), List);
    adaptor.clearAdaptor();
    mRecyclerView.setAdapter(adaptor);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

您现在已经完成,只有待处理的是您访问数据表单服务器调用notifyDataSetChanged()adaptor = new Adaptor(getContext(), getList()); getList()返回模型数据而不调用{{1} }。

希望这会有所帮助..

修改 您可以通过两种方式对每个布局项进行渗透:一个位于上方,另一个位于adaptor.clearAdaptor()

onCreateViewHolder

答案 1 :(得分:1)

检查此链接对于初学者来说,了解从开始到掌握RecyclerView的概念是非常有用的。

https://github.com/codepath/android_guides/wiki/Using-the-RecyclerView

希望这有助于您了解回收者视图概念。

答案 2 :(得分:0)

RecycerView + Fragment + Volley

enter image description here

片段代码:

public class DogListFragment extends Fragment{

    private RecyclerView rv;
    private StaggeredGridLayoutManager llm;
    private DogListAdapter adapter;
    private ArrayList<DogModel> dogList;
    private Context context;

    public static DogListFragment getInstance(){
        return new DogListFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        dogList = new ArrayList<>();
        adapter = new DogListAdapter(context, dogList, this);
        getListFromServer();

    }

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

        View view = inflater.inflate(R.layout.fragment_dog_list, parent, false);
        rv = view.findViewById(R.id.rv);
        llm = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rv.setLayoutManager(llm);
        rv.setAdapter(adapter);
        return view;
    }

    public void getListFromServer(){

        String url = "https://dog.ceo/api/breed/hound/images/random/20";
        RequestQueue requestQueue = Volley.newRequestQueue(context);

        StringRequest request = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);

                        JSONArray array = jsonObject.getJSONArray("message");

                        for(int i=0;i<array.length();i++){
                            String imageUrl = array.getString(i);
                            dogList.add(new DogModel(imageUrl));
                        }
                        adapter.updateDataSet(dogList);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, 
            new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
               }
            }
        );

        requestQueue.add(request);
    }

}

完整代码

Woof Repository

它具有以下实现

  • 通过接口进行片段通信
  • 重复使用片段 getSupportFragmentManager()。findFragmentByTag(TAG)
  • 哪个生命周期方法应具有API调用,以便仅被调用 一次
  • 如何在片段中保存RecylcerView状态(滚动位置+内容)
  • 在RecyclerView中分页
  • 通话剩余(排球)
  • 图像渲染(滑行)
  • JSON解析