Android应用开发——文件存储

版权声明:转载请注明出处 https://blog.csdn.net/Zach_z/article/details/80754121

代码下载地址

一、设计目的

  1. 掌握首选项方式的存储和读取
  2. 掌握位于内存上的数据文件的存储和读取
  3. 掌握位于SD卡上的数据文件的存储和读取

二、设计内容

实现基于文件存储的日程安排应用,数据文件可以保存在机身内存或者SD卡中。通过单击增加图标打开新增加活动界面,通过单击保存按钮将活动内容写入到文件中,并返回前页,点击删除图标,可以删除该活动。

三、软硬件环境及系统所采用的体系结构

开发环境:Android Studio
模拟运行:Android Emulator – Nexus_5X_API_24

四、实现过程及结果

4.1 修改主布局如下所示:

<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="已安排的活动"
        android:background="#777"
        android:textColor="#ddd"
        android:textSize="16pt"
        android:gravity="center" />
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_alignLeft="@+id/title">
    </ListView>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:cropToPadding="false"
        android:onClick="add"
        android:src="@mipmap/add" />

</RelativeLayout>

完成后的界面如图所示:

这里写图片描述

4.2 1. 修改主Activity文件,通过getList()方法从文件itme_me中读取数据显示到ListView组件中。单击新增打开增加活动界面,新增活动界面关闭返回时在onActivityResult()方法中再次调用getItemList()方法获取最新数据并显示:

public class MainActivity extends AppCompatActivity {
    private ListView itemList;
    private void getItemList() throws IOException {
        ArrayList<String> list = new ArrayList<String>();
        try {
            FileInputStream in = openFileInput("item_me");
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
            br.close();
            in.close();
            String[] contents = {};
            String[] allItem = list.toArray(contents);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,allItem);
            itemList.setAdapter(adapter);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        itemList = (ListView) findViewById(R.id.listView);
        try {
            getItemList();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
        }
    }
    public void add(View view){
        Intent intent = new Intent(MainActivity.this,AddItemActivity.class);
        startActivityForResult(intent,0x111);
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode == 0x111 && resultCode == 0x111){
            try {
                getItemList();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.3 创建增加活动界面布局文件additem.xml:

<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="新增活动"
        android:background="#777"
        android:textColor="#ddd"
        android:textSize="16pt"
        android:gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="日期"
        android:textSize="10pt"/>

    <EditText
        android:id="@+id/date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="chooseDate"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开始时间"
        android:textSize="10pt"/>

    <EditText
        android:id="@+id/startTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="chooseStartTime"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="结束时间"
        android:textSize="10pt"/>

    <EditText
        android:id="@+id/endTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="chooseEndTime"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="活动说明"
        android:textSize="10pt"/>
    <EditText
        android:id="@+id/item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="save"
        android:text="保存"
        android:layout_gravity="center"/>

</LinearLayout>

完成后的界面如图所示:

这里写图片描述

4.4 创建增加活动界面Activity文件AddItemActivity.java,输入新增活动的日期、开始时间、结束时间、活动名称,保存到文件item_me中:

public class AddItemActivity extends AppCompatActivity {
    private EditText date,startTime,endTime,item;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.additem);
        date = (EditText) findViewById(R.id.date);
        startTime = (EditText) findViewById(R.id.startTime);
        endTime = (EditText) findViewById(R.id.endTime);
        item = (EditText) findViewById(R.id.item);
    }
    public void chooseDate(View view){
        DatePickerDialog datepd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker dp, int year, int month, int day) {
                date.setText(year + "-" + (month+1)+"-"+day);
            }
        },2018,5,20);
        datepd.setMessage("请选择日期");
        datepd.show();
    }
    public void chooseStartTime(View view){
        TimePickerDialog timepd = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                startTime.setText(hourOfDay + ":" + minute);
            }
        },10,0,true);
        timepd.setMessage("请选择开始时间");
        timepd.show();
    }
    public void chooseEndTime(View view){
        TimePickerDialog timepd = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                endTime.setText(hourOfDay + ":" + minute);
            }
        },12,0,true);
        timepd.setMessage("请选择结束时间");
        timepd.show();
    }
    public void save(View view){
        StringBuilder result = new StringBuilder();
        result.append(date.getText().toString()+" ");
        result.append(startTime.getText().toString()+"-");
        result.append(endTime.getText().toString()+" ");
        result.append(item.getText().toString());
        try{
            FileOutputStream out = openFileOutput("item_me",MODE_APPEND);
            PrintStream ps = new PrintStream(out);
            ps.println(result.toString());
            ps.close();
            out.close();
            Toast.makeText(this,"保存完毕!",Toast.LENGTH_LONG).show();
            Intent intent = getIntent();
            setResult(0x111,intent);
            finish();
        }
        catch (Exception e){
            e.printStackTrace();
        }
      }
   }

在新增活动页面填写日期、开始时间、结束时间和活动说明:

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

点击保存后返回主Activity,退出应用再进来都可以看到:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/Zach_z/article/details/80754121