我是序列化的新手,并试图在我的应用程序中保存一个 ArrayList。我找到了一些教程并尝试将它们放入我的应用程序中。事实证明文件没有保存,我不知道发生了什么(logcat 中没有错误)。
这是我的Java:
package com.frostbytedev.randomgenie;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Steven on 6/11/13.
*/
public class NewList extends Activity implements View.OnClickListener{
String ListName;
String ItemText;
int i = 0;
List<EditText> List = new ArrayList<EditText>();
Button save;
EditText FileName, etItem1, etItem2, etItem3, etItem4, etItem5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newlist);
initilize();
}
private void IndexList() {
List.add(FileName);
List.add(etItem1);
List.add(etItem2);
List.add(etItem3);
List.add(etItem4);
List.add(etItem5);
for(i=1;i<5;i++){
ItemText = List.get(i).getText().toString();
if(ItemText.contentEquals("")){
List.remove(List.get(i));
}
}
}
private void initilize() {
save = (Button)findViewById(R.id.bSave);
FileName = (EditText)findViewById(R.id.etFileName);
etItem1 = (EditText)findViewById(R.id.etItem1);
etItem2 = (EditText)findViewById(R.id.etItem2);
etItem3 = (EditText)findViewById(R.id.etItem3);
etItem4 = (EditText)findViewById(R.id.etItem4);
etItem5 = (EditText)findViewById(R.id.etItem5);
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.bSave:
IndexList();
try {
SaveList();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void SaveList() throws IOException {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(FileName.getText().toString()+".dat");
out = new ObjectOutputStream(fos);
out.writeObject(List);
FileName.setText("Its worked!");
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}