存储方式分类

Android支持的数据存储方式:SharedPrefrence存储手机内部文件存储手机外部文件存储Sqlite数据库存储远程服务器存储

SharedPrefrence存储

介绍

SP存储专门用来存储一些单一的小数据
存储数据的类型:  boolean, float, int, long, String
数据保存的路径:  /data/data/packageName/shared_prefs/yyy.xml
可以设置数据只能是当前应用读取, 而别的应用不可以
应用卸载时会删除此数据

API

SharedPreferences: 对应sp文件的接口,是个接口context. getSharedPreferences (String name, int mode): 得到SP对象name: 文件名(不带.xml)mode: 生成的文件模式(是否是私有的,即其它应用是否可以访问)SharedPreferences可以得到这个存储的数据,但是不能修改它,修改操作由Editor对象来操作Editor sp.edit() : 得到Editor对象Xxx sp.getXxx(name,defaultValue): 根据name得到对应的数据Editor : 能更新sp文件的接口Editor put(name, value) : 保存一个键值对, 没有真正保存到文件中Editor remove(name)commit(): 提交, 数据真正保存到文件中了

例子

package com.example.datastorage;import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;public class SpActivity extends Activity
{public EditText et_sp_key;public EditText et_sp_value;public SharedPreferences sp;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_sp);et_sp_key=(EditText) findViewById(R.id.et_sp_key);et_sp_value=(EditText) findViewById(R.id.et_sp_value);//1.得到sp对象sp=getSharedPreferences("jane", Context.MODE_PRIVATE);}public void save(View v){//2.得到editor对象Editor edit = sp.edit();//3.得到输入的key和valueString key=et_sp_key.getText().toString();String value=et_sp_value.getText().toString();//4.使用editor保存edit.putString(key, value).commit();Toast.makeText(this, "ok了", 0).show();}public void read(View v){String key=et_sp_key.getText().toString();String value = sp.getString(key, null);if(value==null){Toast.makeText(this, "没有这个值", 0).show();}else{et_sp_value.setText(value);}}
}

手机内部文件存储

介绍

应用运行需要的一些较大的数据或图片可以用文件保存的手机内部
文件类型: 任意
数据保存的路径: /data/data/projectPackage/files/
可以设置数据只能是当前应用读取, 而别的应用不可以
应用卸载时会删除此数据

API

读取文件FileInputStream fis = openFileInput("logo.png");
保存文件FileOutputStream fos = openFileOutput("logo.png", MODE_PRIVATE)
得到files文件夹对象File filesDir = getFilesDir();
操作asserts下的文件得到AssetManager : context.getAssets();读取文件: InputStream open(filename);
加载图片文件Bitmap BitmapFactory.decodeFile(String pathName)   // .bmp/.png/.jpg

例子

