【发布时间】:2014-01-25 17:26:10
【问题描述】:
我想请这里的人帮助我解决一个似乎有一个非常简单的解决方案的问题,然而,应用程序在模拟器中一次又一次地崩溃。
运动-
创建一个包含三个活动的应用程序:
1. (主要)第一个活动包括两个按钮,点击每个按钮
经营其他活动之一。
2。第二个活动允许您输入客户信息:
客户姓名,男/女,年龄
并包含一个要添加的按钮 - 单击它会将客户添加到 ArrayList。
当您退出活动时 - 您需要将所有客户 ArrayList 添加到文件中。
3。第三个活动,允许用户查看现有客户总数 -> 从文件中读取的数据。
实现 Serializable 的“客户”类, “Main” Activity 和“ViewCustomers” Activity 都非常容易编写。 “AddCustomer”活动导致应用程序崩溃。 请根据以下(烦人的)第二个活动的代码告诉我为什么应用程序反复崩溃:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import java.io.*;
import java.util.ArrayList;
public class AddCustomerActivity extends Activity {
static final String CUSTOMERSFILE="customers";
ArrayList<Customer> customers;
EditText name, age;
CheckBox male;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcustomerscreen);
name=(EditText)findViewById(R.id.nameText);
age=(EditText)findViewById(R.id.ageText);
male=(CheckBox)findViewById(R.id.maleCheckBox);
Button add=(Button)findViewById(R.id.addcustomerbutton);
FileInputStream fis;
ObjectInputStream ois=null;
try {
fis=openFileInput(CUSTOMERSFILE);
ois=new ObjectInputStream(fis);
customers=(ArrayList<Customer>)ois.readObject();
if(customers==null)
customers=new ArrayList<Customer>();
}
catch(ClassNotFoundException ex)
{
Log.e("add customers","serialization problem",ex);
}
catch(IOException ex)
{
Log.e("add customers","No customers file",ex);
customers=new ArrayList<Customer>();
}
finally
{
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String theName=name.getText().toString();
int theAge=Integer.parseInt(age.getText().toString());
boolean isMale=male.isChecked();
customers.add(new Customer(theName, theAge, isMale));
name.setText("");
age.setText("");
}
});
}
@Override
protected void onPause() {
super.onPause();
FileOutputStream fos;
ObjectOutputStream ous=null;
try {
fos=openFileOutput(CUSTOMERSFILE, Activity.MODE_PRIVATE);
ous=new ObjectOutputStream(fos);
ous.writeObject(customers);
}
catch(IOException ex)
{
Log.e("add customers","some problem",ex);
}
finally
{
try {
ous.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
附: “OnPause”中的代码应该在内部存储中创建文件 并使代码工作,至少在第二次运行时,但它没有。
- U P D A T E(由于对 LogCat 的请求)
那些是日志,
虽然第一条红色\错误线出现在按钮按下时,假设会导致(通过明确的意图)
从“ManuActivity”到“AddCustomerActivity”,
但随后应用程序崩溃了。
“AddCustomerActivity”开头显示的错误日志的链接:
【问题讨论】:
-
你能发布你得到的 logcat 吗?
-
当然,我刚刚做到了。谢谢。
-
您发布的图片不包含导致崩溃的错误。您可以在该图像的末尾找到该错误(“未捕获的处理程序:线程主退出...”)您可以发布该错误的 logcat 吗?
标签: android arraylist fileinputstream objectinputstream internal-storage