Android动态获取json解析后显示到RecyclerView

首先,需要进行获取以及解析的json数据;

{
  "code": "200",
  "tips": "ok",
  "message": "success",
  "devices": [
    {
      "deviceid": 1,
      "userid": 3,
      "username": "demo",
      "devicename": "TPYBoard v202",
      "deviceaddre": "5C:CF:7F:0D:85:65",
      "addtime": 1436879777
    },
    {
      "deviceid": 2,
      "userid": 3,
      "username": "demo",
      "devicename": "MMP",
      "deviceaddre": "a5:a9:a9:ac:a0:a6",
      "addtime": 1848919392
    }
  ]
}

首先需要了解json是什么类型的,然后再进行转换对象以及数组;
fragmten1.xml界面:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.rnd.jsonobjcet.MainActivity">
    <LinearLayout
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <include layout="@layout/title_layout"/>
    LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recy"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
LinearLayout>

再创建一个他的item动态布局:RecyclerView_item.xml,


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:gravity="center"
    >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="70dp"
        android:paddingLeft="10dp"
        android:orientation="vertical">
        <ImageView
            android:layout_width="70dip"
            android:layout_height="70dip"
            android:src="@mipmap/tmw1"/>
    LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="70dp"
        android:paddingLeft="15dp"
        android:paddingRight="10dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/recy_item"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="23dp"
            android:text="Demo"/>
        <TextView
            android:id="@+id/recy_time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="e3:32:66:h5:e3:32:66:h5"
            android:paddingTop="3dp"
            android:textSize="15dp"/>
    LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:gravity="right"
            android:paddingRight="20dp"
            android:paddingTop="15dp"
            android:textSize="23dp"
            android:text="Conent"/>
    LinearLayout>
LinearLayout>
RelativeLayout>

再就是创建recy_item_Adapter.java文件了;

package com.example.rnd.jsonobjcet.Adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.rnd.jsonobjcet.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by rnd on 2018/3/2.
 */

public class recy_item_Adapter extends RecyclerView.Adapter<recy_item_Adapter.ViewHolder> {
    public List> list=new ArrayList<>();
    public Context con;
    public  LayoutInflater inflater;
    public  recy_item_Adapter(List> list, Context con){
        this.con=con;
        this.list=list;
        inflater= LayoutInflater.from(con);
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= inflater.inflate( R.layout.recyclerview_item,null);
        ViewHolder viewHolder=new ViewHolder(view);
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.recy_tv.setText(list.get(position).get("name").toString());
        holder.recy_time.setText(list.get(position).get("shijian").toString());
    }

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

    class ViewHolder extends RecyclerView.ViewHolder{
        public TextView recy_tv,recy_time;
        public ViewHolder(View itemView) {
            super(itemView);
            recy_tv= itemView.findViewById(R.id.recy_item);
            recy_time= itemView.findViewById(R.id.recy_time);
        }
    }

}

ok,适配器写好了,就差主java了,FirstFragment.java,我这是底部选项卡fragment界面获取的动态json解析列表;

package com.example.rnd.jsonobjcet.Fragment;
import android.app.DownloadManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.example.rnd.jsonobjcet.Adapter.recy_item_Adapter;
import com.example.rnd.jsonobjcet.R;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by dm on 16-3-29.
 * 第一个页面
 */
public class FirstFragment extends Fragment {
    public  String date;
    public  String title;
    private TextView datejson;
    public RecyclerView recyclerview;
    public List> list=new ArrayList<>();

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

        View view = inflater.inflate( R.layout.fragment1, container, false );
        recyclerview= view.findViewById(R.id.recy);

        okhttpDate();
        return view;
        //获取数据
    }
    private void okhttpDate() {
        Log.i("TAG","--ok-");
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client=new OkHttpClient();
                Request request=new Request.Builder().url("这里写自己的服务器完整json路径").build();
                try {
                   Response sponse=client.newCall(request).execute();
                   date=sponse.body().string();
//                    //解析
                  jsonJXDate(date);
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void jsonJXDate(String date) {
        if(date!=null) {
            try {
                JSONObject jsonObject = new JSONObject(date);
                String resultCode = jsonObject.getString("message");
                if (resultCode.equals("success")) {
                    JSONArray resultJsonArray = jsonObject.getJSONArray("devices");
                    for(int i=0;i map = new HashMap<>();

                            //获取到json数据中的activity数组里的内容name
                            String name = jsonObject.getString("devicename");
                            //获取到json数据中的activity数组里的内容startTime
                            String shijian=jsonObject.getString("deviceaddre");
                            //存入map
                            map.put("name", name);
                            map.put("shijian", shijian);
                            //ArrayList集合
                            list.add(map);

                    }

                    }

//                for (int i = 0; i < jsonArray.length(); i++) {
//                    JSONObject jsonObject = jsonArray.getJSONObject(i);
//                    title = jsonObject.getString("devicename");
//                    Map map = new HashMap<>();
//                    map.put("title", title);
//                    list.add(map);
//                }
                Message msg=new Message();
                msg.what=1;
                handler.sendMessage(msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    //添加分割线
                    recyclerview.addItemDecoration(new DividerItemDecoration(
                     getActivity(), DividerItemDecoration.VERTICAL));
                    recy_item_Adapter recy=new recy_item_Adapter(list,getActivity());
                    //设置布局显示格式
                    recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
                    recyclerview.setAdapter(recy);
                    break;


            }
        }
    };
}

还有就是网络配置需要记得添加:

<uses-permission android:name="android.permission.INTERNET">uses-permission>

最后重点记住:我这个是fragment底部选项卡做的界面列表,若你是anctivity.jav,就创建activity界面,其它数据挪用就ok。

你可能感兴趣的:(Android)