Android学习笔记(基础)之数据存储(一)

来源:互联网 发布:自动记录运动轨迹软件 编辑:程序博客网 时间:2024/05/23 21:08
<span style="color: rgb(56, 56, 56); font-family: gotham, helvetica, arial, sans-serif; font-size: 18px; line-height: 28.2857036590576px;">SharePreferences</span>
        SharePreferences是一种轻型的数据存储方式,它的本质是基于XML文件存储Key-Value键值对数据,通常用来存储应用的配置信息。其存储位置/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。
         SharedPreferences对象与SQLite数据库相比,免去了创建数据库,创建表,写SQL语句等操作,更加易用。但是SharedPreferences仅支持一下数据类型:
             boolean
             int
             float
             long
             String

       但是无法进行条件查询等,所以不论SharedPreferences的数据存储操作是多么简单,它也只能是存储方式的一种补充。无法完全替代SQLite等其他数据存储方式。

  要操作SharedPreferences首先要在类中获取当前Activity对应的SharedPreferences。
           SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);

为了更好地处理图形界面,Android提供了新的API——PreferenceActivity类

在PreferenceActivity中我常见的有三种方法:
       checkboxPreference
       listPreference
       edittextPreference
内部存储

内部存储文件存储程序内部数据,其他程序不可见。一般处于data/data/XXXX/files 中。安卓还为我们提供了一个简便方法 openFileOutput()来读写应用在内部存储空间上的文件。
public class MainActivity extends Activity {private EditText edit1;private Button btn1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);edit1 = (EditText) findViewById(R.id.edit1);btn1 = (Button) findViewById(R.id.btn1);readSaveText();btn1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {saveCurrentText();}});}private void readSaveText(){//读取try {InputStream is = openFileInput("data");byte[] bytes = new byte[is.available()];is.read(bytes);is.close();String str = new String(bytes,"utf-8");edit1.setText(str);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} }private void saveCurrentText(){      try {OutputStream os = openFileOutput("data", Context.MODE_PRIVATE);os.write(edit1.getText().toString().getBytes("utf-8"));//写入到缓冲区os.flush();//写出到文件os.close();//关闭Toast.makeText(this, "保存成功", Toast.LENGTH_LONG).show();return;} catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}Toast.makeText(this, "保存失败", Toast.LENGTH_LONG).show();}}

外部存储
即读取或写入手机SD卡数据。首先在Manifast.xml文件内添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在主类中使用.getExternalStorageDirectory()方法。
示例代码:
public class MainActivity extends Activity { private EditText et; private TextView show; File sdcard = Environment.getExternalStorageDirectory();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et = (EditText) findViewById(R.id.editText1);show = (TextView) findViewById(R.id.show);findViewById(R.id.btnWrite).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {File myfile = new File(sdcard, "This is my file.txt");if(!sdcard.exists()){Toast.makeText(getApplicationContext(), "当前系统不具备SD卡目录", Toast.LENGTH_SHORT).show();return;}try {myfile.createNewFile();Toast.makeText(getApplicationContext(), "文件已创建完成", Toast.LENGTH_SHORT).show();FileOutputStream fos = new FileOutputStream(myfile);OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");osw.write(et.getText().toString());osw.flush();osw.close();fos.close();Toast.makeText(getApplicationContext(), "文件已写入完成", Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();}}});findViewById(R.id.btnRead).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {File myfile = new File(sdcard, "This is my file.txt");if (myfile.exists()) {try {FileInputStream fis = new FileInputStream(myfile);InputStreamReader isr = new InputStreamReader(fis, "UTF-8");    char[] input = new char[fis.available()];    isr.read(input);    isr.close();    fis.close();    String inString = new String(input);    show.setText(inString);    } catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}});}}


0 0