Android SQLiteAssetHelper数据库无法打开

时间:2018-11-08 10:58:30

标签: android android-sqlite sqliteopenhelper

我正在尝试通过SQLiteAssetHelper在Android Studio中连接SQLite数据库,我已经尝试了所有方法,但是显示... 无法打开数据库。 我不知道这是什么问题。我是android开发的新手。 我看过其他问题的答案,但无济于事。

这是我的数据库类:

public class MyDB extends SQLiteAssetHelper {

private static final String DB_NAME="Demo.db";
private static final int DB_ver=1;

//private static MyDB myDB=null;



public MyDB(Context context) {
    super(context, DB_NAME, null, DB_ver);
}
}

这是数据库访问类:

public class OpenDBHelper {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static OpenDBHelper openDBHelper ;

private OpenDBHelper(Context context)
{

    this.openHelper = new MyDB(context);

}

public static OpenDBHelper getInstance(Context context)
{
    if(openDBHelper==null)
    {
        openDBHelper=new OpenDBHelper(context.getApplicationContext()) ;

    }
    return openDBHelper;
}

public SQLiteDatabase openwrite()
{
    this.db= openHelper.getReadableDatabase();
    return db;
}


}

这是我试图在列表视图中加载数据的主要活动:

public class MainActivity extends AppCompatActivity {

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

    lv=(ListView) findViewById(R.id.lv_main);
    loadStudents();

}
public void loadStudents()
{

    ArrayList<HashMap<String, String>> userList = GetAllStudents();

    ListAdapter adapter = new SimpleAdapter(this, userList, R.layout.lv_row,new String[]{"name","cast","phone"}, new int[]{R.id.tv_name, R.id.tv_cast, R.id.tv_phone});
    lv.setAdapter(adapter);
}
//GEt All Students to listview
public ArrayList<HashMap<String, String>> GetAllStudents(){
    ArrayList<HashMap<String, String>> userList = new ArrayList<>();


    OpenDBHelper open= OpenDBHelper.getInstance(this);
    SQLiteDatabase db=open.openwrite();

    String query = "SELECT * FROM tbl_bio";
    Cursor cursor = db.rawQuery(query,null);
    if(cursor.getCount()>0) {
        while (cursor.moveToNext()) {
            HashMap<String, String> user = new HashMap<>();
            user.put("name", cursor.getString(1));
            user.put("cast", cursor.getString(2));
            user.put("phone", cursor.getString(3));
            //user.put("pass", cursor.getString(4));
            userList.add(user);
        }
    }


    return  userList;
}
}

0 个答案:

没有答案