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

Android-存储数据的几种方法

2015-04-13 21:33 411 查看
1.Android用Java开发,可以使用全局变量

public String picpath;
public String hasfind;
public String ProductID="0";


这种方法适用于程序运行期间,需要多个地方用到的临时值有用

,比如上传图片的路径,截图的路径等,因为这些值都是其他activity产生的,后来可能在其他activity中使用,但是我不想在activity间传来传去,
刚脆扔到全局变量里,这样修改起来也方便.但是全局变量只在内存中保存,程序关闭后数据就不存在了.那么我要保存持久的数据该怎么保存呢,
你首先肯定想到了数据库,对没错,数据库是存储数据最好的地方,但是作为移动端,只是一个客户端不可能把用户的数据都保存在手机上吧,智能机
怎么能离开网络?数据库固然可以,但是重复的读写数据库真的没有必要,客户端只需要存取少量的数据,既然应用都离不开网络,那用时再去服务器
上取就是了,但是还有一些必须保存在客户手机上得东西,不得不存在客户端,像用户名\密码\授权token~~~
2.SharedPreferences存储用户名 密码等信息

SharedPreferences和iOS下plist一样实际是个xml文件,里面的数据以键值对来保存在客户端的数据

SharedPreferences sp = context.getSharedPreferences("userinfo",0);
username = sp.getString("username", "");Editor editor = sp.edit();

editor.putString("username", username);
editor.putString("password", enpwd);
editor.commit();


3.Properties
这个一般用来保存应用的配置文件信息,学Java的都认识这个文件吧,安卓里一样适用,这些配置文件一般保存在应用安装目录下,防止用户删除或者<恶意修改信息,我本人更喜欢用Properties,本质上它也是键值对保存数据

尼玛csdn的默认编辑器还能再垃圾一点吗!!!!!!


/**
* 得到配置文件
* @return
*/
public Properties getProp() {
FileInputStream fis = null;
Properties props = new Properties();
try{

//读取app_path目录下的config
File dirConf = mContext.getDir(path, Context.MODE_PRIVATE);
fis = new FileInputStream(dirConf.getPath() + File.separator + APP_CONFIG);

props.load(fis);
<p class="p1"><span style="white-space:pre">			</span>String value = props.getProperty(key);</p>		}catch(Exception e){
}finally{
try {
fis.close();
} catch (Exception e) {}
}
return props;
}


4.数据库SQLite

Android和iOS都自带了sqlite数据库,这个数据库虽小,但是胆小精悍,基本的SQL语句都支持,连接 访问也简单,适合保存大量的数据在客户端.

SQLiteDatabase db = context.openOrCreateDatabase("my.db",
MODE_PRIVATE, null);//创建或打开数据库
db.execSQL(CREATE_TABLE_SQL);//执行创建表SQL
String sqlbrand = "select distinct b.id,b.name  from ProductBrands b inner join   Product c on b.id=c.brandsid and c.banchyn='0' and c.showinsellthrough='1'  ";//查询所有品牌
String id = "";
String type ="";
String brand ="";

Cursor cursor2 = db.rawQuery(sqlbrand, null);//执行查询语句
while(cursor2.moveToNext()){
id = cursor2.getString(0);
brand = cursor2.getString(1);
brandlist.add(new Product(id, brand));
}
cursor2.close();
db.close();
5.网络
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: