前回はファイルに対してテキストの書き込みを行ったが、オブジェクトを直接書き込むこともできる。今回はまずその方法を学ぼう。
●ステップ1
ファイルに書き込みたいクラスにSerializableインターフェイスを実装する。
import java.io.Serializable; |
public class Word implements Serializable { |
public Word(String word, String body) { |
public String toString() { |
return "word:" + word + " body:" + body; |
●ステップ2
読み込みはfisをObjectInputStreamで包み、readObject()
書き込みはfosをObjectOutputStreamで包み,writeObject(Object)
詳しくは以下のソースコードを参照せよ。
以下のソースコードではWordクラスのインスタンスをファイルに書き込み、その書き込まれたファイルから復元する手順を示している。
import android.os.Bundle; |
import android.support.v7.app.AppCompatActivity; |
import android.widget.Toast; |
import java.io.FileInputStream; |
import java.io.FileNotFoundException; |
import java.io.FileOutputStream; |
import java.io.IOException; |
import java.io.ObjectInputStream; |
import java.io.ObjectOutputStream; |
public class MainActivity extends AppCompatActivity { |
protected void onCreate(Bundle savedInstanceState) { |
super .onCreate(savedInstanceState); |
ObjectInputStream ois= null ; |
ObjectOutputStream oos= null ; |
FileOutputStream fos=openFileOutput( "data.dat" ,MODE_PRIVATE); |
oos= new ObjectOutputStream(fos); |
oos.writeObject( new Word( "word1" , "body1" )); |
FileInputStream fis=openFileInput( "data.dat" ); |
ois= new ObjectInputStream(fis); |
Word w=(Word)ois.readObject(); |
Toast.makeText( this ,w.toString(),Toast.LENGTH_SHORT).show(); |
} catch (FileNotFoundException e) { |
} catch (IOException e) { |
} catch (ClassNotFoundException e) { |
if (ois != null ){ois.close();} |
if (oos != null ){oos.close();} |
オブジェクトのファイルへ書き込み方法がわかったところで前回のお題をListを直接ファイルに書く方法で実現してみよう。StringクラスもArrayListクラスもSerializableインターフェイスを実装しているので特別な処理をせずに上記の方法で読み書きできる。
Q1
登録されているデータ(List)をファイルに書き込み、次回起動時に復元させよ。
なお、今回はObjectOutputStreamクラスとObjectInputStreamクラスを使ってオブジェクトを直接ファイルに記録すること。
書き込み処理は
アプリがバックグランドにまわる際のonPauseをオーバーライドしてそこに書くとよい。
[実行例]
スタート画面
リストアイテムを登録するフォームとボタンがある。

フォームに入力し登録ボタンを押すと・・・

フォーム下部にあるリストビューに表示される。

いくつか登録する。

リストアイテム長押しでアイテムを削除できる。
下図はitem2を削除した。

バックボタンを押してアプリを終了する。

アプリ一覧からアプリを再起動する。

データが復元されていることが確認できる。

●activity_main.xml
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
02 | < android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
03 | xmlns:app = "http://schemas.android.com/apk/res-auto" |
04 | android:layout_width = "match_parent" |
05 | android:layout_height = "match_parent" |
10 | android:layout_width = "0dp" |
11 | android:layout_height = "0dp" |
12 | android:layout_marginLeft = "8dp" |
13 | android:layout_marginRight = "8dp" |
14 | android:layout_marginTop = "8dp" |
15 | app:layout_constraintLeft_toLeftOf = "parent" |
16 | app:layout_constraintRight_toRightOf = "parent" |
17 | app:layout_constraintTop_toBottomOf = "@+id/etItem" |
18 | app:layout_constraintBottom_toBottomOf = "parent" |
19 | android:layout_marginBottom = "8dp" /> |
22 | android:id = "@+id/textView" |
23 | android:layout_width = "wrap_content" |
24 | android:layout_height = "wrap_content" |
26 | android:layout_marginLeft = "8dp" |
27 | app:layout_constraintLeft_toLeftOf = "parent" |
28 | app:layout_constraintBaseline_toBaselineOf = "@+id/etItem" /> |
31 | android:id = "@+id/etItem" |
32 | android:layout_width = "0dp" |
33 | android:layout_height = "wrap_content" |
34 | android:layout_marginLeft = "8dp" |
35 | android:layout_marginTop = "8dp" |
37 | android:inputType = "textPersonName" |
38 | app:layout_constraintLeft_toRightOf = "@+id/textView" |
39 | app:layout_constraintTop_toTopOf = "parent" /> |
42 | android:id = "@+id/button" |
43 | android:layout_width = "wrap_content" |
44 | android:layout_height = "wrap_content" |
45 | android:layout_marginLeft = "8dp" |
46 | android:layout_marginRight = "8dp" |
47 | android:layout_marginTop = "8dp" |
48 | android:onClick = "btClick" |
50 | app:layout_constraintLeft_toRightOf = "@+id/etItem" |
51 | app:layout_constraintRight_toRightOf = "parent" |
52 | app:layout_constraintTop_toTopOf = "parent" /> |
53 | </ android.support.constraint.ConstraintLayout > |
●MainActivity.java
001 | package com.example.mjpurin.filesaveobject; |
003 | import android.os.Bundle; |
004 | import android.support.v7.app.AppCompatActivity; |
005 | import android.view.View; |
006 | import android.widget.AdapterView; |
007 | import android.widget.ArrayAdapter; |
008 | import android.widget.EditText; |
009 | import android.widget.ListView; |
010 | import android.widget.Toast; |
012 | import java.io.FileInputStream; |
013 | import java.io.FileNotFoundException; |
014 | import java.io.FileOutputStream; |
015 | import java.io.IOException; |
016 | import java.io.ObjectInputStream; |
017 | import java.io.ObjectOutputStream; |
018 | import java.util.ArrayList; |
019 | import java.util.List; |
021 | public class MainActivity extends AppCompatActivity { |
023 | private EditText etItem; |
024 | private List<String> list= new ArrayList<>(); |
025 | private ArrayAdapter<String> adapter; |
027 | protected void onCreate(Bundle savedInstanceState) { |
028 | super .onCreate(savedInstanceState); |
029 | setContentView(R.layout.activity_main); |
031 | Object ret=readFile(); |
033 | list=(List<String>)ret; |
035 | lv=(ListView)findViewById(R.id.lv); |
036 | etItem=(EditText)findViewById(R.id.etItem); |
037 | adapter= new ArrayAdapter<>( this ,android.R.layout.simple_list_item_1,list); |
038 | lv.setAdapter(adapter); |
039 | lv.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() { |
041 | public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { |
042 | list.remove(position); |
043 | adapter.notifyDataSetChanged(); |
044 | Toast.makeText(MainActivity. this , "削除しました。" ,Toast.LENGTH_SHORT).show(); |
050 | public void btClick(View v){ |
051 | String item=etItem.getText().toString(); |
053 | adapter.notifyDataSetChanged(); |
057 | private Object readFile() { |
061 | ObjectInputStream ois= null ; |
064 | FileInputStream fis=openFileInput( "data.dat" ); |
066 | ois= new ObjectInputStream(fis); |
068 | ret=ois.readObject(); |
070 | } catch (FileNotFoundException e) { |
072 | } catch (IOException e) { |
074 | } catch (ClassNotFoundException e) { |
080 | } catch (IOException e) { |
090 | protected void onPause() { |
093 | ObjectOutputStream oos= null ; |
096 | FileOutputStream fos=openFileOutput( "data.dat" ,MODE_PRIVATE); |
098 | oos= new ObjectOutputStream(fos); |
101 | oos.writeObject(list); |
103 | } catch (FileNotFoundException e) { |
105 | } catch (IOException e) { |
111 | } catch (IOException e) { |
コメント