这是一个测验应用。有一个问题活动,其中有一个计时器的进度条,一个问题的TextView和四个选项的四个按钮。问题是我无法从/data/data/com.example.mohsinbhat.examsystem/databases/computer.db中读取问题及其答案。另外/data/data/com.example.mohsinbhat.examsystem/databases/computer.db为空。在Text TextView中传递零值,其余的Button文本为空。
这是我的SQLite Helper类,名为computer.java,另一个名为sports.java。这些类的数据库存储在assets文件夹中。
//computer.java
package com.example.mohsinbhat.examsystem.MyQuiz;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
public class computer extends SQLiteOpenHelper {
private static final String Database_path =
"/data/data/com.example.mohsinbhat.examsystem/databases/";
private static final String Database_name = "computer.db";
//NAME of database stored in Assets folder
private static final String Table_name = "computer";//name of table
private static final String uid = "_id";//name of column1
private static final String Question = "Question";//name of column2
private static final String OptionA = "OptionA";//name of column3
private static final String OptionB = "OptionB";//name of column4
private static final String OptionC = "OptionC";//name of column5
private static final String OptionD = "OptionD";//name of column6
private static final String Answer = "Answer";//name of column7
private static final int version = 1;
public SQLiteDatabase sqlite;//object of type SQLiteDatabase
private Context context;//Context object to get context from Question
//Activity
public computer(Context context) {//constructor
super(context, Database_name, null, version);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
//No code because we have already created the database
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//No code because we have already created the database
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbexist = DBexists();//calling the function to check db exists
//or not
if (!dbexist)//if database doesnot exist
{
this.getReadableDatabase();//Create an empty file
copyDBfromResource();//copy the database file information of assets
//folder to newly create file
}
}
private void copyDBfromResource() {
InputStream is;
OutputStream os;
String filePath = Database_path + Database_name;
try {
is = context.getAssets().open(Database_name);//reading purpose
os = new FileOutputStream(filePath);//writing purpose
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);//writing to file
}
os.flush();//flush the outputstream
is.close();//close the inputstream
os.close();//close the outputstream
} catch (IOException e) {
throw new Error("Problem copying database file:");
}
}
public void openDatabase() throws SQLException//called by onCreate method
//of Questions Activity
{
String myPath = Database_path + Database_name;
sqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
private boolean DBexists()//Check whether the db file exists or not
{
SQLiteDatabase db = null;
try {
String databasePath = Database_path + Database_name;
db = SQLiteDatabase.openDatabase(databasePath, null, S
QLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setVersion(1);
db.setLockingEnabled(true);
} catch (SQLException e) {
Log.e("Sqlite", "Database not found");
}
if (db != null)
db.close();///close the opened file
return db != null ? true : false;
}
public String readQuestion(int i)//Used to read the data from the Des.db
//file where id is given and we choose id randomly
{
String Ans = "";//string that contains the required field note that Ans
//is just a local string not related to Answer or Option...
Cursor c = sqlite.rawQuery("SELECT " + Question + " FROM " + Table_name
+ " WHERE "
+ uid + " = " + i + "", null);//cursor to that query
if (c.moveToFirst())
Ans = c.getString(0);
else
Ans = "";
c.close();
return Ans;
}
public String readOptionA(int i)//Used to read the data from the Des.db
//file where id is given and we choose id randomly
{
String Ans = "";//string that contains the required field note that Ans
// is just a local string not related to Answer or Option...
Cursor c = sqlite.rawQuery("SELECT " + OptionA + " FROM " + Table_name +
" WHERE "+ uid + " = " + i + "", null);//cursor to that query
if (c.moveToFirst())
Ans = c.getString(0);
else
Ans = "";
c.close();
return Ans;
}
public String readOptionB(int i)//Used to read the data from the Des.db
//file where id is given and we choose id randomly
{
String Ans = "";//string that contains the required field note that Ans
is just a local string not related to Answer or Option...
Cursor c = sqlite.rawQuery("SELECT " + OptionB + " FROM " + Table_name +
" WHERE " + uid + " = " + i + "", null);//cursor to that query
if (c.moveToFirst())
Ans = c.getString(0);
else
Ans = "";
c.close();
return Ans;
}
public String readOptionC(int i)//Used to read the data from the Des.db
file where id is given and we choose id randomly
{
String Ans = "";//string that contains the required field note that Ans
is just a local string not related to Answer or Option...
Cursor c = sqlite.rawQuery("SELECT " + OptionC + " FROM " + Table_name +
" WHERE " + uid + " = " + i + "", null);//cursor to that query
if (c.moveToFirst())
Ans = c.getString(0);
else
Ans = "";
c.close();
return Ans;
}
public String readOptionD(int i)//Used to read the data from the
//Des.db file where id is given and we choose id randomly
{
String Ans = "";//string that contains the required field note that
Ans is just a local string not related to Answer or Option...
Cursor c = sqlite.rawQuery("SELECT " + OptionD + " FROM " + Table_name +
" WHERE "+ uid + " = " + i + "", null);//cursor to that query
if (c.moveToFirst())
Ans = c.getString(0);
else
Ans = "";
c.close();
return Ans;
}
public String readAnswer(int i)//Used to read the data from the Des.db
//file where id is given and we choose id randomly
{
String Ans = "";//string that contains the required field
Cursor c = sqlite.rawQuery("SELECT " + Answer + " FROM " + Table_name +
" WHERE "+ uid + " = " + i + "", null);//cursor to that query
if (c.moveToFirst())
Ans = c.getString(0);
else
Ans = "";
c.close();
return Ans;
}
这是问题活动的xml布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MyQuiz.Questions">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".Questions">
<com.github.lzyzsd.circleprogress.DonutProgress
android:id="@+id/donut_progress"
android:layout_width="70dp"
android:layout_height="70dp"
android:visibility="invisible"
android:layout_alignParentEnd="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/donut_progress"
android:orientation="vertical">
<TextView
android:id="@+id/Questions"
android:layout_width="match_parent"
android:layout_height="140dp"
android:textAlignment="center"
android:textColor="#393737"
android:textSize="28sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<Button
android:id="@+id/OptionA"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="10dp"
android:onClick="onClick"
android:foreground="?attr/selectableItemBackground"
android:textAlignment="center"
android:visibility="invisible"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="@+id/OptionB"
android:layout_width="0dp"
android:foreground="?attr/selectableItemBackground"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="onClick"
android:padding="10dp"
android:visibility="invisible"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:orientation="horizontal">
<Button
android:id="@+id/OptionC"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:foreground="?attr/selectableItemBackground"
android:padding="10dp"
android:visibility="invisible"
android:textAlignment="center"
android:textAllCaps="false"
android:onClick="onClick"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="@+id/OptionD"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="10dp"
android:visibility="invisible"
android:textAlignment="center"
android:onClick="onClick"
android:foreground="?attr/selectableItemBackground"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/play_button"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="@+id/donut_progress"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginTop="13dp"
android:background="@drawable/custom_option"
android:foreground="?attr/selectableItemBackground"
android:onClick="onClick"
android:text="@string/plays"
android:textColor="#fff"
android:textSize="40sp" />
</RelativeLayout>
答案 0 :(得分:0)
尝试将数据库从资源文件夹复制到设备存储,然后从那里访问它。 下面是将其复制到本地存储的示例代码
private static final String DATABASE_NAME = "yourdb.sqlite";
private static final String DB_PATH_SUFFIX = "/databases/";
//Use this function to openDatabase
//This will copy the database if its not already copied or deleted
public SQLiteDatabase openDataBase() throws SQLException {
File dbFile = context.getDatabasePath(DATABASE_NAME);
if (!dbFile.exists()) {
try {
CopyDataBaseFromAsset();
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
}
//This function copies the database to device storage
public void CopyDataBaseFromAsset() throws IOException {
InputStream myInput = context.getAssets().open(DATABASE_NAME);
String outFileName = getDatabasePath();
File f = new File(context.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
//Get absolute path of database
private String getDatabasePath() {
return context.getApplicationInfo().dataDir + DB_PATH_SUFFIX
+ DATABASE_NAME;
}