Java SQLiteOpenHelper NullPointerException在创建时发生

Java SQLiteOpenHelper NullPointerException在创建时发生,java,android,sqlite,android-asynctask,nullpointerexception,Java,Android,Sqlite,Android Asynctask,Nullpointerexception,这是我第一次尝试在Android中使用SQLite数据库。我有一个数据库,里面有很多电影。我有一个加载活动,在retainedFragment中有一个AsyncTask。在AsyncTask中,我尝试从数据库中获取带有查询的游标。然后我将所有项目添加到ArrayList中,并从那里启动mainActivity 然而,当我尝试创建SQLiteOpenHelper时,我得到了一个NullPointerException。从网上阅读类似的问题来看,问题似乎与我的背景有关,但我无法找到一种方法使其发挥作

这是我第一次尝试在Android中使用SQLite数据库。我有一个数据库,里面有很多电影。我有一个加载活动,在retainedFragment中有一个AsyncTask。在AsyncTask中,我尝试从数据库中获取带有查询的游标。然后我将所有项目添加到ArrayList中,并从那里启动mainActivity

然而,当我尝试创建SQLiteOpenHelper时,我得到了一个NullPointerException。从网上阅读类似的问题来看,问题似乎与我的背景有关,但我无法找到一种方法使其发挥作用。我根据本教程创建了SQLiteOpenHelper:

以下是我的加载活动:

package com.example.pickmymovie;

import java.util.ArrayList;

import com.example.pickmymovie.LoadingFragment.LoadingCallback;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ProgressBar;

public class LoadingActivity extends Activity implements LoadingCallback {

    private ProgressBar bar;
    private LoadingFragment loadFrag;
    private ArrayList<Movie> movies;
    public final static String TAG_TASK_FRAGMENT = "LDFRAG";

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

        bar = (ProgressBar)findViewById(R.id.progress1);
        bar.setMax(10000);

        onPreExecute();
    }

    @Override
    public void onPreExecute() {
        connectWithRetainedFragment().executeTask();
    }

    @Override
    public void onCancelled() {
        // nothing
    }

    @Override
    public void onRunning(int progress) {
        bar.setProgress(progress);

    }

    @Override
    public void onPostExecute(Boolean bool) {
        if (bool) {
            Intent intent = new Intent(LoadingActivity.this, MainActivity.class );
            intent.putParcelableArrayListExtra("movies", movies);
            startActivity(intent);
        }
    }

    /**
     * find the retained fragment and connect to it. then return it so you can
     * calculate stuffs
     * 
     * @return
     */
    public LoadingFragment connectWithRetainedFragment() {
        FragmentManager fm = getFragmentManager();
        // r1 = (RetainedFragment)fm.findFragmentByTag(TAG_TASK_FRAGMENT);
        if (getFragmentManager().findFragmentByTag(TAG_TASK_FRAGMENT) == null) {
            loadFrag = new LoadingFragment();
            fm.beginTransaction().add(loadFrag, TAG_TASK_FRAGMENT).commit();
        }
        return loadFrag;
    }

    @Override
    public void setMovieList(ArrayList<Movie> movies) {
        this.movies = movies;
    }

}
我不完全确定SQLite的开放是如何工作的,这可能就是为什么我自己似乎无法弄明白这一点。感谢您的帮助。

getActivity()
在片段附加到其父活动之前返回null。这就是NPE的原因

提交片段事务不会立即执行它。这就是为什么碎片还没有贴上


通常,您不应该直接调用片段方法(
executeTask()
)。只需依赖片段生命周期回调,如
onCreate()
。如果需要将数据传递给片段,请使用
setArguments(Bundle)

我将AsyncTask移动到LoadingActivity类,而不是使用保留的片段来保存它,从而解决了这个问题。由于碎片是无头的,我很难找到上下文。这大大简化了本节的代码,尽管我不认为这是最好的解决方案。下面是我的LoadingActivity类现在的样子:

package com.example.pickmymovie;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;

public class LoadingActivity extends Activity {

    private ProgressBar bar;

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

        bar = (ProgressBar)findViewById(R.id.progress1);
        bar.setMax(10000);

        LoadingTask task = new LoadingTask(this);
        task.execute();
    }

    /**
     * A dummy task that performs some (dumb) background work and proxies
     * progress updates and results back to the Activity.
     * 
     * Note that we need to check if the callbacks are null in each method in
     * case they are invoked after the Activity's and Fragment's onDestroy()
     * method have been called.
     */
    private class LoadingTask extends AsyncTask<Cursor, Integer, Boolean> {

        private Cursor cursor;
        private ArrayList<Movie> movieList;
        private DataBaseHelper DbHelper;
        private Context context;

        public LoadingTask(Context context) {
            this.context = context;
        }

        /**
         * nothing here
         */
        @Override
        protected void onPreExecute() {
            //Create and open the database.
            DbHelper = new DataBaseHelper(context);
            try {
                DbHelper.createDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                DbHelper.openDataBase();
            }catch(SQLException sqle){
                throw sqle;
            }
            cursor = DbHelper.getCursor();
        }

        /**
         * Note that we do NOT call the callback object's methods directly from
         * the background thread, as this could result in a race condition.
         */
        @Override
        protected Boolean doInBackground(Cursor... param) {
            int total = cursor.getCount();
            int margin = 10000 / total;
            movieList = new ArrayList<Movie>();

            // do the stuff and report back to the home activity.
            for (int i = 0; i < cursor.getCount(); i++) {
                if (cursor.moveToFirst()) {
                    do {
                        Movie movie = new Movie();
                        movie.setId(Integer.parseInt(cursor.getString(0)));
                        movie.setName(cursor.getString(1));
                        movie.setGenre(cursor.getString(2));
                        movie.setImage(cursor.getString(3));
                        movie.setRating(Integer.parseInt(cursor.getString(4)));
                        // Adding movie to the list
                        movieList.add(movie);
                        publishProgress(i * margin);
                    } while (cursor.moveToNext());

                    // I don't think I've ever used a Do/While in java
                    // they taught us this in HS C++, but I've never touched it since.
                    // Oh well, it was in the example code
                }
            }
            return true;
        }

        /**
         * cancel the thing
         */
        @Override
        protected void onCancelled() {
            // nothing
        }

        /**
         * update the activity
         */
        protected void publishProgress(Integer progress) {
            bar.setProgress(progress);
        }

        /**
         * publish the result
         */
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Intent intent = new Intent(LoadingActivity.this, MainActivity.class );
                intent.putParcelableArrayListExtra("movies", movieList);
                Log.w("movies", movieList.get(0).title());
                startActivity(intent);
            }
        }
    }
}
package com.example.pickmymovie;
导入java.io.IOException;
导入java.util.ArrayList;
导入android.app.Activity;
导入android.content.Context;
导入android.content.Intent;
导入android.database.Cursor;
导入android.database.SQLException;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.ProgressBar;
公共类加载活动扩展活动{
私人酒吧;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.loading);
bar=(ProgressBar)findViewById(R.id.progress1);
巴最大值(10000);
LoadingTask任务=新建LoadingTask(此任务);
task.execute();
}
/**
*执行一些(哑)后台工作和代理的虚拟任务
*将进度更新和结果返回到活动。
* 
*注意,我们需要检查中的每个方法中的回调是否为null
*在活动和片段的onDestroy()之后调用它们
*方法已被调用。
*/
私有类装入任务扩展异步任务{
私有游标;
私人电影导演;
私有数据库助手DbHelper;
私人语境;
公共加载任务(上下文){
this.context=上下文;
}
/**
*这里什么都没有
*/
@凌驾
受保护的void onPreExecute(){
//创建并打开数据库。
DbHelper=新数据库助手(上下文);
试一试{
DbHelper.createDataBase();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
DbHelper.openDataBase();
}捕获(SQLException sqle){
抛出sqle;
}
cursor=DbHelper.getCursor();
}
/**
*请注意,我们不直接从调用回调对象的方法
*后台线程,因为这可能导致竞争条件。
*/
@凌驾
受保护的布尔doInBackground(游标…参数){
int total=cursor.getCount();
国际保证金=10000/总;
movieList=newarraylist();
//完成这些工作并向家庭活动汇报。
对于(int i=0;i
哪一行是
LoadingFragment.java:102
LoadingFragment.java:102
Db
package com.example.pickmymovie;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.pickmymovie/databases/";

    private static String DB_NAME = "movieDatabase";

    private SQLiteDatabase myDataBase; 

    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }   

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){

            //database does't exist yet.

        }

        if(checkDB != null){

            checkDB.close();

        }

        //return checkDB != null ? true : false;
        // ^ was in the example code. Seems like a goober way to do it.
        return (checkDB != null);
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public Cursor getCursor() {
        ArrayList<Movie> movieList = new ArrayList<Movie>();
        // Select All Query
        String selectQuery = "SELECT  * FROM movies";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        return cursor;
    }
}
08-10 03:20:30.745: W/dalvikvm(18469): threadid=1: thread exiting with uncaught exception (group=0x417b2da0)
08-10 03:20:30.745: E/AndroidRuntime(18469): FATAL EXCEPTION: main
08-10 03:20:30.745: E/AndroidRuntime(18469): Process: com.example.pickmymovie, PID: 18469
08-10 03:20:30.745: E/AndroidRuntime(18469): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pickmymovie/com.example.pickmymovie.LoadingActivity}: java.lang.NullPointerException
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2334)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.ActivityThread.access$900(ActivityThread.java:169)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.os.Looper.loop(Looper.java:146)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.ActivityThread.main(ActivityThread.java:5487)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at java.lang.reflect.Method.invokeNative(Native Method)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at java.lang.reflect.Method.invoke(Method.java:515)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at dalvik.system.NativeStart.main(Native Method)
08-10 03:20:30.745: E/AndroidRuntime(18469): Caused by: java.lang.NullPointerException
08-10 03:20:30.745: E/AndroidRuntime(18469):    at com.example.pickmymovie.LoadingFragment$LoadingTask.onPreExecute(LoadingFragment.java:102)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.os.AsyncTask.execute(AsyncTask.java:535)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at com.example.pickmymovie.LoadingFragment.executeTask(LoadingFragment.java:70)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at com.example.pickmymovie.LoadingActivity.onPreExecute(LoadingActivity.java:33)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at com.example.pickmymovie.LoadingActivity.onCreate(LoadingActivity.java:28)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.Activity.performCreate(Activity.java:5451)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
08-10 03:20:30.745: E/AndroidRuntime(18469):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
08-10 03:20:30.745: E/AndroidRuntime(18469):    ... 11 more
08-10 03:20:33.467: I/Process(18469): Sending signal. PID: 18469 SIG: 9
package com.example.pickmymovie;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;

