安卓基础学习_ Android数据存储与IO
2013-11-23 23:24
495 查看
数据储存方式: 1.文件 2.SharesPreferences(偏好参数保存) 3.SQLite数据库 4.内容提供者(数据共享) 5.网络 一、SharePreferences偏好参数 SharesPreferences保存用户偏好参数(XML文件形式保存在shared_prefs下) public void save(String username,Integer password)//保存参数 { SharedPreferences preferences=context.getSharedPreferences("userinfo", Context.MODE_PRIVATE); Editor editor=preferences.edit(); editor.putString("username", username); editor.putInt("password", password); editor.commit(); } public Map<String,String> getPreferences()//读取参数 { Map<String,String> userinfo=new HashMap<String, String>(); SharedPreferences preferences=context.getSharedPreferences("userinfo", Context.MODE_PRIVATE); userinfo.put("username", preferences.getString("username", "")); userinfo.put("password", String.valueOf(preferences.getInt("password", 0))); return userinfo; } 读写其他应用的SharePreferences 要读写其他程序的SharePreferences指定相应的访问权限,MODE_WORLD_READABLE:可被其他程序读取,MODE_WORLD_WRITEABLE:可被其他程序写入 实现步骤: 1.需要创建其他程序对应的Context 2.调用其他程序Context的getSharePreferences(String name,int mode)即可获取相应的SharePreferences对象 3.调用SharePreferences的edit()方法获取相应的Editor即可 UserCount应用: //MODE_WORLD_READABLE:This constant was deprecated in API level 17. SharedPreferences preferences = getSharedPreferences("count", MODE_WORLD_READABLE); // 读取SharedPreferences里的count数据 int count = preferences.getInt("count", 0); Editor editor = preferences.edit(); // 存入数据 editor.putInt("count", ++count); // 提交修改 editor.commit(); public class ReadOtherPreferences extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Context useCount = null; try { // 获取其他程序所对应的Context useCount = createPackageContext("org.crazyit.io", Context.CONTEXT_IGNORE_SECURITY); } catch (NameNotFoundException e) { e.printStackTrace(); } // 使用其他程序的Context获取对应的SharedPreferences SharedPreferences prefs = useCount.getSharedPreferences("count", Context.MODE_WORLD_READABLE); // 读取数据 int count = prefs.getInt("count", 0); TextView show = (TextView) findViewById(R.id.show); // 显示读取的数据内容 show.setText("UseCount应用程序以前被使用了" + count + "次。"); } } 二、File存储 读写SD卡上的文件步骤: 1.调用Environment的getExternalStorageState()判断手机上是否插入了SD卡,并且应用程序具有读写SD卡的权限; 2.调用Environment的getExternalStorageDirectory()方法来获取外部存储器,也就是SD卡的目录; 3.使用FileInputStream、FileOutputStream、FileReader或FileWriter读写SD卡里的文件. 保存文件到SD卡 public void onClick(View v) { String name=filename.getText().toString(); String content=filecontent.getText().toString(); FileService service=new FileService(getApplicationContext()); try { if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { service.saveToSDCard(name, content); Toast.makeText(getApplicationContext(), "Save Success", 1000).show(); } else Toast.makeText(getApplicationContext(), "SD is not avi...", 1000).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Save ERROR", 1000).show(); e.getStackTrace(); } } publicvoid saveToSDCard(String filename,String filecontent) throws Exception { File file=new File(Environment.getExternalStorageDirectory(),filename); FileOutputStream fos=new FileOutputStream(file); fos.write(filecontent.getBytes()); fos.close(); } <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 保存文件 public void save(String filename,String filecontent) throws Exception { FileOutputStream fos=context.openFileOutput(filename, Context.MODE_PRIVATE); ---文件操作模式--- // Context.MODE_PRIVATE:私有操作模式,不能被其他应用使用(覆盖) // Context.MODE_APPEND:追加操作模式,不能被其他应用使用(追加) // Context.MODE_WORLD_READABLE:可读操作模式,可被其他应用读取 // Context.MODE_WORLD_WRITEABLE:可写操作模式,可被其他应用写入 // Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE:可读写模式 fos.write(filecontent.getBytes()); fos.close(); } 读取文件内容 private static void read(String filepath) throws Exception { File path=new File(filepath); FileInputStream fis=new FileInputStream(path); ByteArrayOutputStream bos=new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len=0; while((len=fis.read(buffer))!=-1) { bos.write(buffer,0,len); } byte[] data=bos.toByteArray(); String filecontent=new String(data); Log.i(TAG, filecontent); bos.close(); fis.close(); } 往文件中写入内容 private static void write(String filepath,String filecontent) throws Exception { File path=new File(filepath); FileOutputStream fos=new FileOutputStream(path); fos.write(filecontent.getBytes()); fos.close(); } Activity提供了getCacheDir(),getFilesDir方法 getCacheDir():访问/data/data/<package name>/cache目录 getFilesDir():访问文件/data/data/<package name>/files目录 -------------------SD卡文件浏览器----------------------- public class SDFileExplorer extends Activity { ListView listView; TextView textView; // 记录当前的父文件夹 File currentParent; // 记录当前路径下的所有文件的文件数组 File[] currentFiles; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 获取列出全部文件的ListView listView = (ListView) findViewById(R.id.list); textView = (TextView) findViewById(R.id.path); // 获取系统的SD卡的目录 File root = new File("/mnt/sdcard/"); // 如果 SD卡存在 if (root.exists()) { currentParent = root; currentFiles = root.listFiles(); // 使用当前目录下的全部文件、文件夹来填充ListView inflateListView(currentFiles); } // 为ListView的列表项的单击事件绑定监听器 listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // 用户单击了文件,直接返回,不做任何处理 if (currentFiles[position].isFile()) return; // 获取用户点击的文件夹下的所有文件 File[] tmp = currentFiles[position].listFiles(); if (tmp == null || tmp.length == 0) { Toast.makeText(SDFileExplorer.this , "当前路径不可访问或该路径下没有文件", Toast.LENGTH_SHORT).show(); } else { // 获取用户单击的列表项对应的文件夹,设为当前的父文件夹 currentParent = currentFiles[position]; //② // 保存当前的父文件夹内的全部文件和文件夹 currentFiles = tmp; // 再次更新ListView inflateListView(currentFiles); } } }); // 获取上一级目录的按钮 Button parent = (Button) findViewById(R.id.parent); parent.setOnClickListener(new OnClickListener() { @Override public void onClick(View source) { try { if (!currentParent.getCanonicalPath() .equals("/mnt/sdcard")) { // 获取上一级目录 currentParent = currentParent.getParentFile(); // 列出当前目录下所有文件 currentFiles = currentParent.listFiles(); // 再次更新ListView inflateListView(currentFiles); } } catch (IOException e) { e.printStackTrace(); } } }); } private void inflateListView(File[] files) //① { // 创建一个List集合,List集合的元素是Map List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); for (int i = 0; i < files.length; i++) { Map<String, Object> listItem = new HashMap<String, Object>(); // 如果当前File是文件夹,使用folder图标;否则使用file图标 if (files[i].isDirectory()) { listItem.put("icon", R.drawable.folder); } else { listItem.put("icon", R.drawable.file); } listItem.put("fileName", files[i].getName()); // 添加List项 listItems.add(listItem); } // 创建一个SimpleAdapter SimpleAdapter simpleAdapter = new SimpleAdapter(this , listItems, R.layout.line , new String[]{ "icon", "fileName" } , new int[]{R.id.icon, R.id.file_name }); // 为ListView设置Adapter listView.setAdapter(simpleAdapter); try { textView.setText("当前路径为:" + currentParent.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } } } 三、SQLite数据库 SQLite数据库操作(增删改) public class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context) { super(context, "userinfo.db", null, 1); } public void onCreate(SQLiteDatabase db) {//在数据库每一次被创建的时候调用的 String sql="CREATE TABLE userinfo(_id integer primary key autoincrement,name varchar(10),phone varchar(11) NULL,amount integer NULL)"; db.execSQL(sql); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//数据库版本变更时调用 String sql="ALTER TABLE userinfo ADD age ingeter"; db.execSQL(sql); } } public class UserService { private DBOpenHelper dbhelper; public UserService(Context context) { this.dbhelper = new DBOpenHelper(context); } public void add(User user)//增加 { SQLiteDatabase db=dbhelper.getWritableDatabase(); String sql="INSERT INTO userinfo(name,phone,amount) values(?,?,?)"; db.execSQL(sql, new Object[] {user.getName(),user.getPhone(),user.getAmount()}); } public void add(User user) { SQLiteDatabase db=dbhelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put("name", user.getName()); values.put("phone", user.getPhone()); values.put("amount", user.getAmount()); db.insert("userinfo", null, values);//API方法 } public void delete(Integer _id)//删除 { SQLiteDatabase db=dbhelper.getWritableDatabase(); String sql="DELETE FROM userinfo where _id=?"; db.execSQL(sql, new Object[]{_id}); } public void delete(Integer userid) { SQLiteDatabase db=dbhelper.getWritableDatabase(); db.delete("userinfo", "_id=?", new String[]{userid.toString()});//API方法 } public void update(User user)//修改 { SQLiteDatabase db=dbhelper.getWritableDatabase(); String sql="UPDATE userinfo SET name=?,phone=?,amount=? where _id=?"; db.execSQL(sql, new Object[]{user.getName(),user.getPhone(),user.getAmount(),user.get_id()}); } public void update(User user) { SQLiteDatabase db=dbhelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put("name", user.getName()); values.put("phone", user.getPhone()); values.put("amount", user.getAmount()); db.update("userinfo", values, "_id=?", new String[]{user.get_id().toString()});//API方法 } public User find(Integer _id)//查找 { SQLiteDatabase db=dbhelper.getReadableDatabase(); String sql="Select * from userinfo where _id=?"; Cursor cursor=db.rawQuery(sql, new String[]{_id.toString()}); if(cursor.moveToFirst()) { int id=cursor.getInt(cursor.getColumnIndex("_id")); String name=cursor.getString(cursor.getColumnIndex("name")); String phone=cursor.getString(cursor.getColumnIndex("phone")); int amount=cursor.getInt(cursor.getColumnIndex("amount")); return new User(id,name,phone,amount); } cursor.close(); return null; } public User find(Integer userid) { SQLiteDatabase db=dbhelper.getReadableDatabase(); Cursor cursor=db.query("userinfo", null, "_id=?", new String[]{userid.toString()}, null, null, null);//API方法 if(cursor.moveToFirst()) { int id=cursor.getInt(cursor.getColumnIndex("_id")); String name=cursor.getString(cursor.getColumnIndex("name")); String phone=cursor.getString(cursor.getColumnIndex("phone")); int amount=cursor.getInt(cursor.getColumnIndex("amount")); return new User(id,name,phone,amount); } cursor.close(); return null; } public List<User> getScrollData(int offset,int maxResult)//分页获取记录,返回List { SQLiteDatabase db=dbhelper.getReadableDatabase(); List<User> users=new ArrayList<User>(); String sql="SELECT * FROM userinfo order by _id asc limit ?,?"; Cursor cursor=db.rawQuery(sql, new String[]{String.valueOf(offset),String.valueOf(maxResult)}); while(cursor.moveToNext()) { int id=cursor.getInt(cursor.getColumnIndex("_id")); String name=cursor.getString(cursor.getColumnIndex("name")); String phone=cursor.getString(cursor.getColumnIndex("phone")); int amount=cursor.getInt(cursor.getColumnIndex("amount")); users.add(new User(id,name,phone,amount)); } cursor.close(); return users; } public List<User> getScrollData(int offset,int maxResult) { SQLiteDatabase db=dbhelper.getReadableDatabase(); Cursor cursor=db.query("userinfo", null, null, null, null, null, "_id asc", offset+","+maxResult);//API方法 List<User> users=new ArrayList<User>(); while(cursor.moveToNext()) { int id=cursor.getInt(cursor.getColumnIndex("_id")); String name=cursor.getString(cursor.getColumnIndex("name")); String phone=cursor.getString(cursor.getColumnIndex("phone")); int amount=cursor.getInt(cursor.getColumnIndex("amount")); users.add(new User(id,name,phone,amount)); } cursor.close(); return users; } public Cursor getCursorScrollData(int offset,int maxResult)//分页获取记录,返回Cursor { SQLiteDatabase db=dbhelper.getReadableDatabase(); String sql="SELECT * FROM userinfo order by _id asc limit ?,?"; Cursor cursor=db.rawQuery(sql, new String[]{String.valueOf(offset),String.valueOf(maxResult)}); return cursor; } public long getCount() //获取记录总数 { SQLiteDatabase db=dbhelper.getReadableDatabase(); String sql="SELECT count(*) FROM userinfo"; Cursor cursor=db.rawQuery(sql, null); cursor.moveToFirst(); long result=cursor.getLong(0); cursor.close(); return result; } public long getCount() { SQLiteDatabase db=dbhelper.getReadableDatabase(); Cursor cursor=db.query("userinfo", new String[]{"count(*)"}, null, null, null, null, null); cursor.moveToFirst(); long count=cursor.getLong(0); return count; } public void payment()//数据库事务 { SQLiteDatabase db=dbhelper.getWritableDatabase(); db.beginTransaction(); try { db.execSQL("UPDATE userinfo set amount=amount-10 where _id=88"); db.execSQL("UPDATE userinfo set amount=amount+10 where _id=89"); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } }
相关文章推荐
- (about program)android中打印java调用栈
- 编译Android版本的OSG库
- Android SDK 在win8下的常见问题
- Android学习笔记_9_SQLiteOpenHelper对象之数据库增删改查以及事务回滚操作
- Android实现Filterable通过输入文本框实现联系人自动筛选...
- Ubuntu13.04环境下载、编译Android源代码
- 安卓基础学习_Android事件处理
- Android开发-一个简单的五子棋游戏
- android中的Intent(意图)理解
- Android中的BroadcastReceiver理解
- Android Please ensure that adb is correctly located at 类问题解决
- Android Bitmap和Drawable互转及使用BitmapFactory解析图片流
- Android打开并读取Word文件到html中采用PIO技术
- Android学习笔记——文件路径(/mnt/sdcard/...)、Uri(content://media/external/...)学习
- Android_百度地图BaiduMap_搜索服务
- Android调试时, "adb devices"命令提示 adb server is out of date. killing...
- Android 3.0 r1 API中文文档(108) —— ExpandableListAdapter
- android手机获取系统短信sqlite数据库并查看内容
- 我的android 第12天 - 嵌入式关系型SQLite数据库存储数据
- Android 中常见Bitmap操作