Android简单使用SharedPreferences和 SQLite数据库实现数据存储
16lz
2021-01-25
在安卓app中,我们希望之前设置的一些信息能够保存在手机中,这样下次打开app时就能直接显示我们上次保存的信息,此时使用SharedPreferences来存储key-value形式的数据,它是Android提供的一个轻量级的存储类,非常适合用来存储app的各项参数。
当我们需要处理大量数据时,如几百条几千条订单信息的增删改查,这时就需要一个稳健的数据库存储机制来提供支持,SQLite数据库就可以帮助我们完成这样的工作。SQLite是一款轻量级的嵌入式关系数据库,遵守ACID(原子性,一致性,隔离性,持久性)四要素。
SharedPreferences**实现的功能:
- 在登录页面输入用户名和密码(为节省时间未进行验证),使用SharedPreferences保存用户名和密码,并设置登录状态为1(已登录)
- 关闭应用后再次打开直接跳转到主页,并从SharedPreferences中获取用户名并显示
- 点击退出登录按钮,使用SharedPreferences修改登录状态为0(未登录),跳转到登录页面
SQLite数据库实现的功能:
- 在主页点击记账本按钮,跳转到账单页面,从SQLite数据库中获取数据并显示在ListView中
- 在账单页面点击记账按钮,跳转到添加账单页面,输入消费类别和消费金额,点击保存按钮将数据写入到SQLite数据库,并返回到账单页面
- 长按ListView中的子项弹出对话框提示是否删除该账单,点击确认后从SQLite数据库删除该账单(根据账单id),并刷新ListView显示
实现代码:
- MySQLiteHelper.java:数据库操作辅助类SQLiteOpenHelper 负责SQLite数据库的创建和修改
package com.youngpain.alipay.util;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class MySQLiteHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "account.db";//数据库名称 private static final String TABLENAME = "account";//表名称 private static final int DATABASE_VERSION = 1;//数据库版本 //构造方法 public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * 重写onCreate()方法,调用execSQL()方法创建表 * * @param db */ @Override public void onCreate(SQLiteDatabase db) { String sql = "create table " + TABLENAME + "(id integer primary key autoincrement" + ",name varchar(255),money integer)"; db.execSQL(sql); } /** * 重写onUpgrade()方法,升级数据库 * * @param db * @param oldVersion * @param newVersion */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "drop table if exists " + TABLENAME; db.execSQL(sql); this.onCreate(db); }}
- MainActivity.java:负责处理登录
package com.youngpain.alipay.activity;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.Window;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import com.youngpain.alipay.R;public class MainActivity extends Activity { private EditText username; private EditText password; private Button loginButton; private Button forgetButton; //通过SharedPreferences写入登录信息 private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去除标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); //初始化 init(); //读取loginInfo文件 SharedPreferences loginInfo = getSharedPreferences("loginInfo" , Activity.MODE_PRIVATE); //判断登录状态 if (loginInfo.getInt("login", 0) == 1) { //已登录则跳转到个人信息页面,若已登录则用户名和密码已经存储到SharedPreferences中 Intent intent = new Intent(MainActivity.this, PersonInfoActivity.class); startActivity(intent); } else { //如果当前未登录(退出登录),从SharedPreferences中获取用户名和密码,填入输入框 username.setText(loginInfo.getString("username", "")); password.setText(loginInfo.getString("password", "")); } //测试 //forgetButton = findViewById(R.id.forget_pwd); //forgetButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Toast.makeText(MainActivity.this, "通过setOnClickListener实现事件处理" // , Toast.LENGTH_LONG).show(); // } //}); } /** * 使用android:onClick="forgetPwd"实现事件处理 * * @param view */ public void forgetPwd(View view) { Toast.makeText(MainActivity.this, "忘记密码", Toast.LENGTH_LONG).show(); } /** * 通过setOnClickListener实现事件处理 */ private void init() { //获取控件 username = findViewById(R.id.login_et_user); password = findViewById(R.id.login_et_password); loginButton = findViewById(R.id.bt_login); //绑定监听事件 loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = username.getText().toString().trim(); String pwd = password.getText().toString(); if ("".equals(name) || "".equals(pwd)) { Toast.makeText(MainActivity.this, "用户名或密码不能为空" , Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(MainActivity.this , PersonInfoActivity.class); //使用Bundle传递数据 //Bundle bundle = new Bundle(); //bundle.putString("username", name); //intent.putExtras(bundle); //通过SharedPreferences保存信息,使用私有方式存储,不允许其他应用访问 sharedPreferences = getSharedPreferences("loginInfo" , MODE_PRIVATE); //获取Editor添加数据 SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("username", name); editor.putString("password", pwd); //1表示已登录,0表示未登录 editor.putInt("login", 1); //提交修改 editor.commit(); //直接传递数据 //intent.putExtra("username", name); //跳转到个人信息页面并退出当前页面 startActivity(intent); finish(); } } }); }}
- PersonInfoActivity.java:负责主页信息显示
package com.youngpain.alipay.activity;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.Window;import android.widget.Button;import android.widget.TextView;import com.youngpain.alipay.R;public class PersonInfoActivity extends Activity { private TextView username; private TextView showName; private TextView showPhone; private TextView showEmail; private Button editInfo; private Button quitLogin; private Button accountBtn; //通过SharedPreferences获取登录信息 private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去除标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.person_info); //初始化 init(); //使用Bundle获取数据用户名并显示 //String name = getIntent().getExtras().getString("username"); //直接从Intent中获取用户名并显示 //String name = getIntent().getStringExtra("username"); //通过SharedPreferences获取保存的用户名 SharedPreferences loginInfo = getSharedPreferences("loginInfo" , Activity.MODE_PRIVATE); String name = loginInfo.getString("username", "admin"); username.setText("账号:" + name); } //重写onActivityResult方法获取上一个Activity传回来的数据 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (resultCode) { case 8: String name = data.getStringExtra("name"); String phone = data.getStringExtra("phone"); String email = data.getStringExtra("email"); showName.setText(name); showPhone.setText(phone); showEmail.setText(email); break; default: break; } } //初始化 private void init() { username = findViewById(R.id.username); showName = findViewById(R.id.show_name); showPhone = findViewById(R.id.show_phone); showEmail = findViewById(R.id.show_email); editInfo = findViewById(R.id.edit_person_info); quitLogin = findViewById(R.id.quit_login); accountBtn = findViewById(R.id.account_book); editInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取EditPersonInfoActivity返回的数据 startActivityForResult(new Intent(PersonInfoActivity.this , EditPersonInfoActivity.class), 1); } }); quitLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //将SharedPreferences中的登录状态改为0(未登录) sharedPreferences = getSharedPreferences("loginInfo" , MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("login", 0); //提交修改 editor.commit(); //跳转到登录页面 Intent intent = new Intent(PersonInfoActivity.this , MainActivity.class); startActivity(intent); finish(); } }); accountBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //跳转到账本页面 Intent intent = new Intent(PersonInfoActivity.this , AccountBookActivity.class); startActivity(intent); } }); }}
- EditPersonInfoActivity.java:负责修改个人信息
package com.youngpain.alipay.activity;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.Window;import android.widget.Button;import android.widget.EditText;import com.youngpain.alipay.R;public class EditPersonInfoActivity extends Activity { private EditText editName; private EditText editPhone; private EditText editEmail; private Button saveButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去除标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.edit_person_info); //初始化 init(); } //初始化 private void init() { editName = findViewById(R.id.edit_name); editPhone = findViewById(R.id.edit_phone); editEmail = findViewById(R.id.edit_email); saveButton = findViewById(R.id.save_person_info); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取输入信息 String name = editName.getText().toString().trim(); String phone = editPhone.getText().toString().trim(); String email = editEmail.getText().toString().trim(); Intent intent = new Intent(); intent.putExtra("name", name); intent.putExtra("phone", phone); intent.putExtra("email", email); Activity activity = EditPersonInfoActivity.this; //设置要返回的数据 activity.setResult(8, intent); activity.finish(); } }); }}
- AccountBookActivity.java:负责账单显示
package com.youngpain.alipay.activity;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.View;import android.view.Window;import android.widget.AdapterView;import android.widget.Button;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;import com.youngpain.alipay.R;import com.youngpain.alipay.util.MySQLiteHelper;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class AccountBookActivity extends Activity { private ListView accountListView; private Button accountBtn; private MySQLiteHelper sqLiteHelper; private SimpleAdapter simpleAdapter; private List
- AddAccountBookActivity.java:负责添加账单
package com.youngpain.alipay.activity;import android.app.Activity;import android.content.ContentValues;import android.content.Intent;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.View;import android.view.Window;import android.widget.Button;import android.widget.EditText;import com.youngpain.alipay.R;import com.youngpain.alipay.util.MySQLiteHelper;public class AddAccountBookActivity extends Activity { private EditText editAccountType; private EditText editAccountMoney; private Button saveAccountBook; private MySQLiteHelper sqLiteHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去除标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.add_account_book); //初始化 init(); } //初始化 private void init() { editAccountType = findViewById(R.id.edit_account_type); editAccountMoney = findViewById(R.id.edit_account_money); saveAccountBook = findViewById(R.id.save_account_book); saveAccountBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //通过SQLiteOpenHelper调用getWritableDatabase()方法获取SQLiteDatabase,其提供了数据操作方法 sqLiteHelper = new MySQLiteHelper(AddAccountBookActivity.this); SQLiteDatabase database = sqLiteHelper.getWritableDatabase(); //获取消费类型和金额 String name = editAccountType.getText().toString(); double money = Double.valueOf(editAccountMoney.getText().toString()); //使用封装数据 ContentValues values = new ContentValues(); values.put("name", name); values.put("money", money); //插入数据 database.insert("account", null, values); //关闭数据库 database.close(); //跳转到账单页面 Intent intent = new Intent(AddAccountBookActivity.this , AccountBookActivity.class); startActivity(intent); } }); }}
运行结果:
源码:下载
更多相关文章
- “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
- Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
- 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
- Google 官方推出应用开发架构指南
- android interview 2
- 开发任意网站Android客户端
- Android数据读取之Sqlite数据库操作
- Json解析(GSON开源库——最简单的json解析)
- Android性能测试小工具Emmagee