简体   繁体   English

getFileDir()导致NullPointer异常

[英]getFileDir() cause NullPointer exception

I'm in my early days of learning Java but hopefully someone get explain what I'm doing wrong here, numerous Google searches have left my head spinning. 我在学习Java的早期阶段,但希望有人能够解释我在这里做错了什么,许多谷歌搜索让我头疼。

I've been following a tutorial which shows how to save an ArrayList to a text file and then get the details back. 我一直在学习如何将ArrayList保存到文本文件然后获取详细信息的教程。

I am getting the following error:- 我收到以下错误: -

01-10 19:00:37.092 16897-16897/uk.co.c2digital.futurefoto E/AndroidRuntime: FATAL EXCEPTION: main
Process: uk.co.c2digital.futurefoto, PID: 16897
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{uk.co.c2digital.futurefoto/uk.co.c2digital.futurefoto.viewLocations}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2322)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:201)
at uk.co.c2digital.futurefoto.fileControl.<init>(fileControl.java:23)
at uk.co.c2digital.futurefoto.viewLocations.<init>(viewLocations.java:18)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1083)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:155) 
at android.app.ActivityThread.main(ActivityThread.java:5696) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 
01-10 19:05:37.142 16897-16897/uk.co.c2digital.futurefoto D/Process: killProcess, pid=16897
01-10 19:05:37.162 16897-16897/uk.co.c2digital.futurefoto D/Process: com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690 

This is being caused when my file viewLocations.java runs the following (after imports etc) 这是在我的文件viewLocations.java运行以下(导入等之后)时引起的

 public class viewLocations extends AppCompatActivity {

    fileControl filer = new fileControl();
    ArrayList imgArray = filer.getSaved();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_locations);

      }

FileControl(); FileControl(); is located in a seperate file called 'fileControl.java' 位于一个名为'fileControl.java'的独立文件中

public class fileControl extends AppCompatActivity {


    // Set filename
    String filename = getFilesDir() + "/savedList.txt";

    /**
     * Following code gets a list of saved image paths from device
     * @return

     */


    public ArrayList getSaved() {


        // Create variable for storing each line as it's read
        String line;

        // Clear imgArray ready for new entries
        ArrayList newList = new ArrayList();
        newList.clear(); // ensure new array is clear before continuing

        // Try to open file
        try {
            BufferedReader input = new BufferedReader(new FileReader(filename));
            if (!input.ready()) {
                // If input file is not ready, show log error
                Log.d("getSavedList", "Unable to open save file, input not ready");
            } else {

                // If input file is ready, read each line one at a time and add to array
                while ((line = input.readLine()) != null) {
                    newList.add(line);
                }
                input.close();

                // Run verification on results to ensure no duplicates or deleted images are recorded
                newList = listVerify(newList);

            }
        } catch (IOException e) {
            Log.d("getSavedList", "Read save file failed: " + e);
        }

        return newList;
    }

There's a bunch of stuff wrong here. 这里有一堆错误。 First of all, Activity classes, or in your case AppCompatActivity classes are generally for presenting screens with UI, not performing discreet tasks. 首先, Activity类,或者在你的情况下, AppCompatActivity类通常用于呈现带有UI的屏幕,而不是执行谨慎的任务。 Your getSaved() function should probably just reside in whichever Activity actually houses your UI. 你的getSaved()函数可能只是驻留在你的UI实际存在的Activity中。

Second, AppCompatActivity classes can't perform context actions statically. 其次, AppCompatActivity类无法静态执行上下文操作。 In other words, your Activity needs to be instantiated before you can use its super class methods, in this case getFilesDir() . 换句话说,在使用超类方法之前,需要先实例化Activity,在本例中为getFilesDir()

What that boils down to is that you need to initialize filename in a lifecycle function, probably onCreate() 归结为你需要在生命周期函数中初始化filename ,可能是onCreate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM