Android - 从SQLite加载光标

时间:2016-09-01 20:57:59

标签: android sqlite nullpointerexception cursor android-sqlite

我想在Fragment中从SQLite DB加载三列。片段应该:

  • 加载数据库(数据库已经满了,我只是复制它以供以后使用)
  • 创建游标
  • 将对象数据发送到自定义ListAdapter

我收到此错误:

  

尝试调用虚方法'android.database.Cursor   android.database.sqlite.SQLiteDatabase.query(java.lang.String中,   java.lang.String [],java.lang.String,java.lang.String [],   null.java.lang.String,java.lang.String,java.lang.String)'   对象参考                                                                                            在   com.example.somap.myapp.ListFragment.LoadMonsterLinkList(ListFragment.java:88)

我认为问题可能出在初始数据库负载上。但我没有看到为什么加载DB = null

的原因

片段活动(剪切):

public class ListFragment extends Fragment {

private OnFragmentInteractionListener mListener;

/** ----- My global variables ----- **/
/** For log **/
private static String TAG = "Monster list";
/** For view changes **/
private View MyView = null;
/** For DB query **/
private String CategoryID = null;
/** DB **/
private SQLiteDatabase MyDatabase = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //Load view
    this.MyView = inflater.inflate(R.layout.fragment_list, container,false);

    //Change the category label
    SetCategoryLabel(); --> This is OK

    //Load DB;
    LoadDatabase();

    //Create list for MonsterList
    MonsterLink[] MonsterLinkList = LoadMonsterLinkList(); 

    .
    . //Some code
    .
    .

    // Inflate the layout for this fragment
    return this.MyView; //inflater.inflate(R.layout.fragment_list, container, false);
}

public MonsterLink[] LoadMonsterLinkList() {
    Log.i(this.TAG, "LoadMonsterLinkList");

    //Query
    String Table = "Monster";
    String[] Columns = {"ID", "Displayname", "ImagePath"};
    String Where = "Category=\"" + this.CategoryID + "\"";
    Cursor cursor = this.MyDatabase.query(Table,Columns,Where,null,null,null,null); => Here is my error

    MonsterLink[] List = new MonsterLink[cursor.getCount()];

    int i = 0;
    while (cursor.moveToNext()){
        Log.i(this.TAG, cursor.getString(0) + "  " + cursor.getString(1) + "  " + cursor.getString(2));
        MonsterLink monsterlink = new MonsterLink(cursor.getString(0),cursor.getString(1),cursor.getString(2));
        List[i] = monsterlink;
        i++;
    }

    return List;
}

protected void LoadDatabase(){

    MyDBHelper MyDB = new MyDBHelper(this.MyView.getContext());

    try {

        MyDB.createDataBase();
        this.MyDatabase =  MyDB.GetDatabase(); => Mydatabase is null, why?

    } catch (IOException ioe) {

        throw new Error("Unable to create database");

    }
}

这是MyDBHelper类(我在主要活动中工作正常):

public class MyDBHelper extends SQLiteOpenHelper {

//The Androids default system path of your application database.
private static String DB_PATH = "/data/data/com.example.somap.myapp/databases/";

private static String DB_NAME = "Bestiary.db";

private SQLiteDatabase myDataBase;

private final Context myContext;

public SQLiteDatabase GetDatabase(){return this.myDataBase;}

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public MyDBHelper(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;
}

/**
 * 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();

}

1 个答案:

答案 0 :(得分:0)

我认为您应该在onActivityCreated或onViewCreated中传输db函数。在此之前,来自activity的getContext()可以为null。