Android - 持久化方案

Android Studio文件夹:View -> Tool Windows -> Device Explorer

  1. 三种持久化方案

    • 文件存储
      • 文件写入模式
        • MODE_APPEND:存在文件则追加内容
        • MODE_PRIVATE:存在文件则覆盖内容
    • SharedPreferences
    • 数据库
  2. 实践
    2.1 SharedPreferences存储、恢复数据

  • 编写UI页面(包含存储、清空、恢复数据按钮)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="50dp"
       android:gravity="center"
       android:layout_marginLeft="30dp"
       android:layout_marginTop="17dp"
       android:textSize="20dp"
       android:text="用户名:" />

    <EditText
        android:id="@+id/username"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:background="@color/purple_200"
        android:textSize="20dp"
        android:textColor="@color/black"
        android:layout_width="200dp"
        android:layout_height="40dp" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:gravity="center"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="80dp"
        android:textSize="20dp"
        android:text=" 密  码 :" />

    <EditText
        android:id="@+id/password"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="80dp"
        android:gravity="center"
        android:background="@color/cardview_shadow_start_color"
        android:textSize="20dp"
        android:textColor="@color/black"
        android:layout_width="200dp"
        android:layout_height="40dp" />

    <Button
        android:id="@+id/login"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="150dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录" />

    <Button
        android:id="@+id/remove"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清空" />

    <Button
        android:id="@+id/recover"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="250dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="恢复" />


RelativeLayout>
  • 核心处理逻辑
public class SharedPreferencesStore extends AppCompatActivity {

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

        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView usernameTextView = findViewById(R.id.username);
                String username = usernameTextView.getText().toString();

                TextView passwordTextView = findViewById(R.id.password);
                String password = passwordTextView.getText().toString();

                SharedPreferences loginMsg = getSharedPreferences("loginMsg", MODE_PRIVATE);
                SharedPreferences.Editor edit = loginMsg.edit();
                edit.putString("username", username);
                edit.putString("password", password);
                edit.apply();
            }
        });

        findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView usernameTextView = findViewById(R.id.username);
                usernameTextView.setText(null);

                TextView passwordTextView = findViewById(R.id.password);
                passwordTextView.setText(null);

            }
        });

        findViewById(R.id.recover).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences loginMsg = getSharedPreferences("loginMsg", MODE_PRIVATE);
                String username = loginMsg.getString("username", "");
                String password = loginMsg.getString("password", "");

                TextView usernameTextView = findViewById(R.id.username);
                usernameTextView.setText(username);

                TextView passwordTextView = findViewById(R.id.password);
                passwordTextView.setText(password);


            }
        });

    }

}

  • 数据存储地方:data/data/packageName/shared_prefs/fileName

2.2 Sqlite

  • 实现SqliteOpenHelper继承类
public class UserSql extends SQLiteOpenHelper {

    private Context context;

    public UserSql(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.context = context;
    }

	// 创建DB
    @Override
    public void onCreate(SQLiteDatabase db) {

        String sql = "create table user( " +
                "id integer primary key autoincrement, " +
                "username text, " +
                "password text )";

        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
  • 编写CRUD

public class SqliteStore extends AppCompatActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_sqlite);
        UserSql userSql = new UserSql(this, "user.db", null, 1);


        // 增加
        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView usernameTextView = findViewById(R.id.username);
                TextView passwordTextView = findViewById(R.id.password);

                String username = usernameTextView.getText().toString();
                String password = passwordTextView.getText().toString();

