我刚刚开始学习Android Studio,并且已经开始使用基本笔记应用程序了一段时间。我已经在主片段中添加了加载/保存方法。但是,当我第一次启动应用程序时,它会崩溃。如果我删除加载方法并启动应用程序,那么应用程序可以按我的意在我再次添加加载方法并第二次启动应用程序后,应用程序也没有问题。所以我假设我的加载代码存在问题,因为当我第一次启动时它会导致应用程序崩溃。您可以找到第一个屏幕的主要片段代码,以及我在下面的Android Studio中收到的错误。如果你能帮助我解决这个问题,我会非常感激。
MainProjectList.java片段:
public class MainProjectLister extends ListFragment implements
AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener {
Button addProjectButton;
EditText addProjectEditText;
public String projectTitle;
Projekt newProjekt;
ProjektSingleton projektSingleton;
ArrayList<Projekt> projektArrayList;
ArrayAdapter<String> adapter;
ArrayList<Projekt> tempProjektArrayList;
ArrayList<String> ListOfP;
private final String FILENAME="testfile15.txt";
private final String FILENAME2="testfile16.txt";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListOfP = new ArrayList<String>();
projektSingleton = ProjektSingleton.getInstance();
projektSingleton.setProjektList(getSavedArrayList());
ListOfP = getSavedStringList();
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.main_project_lister_layout, container, false);
addProjectButton = (Button) view.findViewById(R.id.addProjectButton);
addProjectEditText = (EditText) view.findViewById(R.id.addProjectEditText);
//addProjectButton onClck method
addProjectButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
//Checking if nothing is entered in the EditText and gives Error messaga
if(TextUtils.isEmpty(addProjectEditText.getText().toString().trim())){
Toast.makeText(getActivity(), "Please type details", Toast.LENGTH_SHORT).show();
return;
}
projectTitle = addProjectEditText.getText().toString();
newProjekt = new Projekt(projectTitle);
projektArrayList = projektSingleton.getProjectList();
projektArrayList.add(newProjekt);
ListOfP.add(projectTitle);
adapter.notifyDataSetChanged();
saveArrayList(projektArrayList);
saveStringList(ListOfP);
addProjectEditText.setText("");
}
});
getActivity().setTitle("DearBear Notes App");
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, ListOfP);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
getListView().setOnItemLongClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
MainProjectLister frag = new MainProjectLister();
ProjectListFragmentChanger fragInterface = (ProjectListFragmentChanger) getActivity();
fragInterface.projectListChangeFragment(frag);
projektSingleton.setProjectNumber(i);
}
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l){
projektArrayList = projektSingleton.getProjectList();
projektArrayList.remove(i);
ListOfP.remove(i);
adapter.notifyDataSetChanged();
saveArrayList(projektArrayList);
saveStringList(ListOfP);
return true;
}
//Interface
public interface ProjectListFragmentChanger{
public void projectListChangeFragment(Fragment fragment);
}
//Save File Method
public void saveArrayList(ArrayList<Projekt> arrayList) {
try {
FileOutputStream fos = getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(arrayList);
out.close();
fos.close();
} catch (IOException e) {
e.printStackTrace ();
}
}
public void saveStringList(ArrayList<String> arrayList) {
try {
FileOutputStream fos = getActivity().openFileOutput(FILENAME2, Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(arrayList);
out.close();
fos.close();
} catch (IOException e) {
e.printStackTrace ();
}
}
//Load Text File Method
public ArrayList<Projekt> getSavedArrayList() {
ArrayList<Projekt> savedArrayList = null;
try {
FileInputStream fis = getActivity().openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
savedArrayList = (ArrayList<Projekt>) ois.readObject();
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace ();
}
return savedArrayList;
}
public ArrayList<String> getSavedStringList() {
ArrayList<String> savedArrayList = null;
try {
FileInputStream fis = getActivity().openFileInput(FILENAME2);
ObjectInputStream ois = new ObjectInputStream(fis);
savedArrayList = (ArrayList<String>) ois.readObject();
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace ();
}
return savedArrayList;
}
}
错误:
$ adb shell am start -n "com.example.lenovo.projectlist/com.example.lenovo.projectlist.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 2394 on device Nexus_5_API_24 [emulator-5554]
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/System: ClassLoader referenced unknown path: /data/app/com.example.lenovo.projectlist-2/lib/x86
I/InstantRun: Instant Run Runtime started. Android package is com.example.lenovo.projectlist, real application class is null.
I/art: Debugger is no longer active
I/art: Starting a blocking GC Instrumentation
W/System: ClassLoader referenced unknown path: /data/app/com.example.lenovo.projectlist-2/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/System.err: java.io.FileNotFoundException: /data/user/0/com.example.lenovo.projectlist/files/testfile15.txt (No such file or directory)
W/System.err: at java.io.FileInputStream.open(Native Method)
W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:146)
W/System.err: at android.app.ContextImpl.openFileInput(ContextImpl.java:485)
W/System.err: at android.content.ContextWrapper.openFileInput(ContextWrapper.java:186)
W/System.err: at com.example.lenovo.projectlist.MainProjectLister.getSavedArrayList(MainProjectLister.java:189)
W/System.err: at com.example.lenovo.projectlist.MainProjectLister.onCreate(MainProjectLister.java:53)
W/System.err: at android.app.Fragment.performCreate(Fragment.java:2335)
W/System.err: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:949)
W/System.err: at android.app.BackStackRecord.setLastIn(BackStackRecord.java:857)
W/System.err: at android.app.BackStackRecord.calculateFragments(BackStackRecord.java:880)
W/System.err: at android.app.BackStackRecord.run(BackStackRecord.java:727)
W/System.err: at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
W/System.err: at android.app.FragmentController.execPendingActions(FragmentController.java:371)
W/System.err: at android.app.Activity.performStart(Activity.java:6680)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
W/System.err: at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
W/System.err: java.io.FileNotFoundException: /data/user/0/com.example.lenovo.projectlist/files/testfile16.txt (No such file or directory)
W/System.err: at java.io.FileInputStream.open(Native Method)
W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:146)
W/System.err: at android.app.ContextImpl.openFileInput(ContextImpl.java:485)
W/System.err: at android.content.ContextWrapper.openFileInput(ContextWrapper.java:186)
W/System.err: at com.example.lenovo.projectlist.MainProjectLister.getSavedStringList(MainProjectLister.java:208)
W/System.err: at com.example.lenovo.projectlist.MainProjectLister.onCreate(MainProjectLister.java:54)
W/System.err: at android.app.Fragment.performCreate(Fragment.java:2335)
W/System.err: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:949)
W/System.err: at android.app.BackStackRecord.setLastIn(BackStackRecord.java:857)
W/System.err: at android.app.BackStackRecord.calculateFragments(BackStackRecord.java:880)
W/System.err: at android.app.BackStackRecord.run(BackStackRecord.java:727)
W/System.err: at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
W/System.err: at android.app.FragmentController.execPendingActions(FragmentController.java:371)
W/System.err: at android.app.Activity.performStart(Activity.java:6680)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
W/System.err: at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
D/AndroidRuntime: Shutting down VM
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lenovo.projectlist, PID: 2394
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo.projectlist/com.example.lenovo.projectlist.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
at android.widget.ListView.setAdapter(ListView.java:493)
at android.app.ListFragment.setListAdapter(ListFragment.java:240)
at com.example.lenovo.projectlist.MainProjectLister.onActivityCreated(MainProjectLister.java:111)
at android.app.Fragment.performActivityCreated(Fragment.java:2361)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1014)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:815)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentController.execPendingActions(FragmentController.java:371)
at android.app.Activity.performStart(Activity.java:6680)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
答案 0 :(得分:1)
发生第一个错误是因为您在尚未创建的文件上调用openFileInput()
。但是,由于您捕获到该错误,getSavedArrayList()
会返回null
并将其分配给ListOfP
,从而在尝试为ArrayAdapter指定null时导致NullPointerException。
为了防止这种情况,您应该先检查文件是否存在,并将列表分配给空文件以防止这两个错误;像这样:
public ArrayList<Projekt> getSavedArrayList() {
ArrayList<Projekt> savedArrayList = null;
try {
// get the file and check if it exists before trying to read it
File savedFile = new File(getActivity().getFilesDir(), FILENAME);
if (savedFile.exists()) {
// if the file containing the list exists, read it and return the list
FileInputStream fis = getActivity().openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
savedArrayList = (ArrayList<Projekt>) ois.readObject();
ois.close();
fis.close();
} else {
// if it doesn't exist, return an empty list
savedArrayList = new ArrayList<>();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace ();
}
return savedArrayList;
}