Android reads local data for local development

Foreword

In daily development, the API interface has not been deployed yet, but the UI has come out. At this time, local data is often used to build the functional interface, which can often save development time to a great extent. The tools are used directly, and there are not many words say open

1. Project construction

1 Create a project

2 Next step Project name My15 Language java Directly finish Create completed

3 After the project is created, right-click main to create the capital source file directory and choose as follows

4 Continue to select assets and press Enter to complete the creation

5 Click assets and right-click to create a file file called JsonData.json. This json file is for storing local Json data according to the format of the server. The project has been built and the next step is to use

2. Steps to use

1. Import library

Add under build under app

api("com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.30")

api("com.google.code.gson:gson:2.8.6")

Add a warehouse under the build under the project track

maven { url 'https://jitpack.io' }

2. Tools

right click on my15 to create a Tools file, and modify the file to be a tool class for reading local data

public class Tools {

    /**
     * Read local resource file
     *
     * @param context context
     * @param fileName local data file name
     * @return
     */
    public static String getFromAssets(Context context, String fileName) {
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        try {
            inputReader = new InputStreamReader(context. getResources(). getAssets(). open(fileName));
            bufReader = new BufferedReader(inputReader);
            String line = "";
            StringBuilder result = new StringBuilder();
            while ((line = bufReader. readLine()) != null)
                result.append(line);
            return result. toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputReader != null) {
                    inputReader. close();
                }
                if (bufReader != null) {
                    bufReader. close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

}

3 Steps to use

1 Right click on my15 to create an adapter named JsonAdapter, which shows the train type and time, the entity class and the layout file in turn.

public class JsonAdapter extends BaseQuickAdapter<JsonBean.DataBean.ResultBean, BaseViewHolder> {

    public JsonAdapter(int layoutResId, @Nullable List<JsonBean.DataBean.ResultBean> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, JsonBean.DataBean.ResultBean item) {

        helper.setText(R.id.cc_tv, "Train:" + item.getTrain());
        helper.setText(R.id.name_tv, "Type:" + item.getName());
        helper.setText(R.id.time_tv, "Time:" + item.getTime());


    }
}

2 Item layout file text_item_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="140dp"
    android:background="@drawable/linearlayout_underline"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:id="@ + id/cc_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:text="Trains" />

        <TextView
            android:id="@ + id/name_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="15dp"
            android:text="Harmony" />


    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical">

        <TextView
            android:id="@ + id/time_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:text="2020-10-12" />

    </LinearLayout>


</LinearLayout>

3 Generate entity class JsonBean based on local Json data

public class JsonBean {

    private String code;
    private String message;
    private DataBean data;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this. message = message;
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public static class DataBean {
        private List<ResultBean> result;

        public List<ResultBean> getResult() {
            return result;
        }

        public void setResult(List<ResultBean> result) {
            this.result = result;
        }

        public static class ResultBean {
            private String train;
            private String name;
            private String time;

            public String getTrain() {
                return train;
            }

            public void setTrain(String train) {
                this. train = train;
            }

            public String getName() {
                return name;
            }

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

            public String getTime() {
                return time;
            }

            public void setTime(String time) {
                this.time = time;
            }
        }
    }
}

4 Finally, it is used, which is also very simple. It is used in MainActivity as follows

public class MainActivity extends AppCompatActivity {


    private List<JsonBean.DataBean.ResultBean> jsonList = new ArrayList<>();
    private JsonAdapter jsonAdapter;
    private RecyclerView jsonRv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R. layout. activity_main);

        jsonRv = findViewById(R.id.json_list);

        String fromAssets = Tools.getFromAssets(this, "JsonData.json");
        JsonBean jsonBean = new Gson().fromJson(fromAssets, JsonBean.class);
        jsonList = jsonBean.getData().getResult();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        jsonRv.setLayoutManager(layoutManager);
        jsonAdapter = new JsonAdapter(R. layout. text_item_layout, jsonList);
        jsonRv.setAdapter(jsonAdapter);
        jsonAdapter. notifyDataSetChanged();


    }
}

5 Finally, look at the running screenshot

Summary

The soldiers and horses are not moved, the food and grass go first, and only by planning in advance can we be even better