安卓基础学习_ Android数据存储与IO

来源:互联网 发布:adobereader破解版mac 编辑:程序博客网 时间:2024/05/19 12:39
数据储存方式: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.需要创建其他程序对应的Context2.调用其他程序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{@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);Context useCount = null;try{// 获取其他程序所对应的ContextuseCount = createPackageContext("org.crazyit.io",Context.CONTEXT_IGNORE_SECURITY);}catch (NameNotFoundException e){e.printStackTrace();}// 使用其他程序的Context获取对应的SharedPreferencesSharedPreferences 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();}elseToast.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;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);// 获取列出全部文件的ListViewlistView = (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();// 使用当前目录下的全部文件、文件夹来填充ListViewinflateListView(currentFiles);}// 为ListView的列表项的单击事件绑定监听器listView.setOnItemClickListener(new OnItemClickListener(){@Overridepublic 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;// 再次更新ListViewinflateListView(currentFiles);}}});// 获取上一级目录的按钮Button parent = (Button) findViewById(R.id.parent);parent.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View source){try{if (!currentParent.getCanonicalPath().equals("/mnt/sdcard")){// 获取上一级目录currentParent = currentParent.getParentFile();// 列出当前目录下所有文件currentFiles = currentParent.listFiles();// 再次更新ListViewinflateListView(currentFiles);}}catch (IOException e){e.printStackTrace();}}});}private void inflateListView(File[] files) //①{// 创建一个List集合,List集合的元素是MapList<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);}// 创建一个SimpleAdapterSimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems, R.layout.line, new String[]{ "icon", "fileName" }, new int[]{R.id.icon, R.id.file_name });// 为ListView设置AdapterlistView.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();}}}
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 微信朋友欠钱把我拉黑了怎么办 淘宝东西寄回去订单号忘写了怎么办 商家退款后客户不退回商品怎么办 有凭证还了本金不消条怎么办 华为荣耀畅玩7x充电慢怎么办 发现淘宝店盗用了我拍的视频怎么办 淘宝售假只能发布50个宝贝怎么办 在肯德基买的券过期了怎么办 新买的手机实体店不给换怎么办 苹果平板充电时显示不在充电怎么办 苏州驾校考试科目二挂了两次怎么办 支付宝收款码少收钱了怎么办 支付宝发的红包不领取怎么办 微信存在风险不能领红包怎么办 天猫超市电话写错了怎么办 天猫买东西地址写错了怎么办 天猫上买衣服收货电话写错了怎么办 电视遥控器不小心按了高清键怎么办 康佳电视打开右下角是红色的怎么办 天猫超市退款成功后收到货怎么办 天猫还没收到货就确认收货了怎么办 支付宝红包抵扣被关了怎么办 水貂绒大衣白色过色了怎么办 双面羊绒大衣袖子洗短了怎么办 特殊类型订单销量评价删除后怎么办 淘宝上卖家发货发错了地址怎么办 买完保险想换保险代理人怎么办 怀孕内裤两边磨的好疼怎么办 露肩连体裤穿着卡裆怎么办 魅族手机恋与制作人换诺基亚怎么办 蚊子叮咬后擦风油精了红肿怎么办 机动车已转让没过户出了事情怎么办 签好的合同如果甲方违约怎么办? 饭店没签合同辞职不给工资怎么办 两家为了带孩子闹翻了怎么办啊? 抵押后租赁的房屋被法院拍卖怎么办 房子买20年了没有过户怎么办 二手车没过户行驶证丢了怎么办 买的二手车行驶证丢了怎么办 在京东仓库做事把东西损坏了怎么办 微信显示该账号登陆环境异常怎么办