每个程序都需要自己的数据进行设计与管理,那么我的博客就从数据存储开始吧。
首先,因为我没有后端云,所以数据只能保存在本地,这个时候就要用到安卓本地文件存储了。在我的代码中,主要用了sqlite数据库存储与SharedPreference存储。
接着,让我来为大家介绍一下我的数据库表。(没有啥好的工具,而且是真机测试,就用截图给大家展示)。
1、总体结构:
因为做的相当简陋,所以,保存数据也只用了4张表,接下来直接贴出建表代码,大家可以看一下每张表的结构。
//大家可以看一下,表的结构很简单
package com.example.hhj.hello.DB; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.example.hhj.hello.Model.Message; import com.example.hhj.hello.Model.User; import java.util.List; public class MyDBHelper extends SQLiteOpenHelper { public static final String sCREATE_USER = "create table users (" + "user_id integer primary key autoincrement, " + "user_name text, " + "password text)";//用户表 public static final String sCREATE_MESSAGE = "create table messages (" + "message_id integer primary key autoincrement, " + "user_send_id integer, " + "user_rec_id integer, " + "content text, " + "send_date integer)";//消息表 public static final String sCREATE_LIST = "create table lists (" + "list_id integer primary key autoincrement, " + "user_id integer, " + "list_name text)";//好友列表表 public static final String sCREATE_LIST_CONTENT = "create table list_content (" + "list_id integer, " + "user_id integer)";//好友列表内容表 public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(sCREATE_USER); db.execSQL(sCREATE_MESSAGE); db.execSQL(sCREATE_LIST); db.execSQL(sCREATE_LIST_CONTENT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
这里面就要说到Sqlite数据库的基础用法了,首先是创建一个类继承SQLiteOpenHelper,并重写其中的onCreate()方法实现数据表的创建,对于onUpgrade()方法,我没用到,因为是自己做得小东西,数据出错直接重新安装就行了,但是,大家可以自己百度一下,会有很详细的介绍。然后就是通过这个类获取可操作数据库(Writable和Readble),并对他们进行操作,常规的操作就是增删改查了。
我的这个程序也不例外,同样是增删改查,那么问题来了,数据从数据库里取出来后怎么保存呢?下面就对我们需要的数据进行抽象包装形成Model类,具体如下:
//User用户表 package com.example.hhj.hello.Model; public class User { private int mUserId; private String mUserName; private String mUserPs; public User(String name,String ps){ mUserName=name; mUserPs=ps; } public User(){ } public int getUserId() { return mUserId; } public void setUserId(int userId) { mUserId = userId; } public String getUserName() { return mUserName; } public void setUserName(String userName) { mUserName = userName; } public String getUserPs() { return mUserPs; } public void setUserPs(String userPs) { mUserPs = userPs; } }
//消息表 package com.example.hhj.hello.Model; import java.util.Date; public class Message { private int mMessageId; private int mUserSend; private int mUserRec; private long mSendDT; private String mContent; private int mType;//0-收,1-发 public int getMessageId() { return mMessageId; } public void setMessageId(int messageId) { mMessageId = messageId; } public int getUserSend() { return mUserSend; } public void setUserSend(int userSend) { mUserSend = userSend; } public int getUserRec() { return mUserRec; } public void setUserRec(int userRec) { mUserRec = userRec; } public long getSendDT() { return mSendDT; } public void setSendDT(long sendDT) { mSendDT = sendDT; } public String getContent() { return mContent; } public void setContent(String content) { mContent = content; } public int getType() { return mType; } public void setType(int type) { mType = type; } }
//好友列表 package com.example.hhj.hello.Model; public class FriendList { private int mListId; private int mUserId; private String mListName; public int getListId() { return mListId; } public void setListId(int listId) { mListId = listId; } public int getUserId() { return mUserId; } public void setUserId(int userId) { mUserId = userId; } public String getListName() { return mListName; } public void setListName(String listName) { mListName = listName; } }
//好友列表信息 package com.example.hhj.hello.Model; public class FriendListContent { private int mListId; private int mUserId; public int getListId() { return mListId; } public void setListId(int listId) { mListId = listId; } public int getUserId() { return mUserId; } public void setUserId(int userId) { mUserId = userId; } }
有了数据的保存结构之后,就让我们开始对数据库进行操作吧。
//操作User 表 package com.example.hhj.hello.DB; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.hhj.hello.Model.User; import com.example.hhj.hello.utils.MyApplication; import java.util.ArrayList; import java.util.List; public class UserDAO { static MyDBHelper sHelper; static SQLiteDatabase sDb; public static User GetById(int id){//查 if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1); sDb=sHelper.getWritableDatabase(); } Cursor cursor=sDb.query("users",null,"user_id=?",new String[]{id+""},null,null,null); if(cursor.getCount()>0){ cursor.moveToFirst(); User user=new User(); user.setUserId(id); user.setUserName(cursor.getString(1)); user.setUserPs(cursor.getString(2)); cursor.close(); return user; } else{ cursor.close(); return null; } } public static User GetByNamePs(String name,String ps){//查 if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1); sDb=sHelper.getWritableDatabase(); } Cursor cursor=sDb.query("users",null,"user_name=? and password=?",new String[]{name,ps},null,null,null); if(cursor.getCount()>0){ cursor.moveToFirst(); User user=new User(); user.setUserId(cursor.getInt(0)); user.setUserName(cursor.getString(1)); user.setUserPs(cursor.getString(2)); cursor.close(); return user; } else{ cursor.close(); return null; } } public static User GetByName(String name){//查 if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1); sDb=sHelper.getWritableDatabase(); } Cursor cursor=sDb.query("users",null,"user_name=?",new String[]{name},null,null,null); if(cursor.getCount()>0){ cursor.moveToFirst(); User user=new User(); user.setUserId(cursor.getInt(0)); user.setUserName(cursor.getString(1)); user.setUserPs(cursor.getString(2)); cursor.close(); return user; } else{ cursor.close(); return null; } } public static void Insert(User user){//增 if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1); sDb=sHelper.getWritableDatabase(); } ContentValues contentValues=new ContentValues(); contentValues.put("user_name",user.getUserName()); contentValues.put("password",user.getUserPs()); sDb.insert("users",null,contentValues); } public static List<User> GetAll(){//查 List<User> list=new ArrayList<>(); User user; if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1); sDb=sHelper.getWritableDatabase(); } Cursor cursor=sDb.query("users",null,null,null,null,null,null); if(cursor.getCount()>0){ while (cursor.moveToNext()){ user=new User(); user.setUserId(cursor.getInt(0)); user.setUserName(cursor.getString(1)); user.setUserPs(cursor.getString(2)); } cursor.close(); return list; } else{ cursor.close(); return null; } } }
对于User表,我做的主要就是查和增,改还没做(不想做了,这句话在后面的程序里会有体现)。
对于其他的数据表操作,由于大量贴代码,估计大家也不看,就先不贴了,大家可以自行去我的任意门下载。
对于数据库的操作,我们对于增删改查一个一个说,从代码开始说。
1、增:
if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1);//先打开数据库 sDb=sHelper.getWritableDatabase();//获取可操作数据库 } ContentValues contentValues=new ContentValues();//实例化一个ContentValues对象 contentValues.put("user_name",user.getUserName());//向ContentValues对象中以键值对的形式添加数据,注意,这里的键要和你的数据库字段名称保持一致 contentValues.put("password",user.getUserPs()); sDb.insert("users",null,contentValues);//调用Insert方法,完成插入。结束2、删:
public static void Delete(){
if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1);//先打开数据库 sDb=sHelper.getWritableDatabase();//获取可操作数据库 }String sql="Delete from users where user_name=1";//写sql语句 sDb.execSQL(sql);//执行删除操作 }
对于sqlite数据库,修改数据库内容有使用execSQL方法执行原始sql语句和使用它封装好的方法两种,我自己是再怎么方便怎么来,对于删除数据,用这个原生sql语句很方便,我一般会选择这个。
3、改:(方法同上)
4、查:
public static User GetByNamePs(String name,String ps){//登陆用方法
if(sHelper==null){ sHelper=new MyDBHelper(MyApplication.getContext(),"qq_test.db",null,1);//先打开数据库 sDb=sHelper.getWritableDatabase();//获取可操作数据库 }Cursor cursor=sDb.query("users",null,"user_name=? and password=?",new String[]{name,ps},null,null,null);//调用query方法获取数据 if(cursor.getCount()>0){//有数据 cursor.moveToFirst(); User user=new User(); user.setUserId(cursor.getInt(0));//通过Cursor取数据 user.setUserName(cursor.getString(1)); user.setUserPs(cursor.getString(2)); cursor.close();//关闭Cursor return user; } else{ cursor.close();//关闭Cursor return null; } }
这里说一下query()方法,首先他的参数如下:
Cursor query (boolean distinct, //没用过,可空,可选 String table, //标明,必选 String[] columns, //取哪些字段,必选 String selection, //where字句条件,必选 String[] selectionArgs, //where子句条件取值,必选 String groupBy, //分组,必选 String having, //分组后条件语句,必选 String orderBy, //排序,必选 String limit,//没用过 CancellationSignal cancellationSignal//没用过
对于返回的Cursor,他是一个游标,可以通过他来获取数据库内容,例如getInt(0),就是取返回的第一列Int型数据
对于数据库操作的介绍先写到这里吧,大家有什么疑问可以提,同时也欢迎各位指点,我们互相学习。
还有就是SharedPreferences,为什么会用到这个呢?在我做记住密码功能的时候,为了记住当前是哪个用户已经登陆,就想要记住他的Id,下次打开应用直接跳转到操作界面而不需要登陆,一个id如果单独用数据库表存,有点大材小用的感觉,所以就用了SharedPreferences 。
具体实现代码如下(讲解请看注释):
package com.example.hhj.hello.utils; import android.content.SharedPreferences; import android.preference.PreferenceManager; import static android.content.Context.MODE_PRIVATE; public class SharePUtil { public static void Put(int id){ SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());//获取一个SharedPreferences实例 SharedPreferences.Editor editor=pref.edit();//获取编辑器 editor.putInt("user_id",id);//修改内容,以键值对的形式,大家注意这种形式很常见 editor.apply();//提交 } public static void Remove(){ SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext()); SharedPreferences.Editor editor=pref.edit(); editor.remove("user_id"); editor.apply(); } public static int Get(){ SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext()); return pref.getInt("user_id",-1); } }
对于数据的存储就到这里了,欢迎大家一起讨论学习。
程序代码任意门:https://github.com/wshhja/hello_QQ
biubiubiu,大家可以star一下吗,虽然不知道有什么用。。。。