Android 将json数据显示在RecyclerView

json数据要通过Get请求获取,这里有个重要的知识点,get请求需要拼接url的

本次拼接url的参数为phone,由于登录的时候已经填了手机号,如果这里再收集手机号就会让客户体验变差,于是我采用了SharedPreferences进行记录并调出

SharedPreferences pref=getSharedPreferences("data",MODE_PRIVATE);
        String phone=pref.getString("phone","");

得到了phone之后,我采用了okhttp请求返回json,注意:进行网络请求都需要开启线程以及一些必要操作(<uses-permission android:name="android.permission.INTERNET" />

url为你申请的网络url

 new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client=new OkHttpClient().newBuilder()
                        .connectTimeout(60000, TimeUnit.MILLISECONDS)
                        .readTimeout(60000,TimeUnit.MILLISECONDS).build();
                //url/phone
                Request request=new Request.Builder().url("url/phone"+phone).build();
                try {
                    Response sponse=client.newCall(request).execute();
                    String string = sponse.body().string();
                    Log.d("list",string);
                    jsonJXDate(string);
                }catch (IOException | JSONException e){
                    e.printStackTrace();
                }
            }
        }).start();

由上可知,string即为所需的json

展示大概长这样

{
  "code": 200,
  "message": "成功",
  "data": [
    {
      "id": "string",
      "createTime": "2023-04-18T05:50:08.905+00:00",
      "updateTime": "2023-04-18T05:50:08.905+00:00",
      "isDeleted": 0,
      "param": {},
      "phone": "15019649343",
      "commercialTenant": "string",
      "payTime": "2023-04-18T05:50:08.905+00:00",
      "type": "string",
      "paymentType": "string",
      "bills": [
        {
          "product": "烧烤",
          "amount": "4",
          "price": "60",
          "subtotal": "240"
        }
      ],
      "total": "string"
    },
    {
      "id": "643e9efb09ecf071b0fd2df0",
      "createTime": "2023-04-18T13:28:35.889+00:00",
      "updateTime": "2023-04-18T13:28:35.889+00:00",
      "isDeleted": 0,
      "param": {},
      "phone": "15019649343",
      "commercialTenant": "string",
      "payTime": "2023-04-18T13:28:35.889+00:00",
      "type": "string",
      "paymentType": "string",
      "bills": [
        {
          "product": "兰州拉面",
          "amount": "5",
          "price": "40",
          "subtotal": "200"
        }
      ],
      "total": "string"
    }
  ],
  "ok": true
}

我所需要的是payTime,product,subtotal

有{}用JSONObject,有[]用JSONArray,一步步来靠近你的需要
JSONObject j1 = new JSONObject(data);
            try {
                JSONArray array = j1.getJSONArray("data");
                for (int i=0;i<array.length();i++){
                    j1=array.getJSONObject(i);
                    Map<String,Object>map=new HashMap<>();
                    String payTime = j1.getString("payTime");
                    JSONObject bills = j1.getJSONArray("bills").getJSONObject(0);
                    String product = bills.getString("product");
                    String subtotal = bills.getString("subtotal");
                    map.put("payTime",payTime);
                    map.put("product",product);
                    map.put("subtotal",subtotal);
                    list.add(map);
                }
                Message msg=new Message();
                msg.what=1;
                handler.sendMessage(msg);

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

    }
    public Handler handler=new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //添加分割线
                    rv.addItemDecoration(new androidx.recyclerview.widget.DividerItemDecoration(
                            MeActivity.this, androidx.recyclerview.widget.DividerItemDecoration.VERTICAL));
                    MyAdapter recy = new MyAdapter(MeActivity.this, list);
                    //设置布局显示格式
                    rv.setLayoutManager(new LinearLayoutManager(MeActivity.this));
                    rv.setAdapter(recy);
                    break;
            }
        }
    };

在adapter处通过常规layout显示后填入数据

 //定义时间展现格式
        Map<String, Object> map = list.get(position);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        LocalDateTime dateTime = LocalDateTime.parse(map.get("payTime").toString(), formatter);
        String strDate = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        holder.produce.setText(map.get("product").toString());
        holder.payTime.setText(strDate);
        holder.price.setText(map.get("subtotal").toString());

就大功告成啦,由于后台那边还没把base64图片传上来,导致少了个图片,大致就是这样的

 ui方面有点丑,如果有更好的方法还请大家多多指教

Android Studio中,可以使用Logcat来查看JSON数据。可以使用以下代码将JSON数据打印到Logcat中: ```java Log.d("JSON", json); ``` 其中,"JSON"是标签,json是包含JSON数据的字符串变量。在Logcat中,可以使用过滤器来查看特定标签的日志。 如果想要在应用程序中显示JSON数据,可以使用TextViewRecyclerView等视图组件。可以使用以下代码将JSON数据设置为TextView的文本: ```java TextView textView = findViewById(R.id.text_view); textView.setText(json); ``` 其中,R.id.text_view是TextView的ID,json是包含JSON数据的字符串变量。 如果想要将JSON数据显示RecyclerView中,可以创建一个包含JSON数据的列表,并使用适配器将其绑定到RecyclerView上。可以使用以下代码创建适配器: ```java public class JsonAdapter extends RecyclerView.Adapter<JsonAdapter.JsonViewHolder> { private List<JSONObject> mJsonList; public JsonAdapter(List<JSONObject> jsonList) { mJsonList = jsonList; } @NonNull @Override public JsonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.json_item, parent, false); return new JsonViewHolder(view); } @Override public void onBindViewHolder(@NonNull JsonViewHolder holder, int position) { JSONObject jsonObject = mJsonList.get(position); holder.bind(jsonObject); } @Override public int getItemCount() { return mJsonList.size(); } public static class JsonViewHolder extends RecyclerView.ViewHolder { private TextView mTextView; public JsonViewHolder(@NonNull View itemView) { super(itemView); mTextView = itemView.findViewById(R.id.text_view); } public void bind(JSONObject jsonObject) { mTextView.setText(jsonObject.toString()); } } } ``` 其中,R.layout.json_item是RecyclerView中每个项目的布局文件,jsonList是包含JSON数据的列表。可以使用以下代码将适配器绑定到RecyclerView上: ```java RecyclerView recyclerView = findViewById(R.id.recycler_view); JsonAdapter adapter = new JsonAdapter(jsonList); recyclerView.setAdapter(adapter); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值