(六)数据存储与访问

本文详细介绍了Android中的数据存储方式,包括SharedPreferences的文件位置和格式,内部存储器上的文件读写,资源文件的访问,以及SQLite数据库的操作。通过实验步骤展示了如何在Android Studio中创建相关工程,并分析了各种存储方式的适用场景和优缺点。
摘要由CSDN通过智能技术生成

一、实验内容

  1. 通过SimplePreferenceDemo说明SharedPreferences的文件保存位置和保存格式。
  2. 通过InternalFileDemo程序实现在内部存储器上进行文件写入和读取。
  3. 通过ResourceFileDemo程序实现如何在程序运行时访问资源文件。
  4. 通过SQLiteDemo来实现对数据库操作的一个示例。

二、实验仪器、设备

硬件:PC 微型计算机、1G以上内存,40G以上硬盘
软件:Windows XP,Eclipse , JDK , Android SDK

三、实验步骤

1.通过SimplePreferenceDemo说明SharedPreferences的文件保存位置和保存格式。
1) 创建SimplePreferenceDemo工程
打开Android Studio,点击Start a new Android Studio project;
勾选Phone and Tablet,点击next;
勾选Empty Activity,点击next;
在Activity Name中填写SimplePreferenceDemo,在Layout Name中添加main,点击finish。
2)程序代码:
MainActivity.java:

package com.example.simplepreferencedemo;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
   

    private EditText nameText;
    private EditText ageText;
    private EditText heightText;

    public static final String PREFERENCE_NAME="SaveSetting";
    public static int MODE= Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nameText=(EditText)findViewById(R.id.name);
        ageText=(EditText)findViewById(R.id.age);
        heightText=(EditText)findViewById(R.id.height);
    }

    @Override
    protected void onStart() {
   
        super.onStart();
        loadSharedPreferences();
    }

    @Override
    protected void onStop() {
   
        super.onStop();
        saveSharedPreferences();
    }

    private void loadSharedPreferences(){
   
        SharedPreferences sharedPreferences=getSharedPreferences(PREFERENCE_NAME,MODE);
        String name=sharedPreferences.getString("Name","Tom");
        int age=sharedPreferences.getInt("Age",20);
        float height=sharedPreferences.getFloat("Height",1.81f);

        nameText.setText(name);
        ageText.setText(String.valueOf(age));
        heightText.setText(String.valueOf(height));
    }

    private void saveSharedPreferences(){
   
        SharedPreferences sharedPreferences=getSharedPreferences(PREFERENCE_NAME,MODE);
        SharedPreferences.Editor editor=sharedPreferences.edit();

        editor.putString("Name",nameText.getText().toString());
        editor.putInt("Age",Integer.parseInt(ageText.getText().toString()));
        editor.putFloat("Height",Float.parseFloat(heightText.getText().toString()));
        editor.commit();
    }
}

Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/name"
        android:text=""
        android:layout_width="280dip"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dip"/>

    <TextView
        android:id="@+id/name_label"
        android:text="姓名:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toRightOf="@+id/name"
        android:layout_alignBaseline="@+id/name"/>

    <EditText
        android:id="@+id/age"
        android:text=""
        android:layout_width="280dip"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dip"
        android:layout_below="@id/name"
        android:numeric="integer"/>

    <TextView
        android:id="@+id/age_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toRightOf="@id/age"
        android:layout_alignBaseline="@id/age"
        android:text="年龄:"/>

    <EditText
        android:id="@+id/height"
        android:layout_width="280dip"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dip"
        android:layout_below="@id/age"
        android:numeric="decimal"/>

    <TextView
        android:id="@+id/height_label"
        android:text="身高"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toRightOf="@id/height"
        android:layout_alignBaseline="@id/height"/>
</RelativeLayout>

AndroidMainfest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.simplepreferencedemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Strings.xml:

<resources>
    <string name="app_name">SimplePreferenceDemo_liurui_164573</string>
</resources>

1)运行结果分析
在这里插入图片描述
打开软件时,输入信息,关闭软件,当再次打开软件的时候信息从手机文件/data/data/<包名>中读出来,显示到用户界面。
2.通过InternalFileDemo程序实现在内部存储器上进行文件写入和读取。
1)创建InternalFileDemo工程
打开Android Studio,点击Start a new Android Studio project;
勾选Phone and Tablet,点击next;
勾选Empty Activity,点击next;
在Activity Name中填写InternalFileDemo,在Layout Name中添加main,点击finish。
2)程序代码:
MainActivity.java:

package com.example.internalfiledemo;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;


public class MainActivity extends AppCompatActivity {
   

    private final String FILE_NAME="fileDemo.txt";
    private TextView labelView;
    private TextView displayView;
    private CheckBox appendBox;
    private EditText entryText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        labelView=(TextView)findViewById(R.id.label);
        displayView=(TextView)findViewById(R.id.display);
        appendBox=(CheckBox)findViewById(R.id.append);
        entryText=(EditText)findViewById(R.id.entry);
        Button writeButon=(Button)findViewById(R.id.write);
        Button readButton=(Button)findViewById(R.id.read);

        writeButon.setOnClickListener(writeButtonListener);
        readButton.setOnClickListener(readButtonListener);

        entryText.selectAll();
        entryText.findFocus();
    }
    View.OnClickListener writeButtonListener =new View.OnClickListener(){
   
        @Override
        public void onClick(View v) {
   
            FileOutputStream fos=null;
            try {
   
                if (appendBox.isChecked()){
   
                    fos=openFileOutput(FILE_NAME, Context.MODE_APPEND);
                }else {
   
                    fos=openFileOutput(FILE_NAME,Context.MODE_PRIVATE);
                }
                String text=entryText.getText().toString();
                fos.write(text.getBytes());
                labelView.setText("文件写入成功,写入长度:"+text.length());
                entryText.setText("");
            }catch (FileNotFoundException e){
   
                e.printStackTrace();
            } catch (IOException e) {
   
                e.printStackTrace();
            }
            finally {
   
                if (fos!=null){
   
                    try {
   
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
   
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    View.OnClickListener readButtonListener=new View.OnClickListener() {
   
        @Override
        public void onClick(View v) {
   
            displayView.setText("");
            FileInputStream fis=null;
            try {
   
                fis=openFileInput(FILE_NAME);
                if (fis.available()==0){
   
                    return;
                }
                byte[] readBytes=new byte[fis.available()];
                while (fis.read(readBytes)!=-1){
   

                }
                String text=new String(readBytes);
                displayView.
  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值