Android-从SQLite加载光标
我想从SQLite DB内部片段加载三列。片段应:Android-从SQLite加载光标,android,sqlite,nullpointerexception,cursor,android-sqlite,Android,Sqlite,Nullpointerexception,Cursor,Android Sqlite,我想从SQLite DB内部片段加载三列。片段应: Load DB(数据库已经满了,我只是复制它供以后使用) 创建光标 将对象数据发送到自定义ListAdapter 我得到这个错误: 尝试调用虚拟方法“android.database.Cursor” android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[],java.lang.String,java.lang.String[], nul
- Load 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");
}
}
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();
}
这里是MyDBHelper类(我在主要活动中工作得很好):
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");
}
}
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();
}
我认为应该在onActivityCreated或onViewCreated中传输db函数。在此之前,活动中的getContext()可以为null。不是这样。我只是有一个旧版本的数据库是空的。否则装载就可以了