1. 程式人生 > >Android動態獲取json解析後顯示到RecyclerView

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介面:

<?xml version="1.0" encoding="utf-8"?>
<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,

<?xml version="1.0" encoding="utf-8"?>
<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<Map<String,Object>> list=new ArrayList<>();
    public Context con;
    public  LayoutInflater inflater;
    public  recy_item_Adapter(List<Map<String,Object>> 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<Map<String,Object>> 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<resultJsonArray.length();i++){
                        jsonObject = resultJsonArray.getJSONObject( i );
                        Map<String, Object> 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<String, Object> 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。