                SQLiteDatabase writableDatabase = userSql.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put("username", username);
                contentValues.put("password", password);
                contentValues.put("id", new Random().nextInt(100));
                writableDatabase.insert("user", null, contentValues);
                Toast.makeText(SqliteStore.this, "登录成功!", Toast.LENGTH_SHORT).show();
            }
        });

        // 删除
        findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView usernameTextView = findViewById(R.id.username);
                String username = usernameTextView.getText().toString();

                SQLiteDatabase writableDatabase = userSql.getWritableDatabase();
                writableDatabase.delete("user", "username = ?", new String[]{username});

            }
        });

        // 修改
        findViewById(R.id.update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView usernameTextView = findViewById(R.id.username);
                String username = usernameTextView.getText().toString();
                String updatePassword = "updateupdate";

                SQLiteDatabase writableDatabase = userSql.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put("password", updatePassword);
                writableDatabase.update("user", contentValues, "username = ?", new String[]{username});

            }
        });




        // 查询
        findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase readableDatabase = userSql.getWritableDatabase();
                Cursor cursor = readableDatabase.query("user", null, null, null, null, null, null);
                if (cursor.moveToFirst()) {
                    do {
                        String id = cursor.getString(cursor.getColumnIndexOrThrow("id"));
                        String username = cursor.getString(cursor.getColumnIndexOrThrow("username"));
                        String password = cursor.getString(cursor.getColumnIndexOrThrow("password"));
                        Toast.makeText(SqliteStore.this, id + username + password, Toast.LENGTH_LONG).show();
                    } while (cursor.moveToNext());
                }
            }
        });



        // 这个不用理,清楚输入框的
        findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView usernameTextView = findViewById(R.id.username);
                TextView passwordTextView = findViewById(R.id.password);

                usernameTextView.setText(null);
                passwordTextView.setText(null);
            }
        });
    }
}

  • UI界面

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="17dp"
        android:textSize="20dp"
        android:text="用户名:" />

    <EditText
        android:id="@+id/username"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:background="@color/purple_200"
        android:textSize="20dp"
        android:textColor="@color/black"
        android:layout_width="200dp"
        android:layout_height="40dp" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:gravity="center"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="80dp"
        android:textSize="20dp"
        android:text=" 密  码 :" />

    <EditText
        android:id="@+id/password"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="80dp"
        android:gravity="center"
        android:background="@color/cardview_shadow_start_color"
        android:textSize="20dp"
        android:textColor="@color/black"
        android:layout_width="200dp"
        android:layout_height="40dp" />

    <Button
        android:id="@+id/login"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="150dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录" />

    <Button
        android:id="@+id/delete"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除" />

    <Button
        android:id="@+id/search"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="250dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查找" />


    <Button
        android:id="@+id/update"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="300dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改" />

    <Button
        android:id="@+id/remove"
        android:gravity="center"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="350dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清空" />


RelativeLayout>

  • LitePal操作Sqlite
    • 下载第三方LitePal的jar包,链接:https://github.com/guolindev/LitePal/tree/master/downloads
    • Android Studio导入,放到app/libs目录下,右键jar包 -> Add as library…
    • AndroidManifest.xml添加name,android:name=“org.litepal.LitePalApplication”
    • app/src/main目录下创建assets,再创建litepal.xml

<litepal>
	// 操作的数据库名称
    <dbname value="student">dbname>
    // 迭代的版本号
    <version value="1">version>

    <list>
    	// 关联的实体类
        <mapping class="com.example.myapplication.entity.Student">mapping>
    list>
litepal>
- 创建实体类继承于DataSupport
public class Student extends DataSupport {

    private Integer id;

    private String username;

    private String password;

    public Student() {}

    public Student(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}


- CRUD
public class LitepalStore extends AppCompatActivity {

	// 创建数据库
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_litepal);

        findViewById(R.id.create_db).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LitePal.getDatabase();
            }
        });

		// 新增
        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int id = new Random().nextInt(100);
                String username = ((TextView) findViewById(R.id.username)).getText().toString();
                String password = ((TextView) findViewById(R.id.password)).getText().toString();
                Student student = new Student(id, username, password);
                student.save();
            }
        });

		// 删除
        findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String username = ((TextView) findViewById(R.id.username)).getText().toString();
                Toast.makeText(LitepalStore.this, username, Toast.LENGTH_LONG).show();
                DataSupport.deleteAll(Student.class, "username = ?", username);
            }
        });

		// 修改
        findViewById(R.id.update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String username = ((TextView) findViewById(R.id.username)).getText().toString();

                List<Student> studentList = LitePal.findAll(Student.class);
                Integer id = null;
                for (Student student : studentList) {
                    if (username.equals(student.getUsername())) {
                        id = student.getId();
                    }
                }

                Student student = new Student();
                student.setUsername(username);
                student.setPassword("updatePassword");

                student.update(id);

            }
        });


		// 查询
        findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                List<Student> studentList = LitePal.findAll(Student.class);
                for (Student student : studentList) {
                    Toast.makeText(LitepalStore.this, student.toString(), Toast.LENGTH_SHORT).show();
                }


            }
        });

    }

}


- UI代码




    

    


    

    

    

你可能感兴趣的:(android)