安卓开发简单实现历史记录功能 – SharedPreferences存储

点击添加按钮添加数据 并存储,通过 listData 类实现添加复杂数据

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <ListView
        android:id="@+id/ls"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_above="@id/btn"/>

    <Button
        android:id="@+id/btn"
        android:layout_alignParentBottom="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="添加"/>

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="234dp"
        android:layout_marginBottom="1dp"
        android:layout_toRightOf="@id/btn"
        android:text="跳转" />
</RelativeLayout>

MainActivity.java

package com.android.lmarch.listtwoadd;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.lmarch.listtwoadd.listData;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //private ListView ls;
    private Button btn,btn2;
    private List<listData> list;
    private Myadapter adapter;
    private final String TOTAL = "TOTAL";
    private final String NAME = "NAME";
    private final String CONTENT = "CONTENT";
    private final String PIC = "PIC";
    private final String URL = "URL";
    //private ListView ls_1;//,ls_2;
    private SharedPreferences sp_1;//sp_2;
    String name = "";
    String content = "";
    String pic = "https://www.youtube.com/favicon.ico";
    String url = "https://www.youtube.com/";
    int i = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(this);
        btn2 = (Button)findViewById(R.id.btn2);
        btn2.setOnClickListener(this);

        //获取数据
        list = new ArrayList<listData>();
        sp_1 = getApplicationContext().getSharedPreferences("bookmark",MODE_PRIVATE);//书签
        //ls_1 = (ListView)findViewById(R.id.ls);
        getListData();
        adapter = new Myadapter();
        //ls_1.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn:
                content = content + i++;
                name = name + i++;
                addData();
                save(list);
            break;
            case R.id.btn2:
                Intent i = new Intent(MainActivity.this,Two.class);
                startActivity(i);
                break;
        }
    }

    /**
     * start
     *添加列表项
     */
    private void addData(){
        if (content != null && !content.equals("")){
            listData data = new listData();
            data.setName(name);
            data.setContent(content);
            data.setPic(pic);
            data.setUrl(url);
            // data.setPosition(list.size());
            list.add(0,data); //数据从头部添加
            //list.add(0,data); //数据从末尾添加
            adapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(),"已保存书签",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取数据
     */
    private void getListData(){
        int lens = sp_1.getInt(TOTAL, 1);
        for (int i = 0; i < lens; i++){
            String name = sp_1.getString(NAME + i, null);
            String content = sp_1.getString(CONTENT + i, null);
            String pic = sp_1.getString(PIC + i, null);
            String url = sp_1.getString(URL + i, null);
            if (content != null){
                listData data = new listData();
                // data.setPosition(sp.getInt(POSITION + i, i));
                data.setName(name);
                data.setContent(content);
                data.setPic(pic);
                data.setUrl(url);
                list.add(data);
            }
        }
    }

    /**
     * 保存数据
     */
    @SuppressLint({"ApplySharedPref", "CommitPrefEdits"})
    private void save(List<listData> list){
        if (list == null || list.size() == 0){
            Toast.makeText(MainActivity.this, "还没数据", Toast.LENGTH_LONG).show();
            return;
        }
        sp_1.edit().clear();
        for (int i = 0; i < list.size(); i++){
            sp_1.edit().putString(NAME + i, list.get(i).getContent()).commit();
            sp_1.edit().putString(CONTENT + i, list.get(i).getName()).commit();
            sp_1.edit().putString(PIC + i, list.get(i).getPic()).commit();
            sp_1.edit().putString(URL + i, list.get(i).getUrl()).commit();
        }
        sp_1.edit().putInt(TOTAL, list.size()).commit();
    }

    /**
     * 适配器
     */
    class Myadapter extends BaseAdapter{
        @Override
        public int getCount(){return list == null ? 0 : list.size();}
        @Override
        public Object getItem(int arg0){return list.get(arg0);}
        @Override
        public long getItemId(int arg0){return arg0;}
        @SuppressLint("InflateParams")
        @Override
        public View getView(int arg0, View view, ViewGroup arg2){
            if (view == null){
                view = getLayoutInflater().inflate(R.layout.test_item, null);
            }
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
            TextView tv_pic = (TextView) view.findViewById(R.id.tv_pic);
            TextView tv_url = (TextView) view.findViewById(R.id.tv_url);
            tv_name.setText(list.get(arg0).getName());
            tv_content.setText(list.get(arg0).getContent());//获取内容打印到textview
            tv_pic.setText(list.get(arg0).getPic());
            tv_url.setText(list.get(arg0).getUrl());//获取内容打印到textview
            return view;
        }
    }
}

listData.java

package com.android.lmarch.listtwoadd;

public class listData {
    private String name;
    private String content;
    private String pic;
    private String url;
    // private int position;

    public String getName(){
        return name;
    }

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

    public String getContent(){
        return content;
    }

    public void setContent(String content){
        this.content = content;
    }

    public String getPic(){
        return pic;
    }

    public void setPic(String pic){
        this.pic = pic;
    }

    public String getUrl(){
        return url;
    }

    public void setUrl(String url){
        this.url = url;
    }
}

test_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/tv_pic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/tv_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>