package com.example.datastorage;import java.io.FileOutputStream;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;public class IFActivity extends Activity
{private ImageView iv_if;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_if);iv_if=(ImageView) findViewById(R.id.iv_if);}public void save(View v) throws Exception{//1.先得到InputStream,用来读取assets下的logo.png//2.得到OutputStream,用来输出data/data/packageName/files/logo.pngAssetManager manager = getAssets();InputStream is = manager.open("logo.png");FileOutputStream fos = openFileOutput("logo.png", Context.MODE_PRIVATE);//3.边读边写byte[] buffer =new byte[1024];int len=-1;while((len=is.read(buffer))!=-1){fos.write(buffer, 0, len);}fos.close();is.close();Toast.makeText(this, "保存完成", 0).show();}public void read(View v){//1.得到图片问价路径String path = getFilesDir().getAbsolutePath();String imagePath=path+"/logo.png";//2.读取加载图片文件得到bitmap对象Bitmap bitmap = BitmapFactory.decodeFile(imagePath);//3.将它设置到imageView中显示iv_if.setImageBitmap(bitmap);}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextViewandroid:id="@+id/textView1"android:layout_width="match_parent"android:layout_height="wrap_content"android:padding="5dp"android:text="1. 将asserts下的logo.png保存到手机内部\n2. 读取手机内部图片文件显示"android:textColor="#ff0000"android:textSize="15sp" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><Buttonandroid:id="@+id/btn_if_save"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="save"android:text="保 存" /><Buttonandroid:id="@+id/btn_if_read"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="read"android:text="读 取" /></LinearLayout><ImageViewandroid:id="@+id/iv_if"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ic_launcher" />
</LinearLayout>

手机外部文件存储

介绍

应用运行用到的数据文件(如图片)可以保存到sd卡中
文件类型: 任意
数据保存的路径: 路径1: /storage/sdcard/Android/data/packageName/files/路径2: /storage/sdcard/xxx/
路径1 :其它应用可以访问,应用卸载时删除
路径2 : 其它应用可以访问, 应用卸载时不会删除
必须保证sd卡挂载在手机上才能读写, 否则不能操作

API

Environment :  操作SD卡的工具类得到SD卡的状态:Environment.getExternalStorageState() 得到SD卡的路径:Environment.getExternalStorageDirectory()SD卡可读写的挂载状态值:Environment.MEDIA_MOUNTEDcontext. getExternalFilesDir():  得到/mnt/sdcard/Android/data/pageckage_name/files/xxx.txt操作SD卡的权限:android.permission.WRITE_EXTERNAL_STORAGE

例子

package com.example.datastorage;import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;public class OFActivity extends Activity
{private EditText et_of_name;private EditText et_of_content;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_of);et_of_name=(EditText) findViewById(R.id.et_of_name);et_of_content=(EditText) findViewById(R.id.et_of_content);}public void save(View v) throws Exception{/** 1.判断sd卡的状态,如果是挂载的状态才可以继续,否则就提示* 2.读取输入的文件名/没人* 3.得到指定文件的OutputSteam*        1)得到sd卡下的files路径*       2)组成完整的路径*      3)创建FileOutputStream* 4.写出数据*/if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){String fileName = et_of_name.getText().toString();String context = et_of_content.getText().toString();/** @param type The type of files directory to return.  May be null for* the root of the files directory or one of* the following Environment constants for a subdirectory:* {@link android.os.Environment#DIRECTORY_MUSIC},* {@link android.os.Environment#DIRECTORY_PODCASTS},* {@link android.os.Environment#DIRECTORY_RINGTONES},* {@link android.os.Environment#DIRECTORY_ALARMS},* {@link android.os.Environment#DIRECTORY_NOTIFICATIONS},* {@link android.os.Environment#DIRECTORY_PICTURES}, or* {@link android.os.Environment#DIRECTORY_MOVIES}.getExternalFilesDir需要一个type的参数,如果传入的是null,那么就是代表外存的file根目录自己,如果是DIRECTORY_MUSIC,就会在files目录下面再创建一个movies目录,然后再将文件放进去*/String filesPath = getExternalFilesDir(null).getAbsolutePath();String filePath= filesPath +"/"+fileName;FileOutputStream fos =new FileOutputStream(filePath);fos.write(context.getBytes("UTF-8"));fos.close();Toast.makeText(this, "保存完成", 0).show();}else{Toast.makeText(this, "sd卡不存在", 0).show();           }}public void read(View v) throws Exception{if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){String fileName = et_of_name.getText().toString();String filesPath = getExternalFilesDir(null).getAbsolutePath();String filePath= filesPath +"/"+fileName;FileInputStream fis = new FileInputStream(filePath);ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buffer =new byte[1024];int len= -1;while((len=fis.read(buffer))!=-1){baos.write(buffer,0,len);}String context =baos.toString();et_of_content.setText(context);}else{Toast.makeText(this, "sd卡不存在", 0).show();           }}public void save2(View v) throws Exception{if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){String fileName = et_of_name.getText().toString();String context = et_of_content.getText().toString();//得到指定文件的FileOutputStream//1). /storage/sdcard///2). /storage/sdcard/jane/(创建文件夹)//3). /storage/sdcard/jane/xxx.txtString sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();File file = new File(sdpath+"/jane");if(!file.exists()){file.mkdir();}String filePath = sdpath+"/jane/"+fileName;FileOutputStream fos =new FileOutputStream(filePath);fos.write(context.getBytes("UTF-8"));fos.close();Toast.makeText(this, "保存完成", 0).show();}else{Toast.makeText(this, "sd卡不存在", 0).show();          }}public void read2(View v) throws Exception{if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){String fileName = et_of_name.getText().toString();String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();String filePath = sdpath+"/jane/"+fileName;FileInputStream fis = new FileInputStream(filePath);ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buffer =new byte[1024];int len= -1;while((len=fis.read(buffer))!=-1){baos.write(buffer,0,len);}String context =baos.toString();et_of_content.setText(context);fis.close();}else{Toast.makeText(this, "sd卡不存在", 0).show();           }}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><EditTextandroid:id="@+id/et_of_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="存储的文件名" /><EditTextandroid:id="@+id/et_of_content"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="存储的文件内容" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="save"android:text="保 存" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="read"android:text="读 取" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="save2"android:text="保 存2" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:onClick="read2"android:text="读 取2" /></LinearLayout>
</LinearLayout>

例子

修改应用名称

package com.example.apphouse;import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;public class MainActivity extends Activity implements OnItemLongClickListener
{/** 现在需要给里面的item添加长按,然后实现修改名称的功能* 现在需要给gridView的item添加长按监听* 在回调方法里面实现AlertDialog* 然后需要处理点击修改,*         需要更新界面,*        还需要将名称保存到sp中* 还需要保证退出后再进入显示的是修改过的名称*/private GridView gridView;private MyAdapter myAdapter;private SharedPreferences sp;String[] names = new String[] { "手机防盗", "通讯卫士", "软件管理", "流量管理", "进程管理","手机杀毒", "缓存清理", "高级工具", "设置中心" };int[] icons = new int[] { R.drawable.widget01, R.drawable.widget02,R.drawable.widget03, R.drawable.widget04, R.drawable.widget05,R.drawable.widget06, R.drawable.widget07, R.drawable.widget08,R.drawable.widget09 };@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);gridView =(GridView) findViewById(R.id.gridView1);myAdapter=new MyAdapter(this, names, icons);gridView.setAdapter(myAdapter);gridView.setOnItemLongClickListener(this);sp=getSharedPreferences("jane", Context.MODE_PRIVATE);}@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id){if(position==0){//得到当前显示的名称final TextView textview = (TextView) view.findViewById(R.id.name);String name = textview.getText().toString();//为dialog准备输入框对象final EditText editText =new EditText(this);editText.setHint(name);//显示AlertDialognew AlertDialog.Builder(this).setTitle("修改名称").setView(editText).setPositiveButton("修改", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){String newName = editText.getText().toString();//更新界面textview.setText(newName);//将名称保存到sp中,注意呀,一定要commit(),不然没法保存sp.edit().putString("NAME", newName).commit();}}).setNegativeButton("Cancel", null).show();}return true;}
}
package com.example.apphouse;import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;public class MyAdapter extends BaseAdapter
{public Context context;public String[] names;public int[] icons;private SharedPreferences sp;public MyAdapter(Context context, String[] names, int[] icons){super();this.context = context;this.names = names;this.icons = icons;sp=context.getSharedPreferences("jane", context.MODE_PRIVATE);}@Overridepublic int getCount(){return names.length;}@Overridepublic Object getItem(int position){return names[position];}@Overridepublic long getItemId(int position){return 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent){if(convertView==null){convertView=View.inflate(context, R.layout.grid_view_item, null);}//然后将对应数据设置到对应的位置ImageView imageView = (ImageView) convertView.findViewById(R.id.icon);TextView textView = (TextView) convertView.findViewById(R.id.name);imageView.setImageResource(icons[position]);textView.setText(names[position]);if(position==0){//从sp中读取保存的名称,如果存在就显示String saveName =sp.getString("NAME", null);if(saveName!=null){textView.setText(saveName);}}return convertView;}
}

Android的数据存储:SharedPrefrence存储,手机内部文件存储,手机外部文件存储相关推荐

  1. Android查看手机内部储存目录及数据库文件[转]

    本文转自:https://blog.csdn.net/msn465780/article/details/76813122 我们平时开发的时候会经常用到文件缓存,常用的是手机内部储存和手机外部储存,手 ...

  2. android db 代码查看工具,Android查看手机内部储存目录及数据库文件

    咱们平时开发的时候会常常用到文件缓存,经常使用的是手机内部储存和手机外部储存,手机内部存储主要包括APP安装后的一些文件,外部储存就是你们一般可使用的空间,用来存点图片电影之类的.html 当须要快速 ...

  3. 小米手机60帧录屏_手机录屏怎样只录手机内部声音不录入外部声音?教你三种方法,一定能帮到你...

    随着Android系统不断迭代升级,手机截图长截图.手机录屏都成为了每部手机的标配,现在的手机都会有这几个功能! 但是经常使用录屏功能的小伙伴可能会遇到一些问题,比如录屏录制声音时,会将周围环境中的噪 ...

  4. 手机录屏怎样只录手机内部声音不录入外部声音?教你三种方法,一定能帮到你

    随着Android系统不断迭代升级,手机截图长截图.手机录屏都成为了每部手机的标配,现在的手机都会有这几个功能! 但是经常使用录屏功能的小伙伴可能会遇到一些问题,比如录屏录制声音时,会将周围环境中的噪 ...

  5. Android之获取手机内部及sdcard存储空间

    Android之获取手机内部及sdcard存储空间 文章链接 知识点: 内部存储空间获取总大小和可用大小: sdcard存储空间获取总大小和可用大小: 新名词记录{StatFs:描述文件系统信息的类} ...

  6. Android 11 从沙盒拷贝文件到外部共享存储区域

    本文是 Android 11 从外部存储读取文件到应用沙盒存储   的兄弟篇 :Android 11 从沙盒拷贝文件到外部共享存储区域,效果: 1. 需求中我们需要把自己应用沙盒的文件拷贝到外部共享存 ...

  7. ProxmoxVE(V5.2) 之 使用外部ceph存储(luminous)

      上面左边是我的个人 微  信,如需进一步沟通,请加  微  信.  右边是我的公众号"Openstack私有云",如有兴趣,请关注. 继上篇博文<ProxmoxVE 之集 ...

  8. Android——数据存储(课堂代码整理:SharedPreferences存储和手机内部文件存储)...

    layout文件: 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmln ...

  9. android 获取手机SD卡和手机的内部存储

    在开发过程中有时候会获取手机的SD存储使用状况. 布局文件 <LinearLayout xmlns:android="http://schemas.android.com/apk/re ...

最新文章

  1. php关机启动不了,win10关机关不掉怎么办
  2. 修改sqlarchemy源码使其支持jdbc连接mysql
  3. 5G NGC — 关键技术 — CUPS
  4. 《职场一点诀 帆风顺,一定快乐?》读后感
  5. dotNET:怎样处理程序中的异常(实战篇)?
  6. 如何安装最新版本Pycharm2019
  7. 第六章——并行接口技术
  8. JavaScript效果之选项卡
  9. 小程序监听点击右上角按钮_朋友圈支持应用直达、公众号小程序支持行动按钮文案、原生页拉取...
  10. c语言解三元一次方程组_在R里面对三元一次方程求解
  11. Linux 命令 之 【stat】 查看文件状态。 (包括修改时间)
  12. ssh-keygen的使用方法及配置authorized_keys两台linux机器相互认证
  13. Luogu P2079 烛光晚餐(背包)
  14. Java垃圾回收机制详解(万字总结!一篇入魂!)
  15. thinkphp前台模板运算符
  16. Modelsim的tcl命令
  17. linux iptables源ip替换,Linux更改源IP地址的传入流量
  18. 直击|支付宝还信用卡下月开始收费 每月2000免费额度
  19. 小数点化分数的过程_小数怎么化成分数
  20. 我不是九爷 带了解 Unity3D与VR虚拟现实

热门文章

  1. 查分吧(chafenba)万用考试成绩查询小程序源码
  2. 银河麒麟系统设置变更
  3. 实现轮播图,仅需3步
  4. 大牛给计算机方向学生的 7 个建议
  5. js11位手机号码正则验证
  6. 十七、缓存预热、缓存雪崩、缓存击穿、缓存穿透、性能指标监控等企业级解决方案
  7. 矩阵特征值和特征向量求解——特征值分解
  8. 人工智能的三个层次:运算智能,感知智能,认知智能
  9. 5G:三大场景--- eMBB、URLLC、mMTC
  10. 【初识】初学编程,望多指教