使用凌空json数据的片段中的Recyclerview?

Posted

技术标签:

【中文标题】使用凌空json数据的片段中的Recyclerview?【英文标题】:Recyclerview in fragmnet using volley json data? 【发布时间】:2016-11-04 13:12:44 【问题描述】:

请任何人解释 RecyclerView 在片段中使用 volley 获取 json 数据。 我已经在下面提到了链接编码Google recyclerview in fragment

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

我的fragmnet编码:

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);

    

【问题讨论】:

该链接的哪个部分您不理解? 概念 5. 为每个视图设置样式并添加一个 RecyclerView 这几乎是直截了当的.. 设计每一行?你对哪一部分有疑问? 我的疑惑是recyclerview和fragment如何连接 我有一个问题要问你,你有没有在Activity 上与RecyclerView 合作过? 【参考方案1】:

首先你需要四样东西

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

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

3 ) 一个模型类来保存数据

4 ) 处理每个布局项的数据的回收器适配器

首先创建一个布局项

例如,让我们创建一个只有TextView 的视图

XML

每个_item.xml

   <TextView
        android:id="@+id/name"
        android:layout_
        android:layout_
        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() 返回模型数据并且不调用adaptor.clearAdaptor()

希望这会有所帮助..

编辑 您可以通过两种方式对每个布局项进行充气 .. 一种在上方,第二种在 onCreateViewHolder

 View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item, null);

【讨论】:

我在 inflater = LayoutInflater.from(context); 中得到错误适配器中的这一行 最后我得到这个错误 java.lang.Throwable: Explicit terminate method 'end' not called。你有什么想法吗? 你能发布你的代码和可能的 LogCat 吗.. 这可能是与 JSON Volley @vinothkumar 相关的一些错误 @vinothkumar 如果这个答案有帮助,请投票表示感谢。希望我也能解决当前问题 我会试试这个方法【参考方案2】:

查看此链接 对初学者从开始理解概念到掌握 RecyclerView 非常有帮助。

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

希望这有助于您理解回收站视图的概念。

【讨论】:

我会检查这个例子 我想要片段好友中的recyclerview【参考方案3】:

RecycerView + Fragment + Volley

片段代码:

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 调用,以便它被调用 一次 如何在 Fragment 中保存 RecyclerView 状态(滚动位置 + 内容) RecyclerView 中的分页 休息呼叫(排球) 图像渲染(滑动) JSON 解析

【讨论】:

以上是关于使用凌空json数据的片段中的Recyclerview?的主要内容,如果未能解决你的问题,请参考以下文章

Android登录注册:无法使用凌空将数据插入数据库

如何从片段中的 JSON 响应中的对象获取数据

如何用凌空POST jsonobject

AJAX 响应:数据(JSON、XML)还是 HTML 片段? [关闭]

从片段中的json获取值

片段中的 JSON 解析 [关闭]