-4

I have a big problem in this project. In this project, I want to read a db data become to a SQLite.

But there was also an Error happened.

I put the db data(last.db) in src→main→assets folder.

Process: net.macdidi.lasttest, PID: 4829
              java.lang.ExceptionInInitializerError
                  at net.macdidi.lasttest.MainActivity.onCreate(MainActivity.java:20)
                  at android.app.Activity.performCreate(Activity.java:6262)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2458)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2565)
                  at android.app.ActivityThread.access$900(ActivityThread.java:150)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:168)
                  at android.app.ActivityThread.main(ActivityThread.java:5821)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
                  at net.macdidi.lasttest.DatabaseHelper.<clinit>(SQLiteOpenHelper.java:18)
                  at net.macdidi.lasttest.MainActivity.onCreate(MainActivity.java:20) 
                  at android.app.Activity.performCreate(Activity.java:6262) 
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125) 
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2458) 
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2565) 
                  at android.app.ActivityThread.access$900(ActivityThread.java:150) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:168) 
                  at android.app.ActivityThread.main(ActivityThread.java:5821) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687) 

and this is my code

class DatabaseHelper extends SQLiteOpenHelper {
private static Context context;
private static String DB_PATH = context.getFilesDir().getAbsolutePath();
private static String DB_NAME = "last.db";

private final Context mCtx;
public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, 1);
     this.mCtx = context;
}
public boolean createDatabase() {
    boolean dbExist = checkDatabase();
    this.getReadableDatabase();
    if (dbExist == false) {
        if (copyDatabase() == false) {
            return false;
        }
    }
    return true;
}
private boolean checkDatabase() {
    SQLiteDatabase checkDB = null;
    String dbpath = DB_PATH + DB_NAME;
    try {
        checkDB = SQLiteDatabase.openDatabase(dbpath,
                null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        return false;
    }
    if (checkDB != null) {
        checkDB.close();
        return true;
    }
    return false;
}
private boolean copyDatabase() {
    try {
        InputStream input = mCtx.getAssets().open(DB_NAME);
        this.getReadableDatabase();
        String outFileName = DB_PATH + DB_NAME;
        OutputStream output =
                new FileOutputStream(outFileName);
        byte [] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
        return false;
    }
    return true;
}
public void onCreate(SQLiteDatabase db) {
}
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
}

}

I deeply hope someone can help me to solve this big problem for me.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
user7338292
  • 11
  • 1
  • 1

1 Answers1

2
private static String DB_PATH = context.getFilesDir().getAbsolutePath();

First, context is null at this point.

Second, do not attempt to call methods inherited from your Activity from a field initializer. Postpone that work until onCreate(), typically after super.onCreate().

So replace that line with:

private static String DB_PATH;

and in onCreate(), add:

DB_PATH=getFilesDir().getAbsolutePath();

Or, better yet, delete all this code and use SQLiteAssetHelper.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    Alternative answer: Use the `mCtx` that is initialized within onCreate and remove the the other Context – OneCricketeer Dec 24 '16 at 19:42
  • This kind of answer (and the fact that you did reopen this question) is what make SO full of non useful answers, how is that (by that I mean question and your answer) supposed to help anyone in the future? –  Dec 24 '16 at 21:12
  • @RC.: A `NullPointerException` can have any number of root causes. The *immediate* cause (referencing a `context` field that has not been initialized) might well fit your proposed duplicate. However, the *underlying* problem (attempting to initialize something before such initialization will work) is not. In my answer, I addressed both facets, and so IMHO this adds value to the OP and to the site overall. If you feel that you can provide a better answer -- e.g., an in-depth explanation of the lifecycle and why initializers do not work here -- feel free to add one. – CommonsWare Dec 24 '16 at 21:30
  • There are a lot of "attempting to initialize something before such initialization" question already on the site: http://stackoverflow.com/questions/7547651/android-sqlitedatabase-nullpointerexception/7547926#7547926, http://stackoverflow.com/questions/27170428/android-passing-context-to-helper-class-results-in-npe, etc –  Dec 25 '16 at 08:13