public class LoadingActivity extends Activity {

    private ProgressBar bar;

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

        bar = (ProgressBar)findViewById(R.id.progress1);
        bar.setMax(10000);

        LoadingTask task = new LoadingTask(this);
        task.execute();
    }

    /**
     * A dummy task that performs some (dumb) background work and proxies
     * progress updates and results back to the Activity.
     * 
     * Note that we need to check if the callbacks are null in each method in
     * case they are invoked after the Activity's and Fragment's onDestroy()
     * method have been called.
     */
    private class LoadingTask extends AsyncTask<Cursor, Integer, Boolean> {

        private Cursor cursor;
        private ArrayList<Movie> movieList;
        private DataBaseHelper DbHelper;
        private Context context;

        public LoadingTask(Context context) {
            this.context = context;
        }

        /**
         * nothing here
         */
        @Override
        protected void onPreExecute() {
            //Create and open the database.
            DbHelper = new DataBaseHelper(context);
            try {
                DbHelper.createDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                DbHelper.openDataBase();
            }catch(SQLException sqle){
                throw sqle;
            }
            cursor = DbHelper.getCursor();
        }

        /**
         * Note that we do NOT call the callback object's methods directly from
         * the background thread, as this could result in a race condition.
         */
        @Override
        protected Boolean doInBackground(Cursor... param) {
            int total = cursor.getCount();
            int margin = 10000 / total;
            movieList = new ArrayList<Movie>();

            // do the stuff and report back to the home activity.
            for (int i = 0; i < cursor.getCount(); i++) {
                if (cursor.moveToFirst()) {
                    do {
                        Movie movie = new Movie();
                        movie.setId(Integer.parseInt(cursor.getString(0)));
                        movie.setName(cursor.getString(1));
                        movie.setGenre(cursor.getString(2));
                        movie.setImage(cursor.getString(3));
                        movie.setRating(Integer.parseInt(cursor.getString(4)));
                        // Adding movie to the list
                        movieList.add(movie);
                        publishProgress(i * margin);
                    } while (cursor.moveToNext());

                    // I don't think I've ever used a Do/While in java
                    // they taught us this in HS C++, but I've never touched it since.
                    // Oh well, it was in the example code
                }
            }
            return true;
        }

        /**
         * cancel the thing
         */
        @Override
        protected void onCancelled() {
            // nothing
        }

        /**
         * update the activity
         */
        protected void publishProgress(Integer progress) {
            bar.setProgress(progress);
        }

        /**
         * publish the result
         */
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Intent intent = new Intent(LoadingActivity.this, MainActivity.class );
                intent.putParcelableArrayListExtra("movies", movieList);
                Log.w("movies", movieList.get(0).title());
                startActivity(intent);
            }
        }
    }
}