Android简单使用SharedPreferences和 SQLite数据库实现数据存储

版权声明:原创文章,未经允许,禁止转载! https://blog.csdn.net/weixin_36512652/article/details/83280292
  在安卓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<Map<String, Object>> accounts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.account_book);

        //初始化
        init();

        //从数据库获取账单信息并显示
        sqLiteHelper = new MySQLiteHelper(AccountBookActivity.this);
        SQLiteDatabase database = sqLiteHelper.getReadableDatabase();
        //表名,列名,查询条件(可包含?),查询参数(替代?),分组字段,分组条件,排序字段
        Cursor cursor = database.query("account", null, null
                , null, null, null, null);
        //将查询到的数据封装到List方便ListView使用
        accounts = new ArrayList<>();
        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>();
            Integer id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            Double money = cursor.getDouble(cursor.getColumnIndex("money"));
            map.put("id", id);
            map.put("name", name);
            map.put("money", money);
            accounts.add(map);
        }
        //关闭数据库
        database.close();
        //创建Adapter
        simpleAdapter = new SimpleAdapter(this, accounts, R.layout.account_book_item
                , new String[]{"name", "money"}, new int[]{R.id.type, R.id.money});
        //绑定Adapter
        accountListView.setAdapter(simpleAdapter);
    }


    //初始化
    private void init() {
        accountListView = findViewById(R.id.account_listview);
        accountBtn = findViewById(R.id.add_account);
        accountBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击记账按钮跳转到添加账单页面
                Intent intent = new Intent(AccountBookActivity.this
                        , AddAccountBookActivity.class);
                startActivity(intent);
            }
        });
        accountListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position
                    , final long id) {
                //创建对话框
                new AlertDialog.Builder(AccountBookActivity.this).setTitle("删除账单")
                        .setIcon(R.drawable.dialog).setMessage("确定要删除该账单?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //获取要删除数据的id
                                String id = String.valueOf(accounts.get(position).get("id"));
                                //从数据库删除数据
                                SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
                                database.delete("account", "id=?"
                                        , new String[]{id});
                                //关闭数据库
                                database.close();

                                //从List中删除数据并刷新ListView显示
                                accounts.remove(position);
                                simpleAdapter.notifyDataSetChanged();
                                accountListView.invalidate();
                            }
                        })
                        .setNegativeButton("取消", null).create().show();
                return false;
            }
        });
    }
}
  • 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);
            }
        });

    }
}

运行结果:

源码:下载

猜你喜欢

转载自blog.csdn.net/weixin_36512652/article/details/83280292
今日推荐