您的位置:首页 > 移动开发 > Android开发

Adnroid中的数据存储大全,以及ActiveAndroid的简单使用

2017-01-09 07:15 477 查看
进行android开发,势必会用到本地存放的功能,让APP持久化,不是单机的,下面介绍Android中的几种保存数据方法.

一. SharedPreference(保存一些变量值,登录信息等的简单信息)

通过Activity自带的getSharedPreferences方法,可以得到SharedPreferences对象。

public static void putBoolean(String key, boolean value, Context ctx) { //存
SharedPreferences sp = ctx.getSharedPreferences("config",
Context.MODE_PRIVATE);
sp.edit().putBoolean(key, value).commit();
}

public static boolean getBoolean(String key, boolean defValue, Context ctx) { //取
SharedPreferences sp = ctx.getSharedPreferences("config",
Context.MODE_PRIVATE);
return sp.getBoolean(key, defValue);
}


另外还有putString,putint等,用法一模一样


note:SharedPreference的默认保存的文件路径为 data/data/当前工程完整包名/shared_prefs下

应用卸载,数据丢失,SharedPreference也可以保存对象,但是非常麻烦,其他类型的数据建议利用内部文件进行存储

二. 手机内部文件存储(就是利用输入输出流进行写入和读取)

例:保存一张图片到SD卡中的方法

public static String imagePath(Context context, File file, int id) {
try {
Bitmap pic = BitmapFactory.decodeResource(context.getResources(), id);
FileOutputStream fos = new FileOutputStream(file);
pic.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Throwable t) {
t.printStackTrace();
}
return file.getAbsolutePath();
}


三. sqlite数据库

Android上的小型数据库,数据类型有

•INT : 整数

•FLOAT: 小数

•CHAR : 字符串文本

•BLOB : 文件

•TEXT:字符串

•DATE : 日期/日期时间

创建数据库的步骤:

1.创建类继承SQLiteOpenHelper

public class My_SQL_Info extends SQLiteOpenHelper{
public My_SQL_Info(Context context,String name) {
super(context,name, null, 1);  //数据库的名字,和版本号
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "          //这里就是创建表名和属性
+ user+ "("
+ Sql.FAVID + " INT ,  "
+ Sql.DIANZHAN + " INT ,  "
+ Sql.AID + " INT ,  "
+ Sql.CLICK + " INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//更新数据库时才会调用(根据版本号)
}

}


2.使用SQL语句进行增删改查的操作

My_SQL_Info helper=new My_SQL_Info()

//向表中添加一条记录
public void add(String name,int age){
SQLiteDatabase sd=helper.getWritableDatabase();
sd.execSQL("insert into " + 表名 + " (name,age) values (?,?)",new Object[]{name,age});
sd.close();
}
//返回数据库中的全部数据
public void getAll(){
List<User> user=new ArrayList();
SQLiteDatabase sd=helper.getWritableDatabase();
Cursor curso=  sd.rawQuery("select * from" + 表名,null);
while(curso.moveToNext()){
String name=curso.getString(curso.getColumnIndex("name"));
int age=curso.getint(curso.getColumnIndex(age));
user person = new user(name, age);
user.add(person);
}
cursor.close();
sd.close();
return user;
}


//根据name查询并返回对应的这条数据,没有则返回null
public void getName(){
User user=null;
SQLiteDatabase sd=helper.getWritableDatabase();
Cursor cursor=sd.rawQuery("select * from "+ 表名 + "where name=?",new String[ ]{name});
if (cursor.moveToNext) {
String name=curso.getString(curso.getColumnIndex("name"));
int age=curso.getint(curso.getColumnIndex(age));
user= new User(name, age);
}
cursor.close();
db.close();
return user;
}
/**
* 更新aid对应的name的age值
*/
public void update(String name, int age) {
SQLiteDatabase db = helper.getReadableDatabase();
db.execSQL("update " + 表名+ " set age=? where name=?", new Object[]{age, name});
db.close();
} /**
* 删除一条记录
*/
public void delete(String name) {
SQLiteDatabase db = helper.getReadableDatabase();
db.execSQL("delete from " + 表名+ " where name=?", new Object[]{name});
db.close();
}


/**
* 判断有没有这张表
*/
public boolean tabIsExist(String tabName) {
boolean result = false;
SQLiteDatabase db = helper.getReadableDatabase();
if (tabName == null) {
return false;
}
Cursor cursor = null;
try {
String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tabName.trim() + "' ";
cursor = db.rawQuery(sql, null);
if (cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
result = true;
}
}

} catch (Exception e) {
// TODO: handle exception
}
return result;
}


note:数据保存的路径: /data/data/projectPackage/databases/xxx.db

另外再介绍一种简单的操作数据库的框架ActiveAndroid

项目地址:https://github.com/pardom/ActiveAndroid

1.导入项目

maven { url “https://oss.sonatype.org/content/repositories/snapshots/” }

依赖:compile ‘com.michaelpardo:activeandroid:3.1.0-SNAPSHOT’

2.在配置文件中 AA_DB_NAME的value表示数据库名,AA_DB_VERSION表示版本号

<meta-data android:name="AA_DB_NAME" android:value="user.db" />
<meta-data android:name="AA_DB_VERSION" android:value="1" />


3.在Application中进行初始化

@Override
public void onCreate() {
super.onCreate();
ActiveAndroid.initialize(this);
}
@Override
public void onTerminate() {
super.onTerminate();
ActiveAndroid.dispose();
}


4.创建表

@Table(name = "user_info")  //表名,若没有,则默认类名就是表名
public class UserInfodb {
@Column(name = "name")
private String name;
@Column(name = "age")
private int   age;


5.增删改查

增:

UserInfodb restaurants = new UserInfodb();
restaurants.name = "张三";
restaurants.save();


批量插入:

ActiveAndroid.beginTransaction();
try {
for (int i = 0; i < 100; i++) {
Item item = new Item();
item.name = "Example " + i;
item.save();
}
ActiveAndroid.setTransactionSuccessful();
}
finally {
ActiveAndroid.endTransaction();
}


更新:

new Update(UserInfodb .class).set("age=?," + "name=?", age, name).execute();


删除:

Item item = Item.load(Item.class, 1);
item.delete();


查询一条:

public static Item getRandom(Category category) {
return new Select()
.from(Item.class)
.where("Category = ?", category.getId())
.orderBy("RANDOM()")
.executeSingle();
}


查询所有:

public static List<Item> getAll(Category category) {
return new Select()
.from(Item.class)
.where("Category = ?", category.getId())
.orderBy("Name ASC")
.execute();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: