Java 编写arrayList<;类别>;归档
我是android应用程序开发新手,我曾尝试将arrayList写入文件,但在代码中尝试这样做时遇到了问题:Java 编写arrayList<;类别>;归档,java,android,file-io,arraylist,Java,Android,File Io,Arraylist,我是android应用程序开发新手,我曾尝试将arrayList写入文件,但在代码中尝试这样做时遇到了问题: public class AddActivity extends Activity implements Serializable { /** * */ private static final long serialVersionUID = 1L; public transient Context ctx; private final String filename = "Ac
public class AddActivity extends Activity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public transient Context ctx;
private final String filename = "Accounts";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
final EditText name = (EditText) findViewById(R.id.name);
final EditText username = (EditText) findViewById(R.id.username);
final EditText password = (EditText) findViewById(R.id.password);
final EditText type = (EditText) findViewById(R.id.type);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(View arg0) {
String n = name.getText().toString();
String u = username.getText().toString();
String p = password.getText().toString();
String t = type.getText().toString();
Account newAccount = new Account (n, u , p, t);
ArrayList<Account> accounts;
String filePath = getFilesDir().getPath().toString() + "/" + filename;
File fl = new File(filePath);
try {
if (fl.exists()){
FileInputStream fis = ctx.openFileInput(filename);
ObjectInputStream oi = new ObjectInputStream(fis);
accounts = (ArrayList<Account>) oi.readObject();
accounts.add(newAccount);
oi.close();
fis.close();
fl.delete();
}else{
accounts = new ArrayList<Account>();
accounts.add(newAccount);
}
fl.createNewFile();
FileOutputStream fos = (openFileOutput(filename, Context.MODE_PRIVATE));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(accounts);
oos.flush();
oos.close();
fos.close();
} catch (IOException e) {
Log.e("InternalStorage", e.getMessage());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
}
每次单击“添加”按钮,我都会收到一个错误,上面写着“很遗憾,(应用程序名称)已停止”。请帮忙。谢谢。我想您也可以尝试以下代码将列表写入文件:
File myfile = getFileStreamPath(FileName);
try {
if (myfile.exists() || myfile.createNewFile()) {
FileOutputStream fos = openFileOutput(FileName, MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(masterlistrev);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
logcat中对此异常的描述是什么?请发布堆栈跟踪如果应用程序崩溃,这意味着您有一个堆栈跟踪。请用你的问题贴出来,不要让我们猜测错误是什么。第56行的NPE是哪一个?
File myfile = getFileStreamPath(FileName);
try {
if (myfile.exists() || myfile.createNewFile()) {
FileOutputStream fos = openFileOutput(FileName, MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(masterlistrev);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}