Java 用户是否可以更新预定义的数据库?安卓工作室

Java 用户是否可以更新预定义的数据库?安卓工作室,java,android,database,sqlite,android-studio,Java,Android,Database,Sqlite,Android Studio,我是Android Studio的新手,所以请容忍我 我想做一个应用程序,有报价列表,并有一个最喜欢的按钮除了每个报价 因此,在创建数据库之后,我使用SQLite浏览器创建预定义的数据库 我打开Android studio,右键单击并粘贴到资产文件夹 所以我的问题是 1) 当用户单击某些引号上的收藏夹按钮时,如何更新数据库?这样应用程序就可以知道哪一个是用户的最爱,并将其列在另一个活动中 2) 我想使用SQlite浏览器更新我的报价列表,并用新的数据库文件替换资产文件夹中的旧数据库文件。但是当我

我是Android Studio的新手,所以请容忍我 我想做一个应用程序,有报价列表,并有一个最喜欢的按钮除了每个报价

因此,在创建数据库之后,我使用SQLite浏览器创建预定义的数据库 我打开Android studio,右键单击并粘贴到资产文件夹

所以我的问题是

1) 当用户单击某些引号上的收藏夹按钮时,如何更新数据库?这样应用程序就可以知道哪一个是用户的最爱,并将其列在另一个活动中

2) 我想使用SQlite浏览器更新我的报价列表,并用新的数据库文件替换资产文件夹中的旧数据库文件。但是当我尝试在Bluestack上测试它时,它只显示以前的数据库文件

3) 如果在使用预定义数据库时无法更新SQLite,那么除了SQLite之外,还有什么我可以使用的吗

这是我的密码

数据库OpenHelper.java

public class DatabaseOpenHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";

private SQLiteDatabase database;

private final Context context;

// database path
private static String DATABASE_PATH;

/** constructor */
public DatabaseOpenHelper(Context ctx) {
    super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = ctx;
    DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
            + "/databases/";

}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public void create() throws IOException {
    boolean check = checkDataBase();

    SQLiteDatabase db_Read = null;

    // Creates empty database default system path
    db_Read = this.getWritableDatabase();
    db_Read.close();
    try {
        if (!check) {
            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 = DATABASE_PATH + DATABASE_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    } 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 = context.getAssets().open(DATABASE_NAME);

    // Path to the just created empty db
    String outFileName = DATABASE_PATH + DATABASE_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();

}

/** open the database */
public void open() throws SQLException {
    String myPath = DATABASE_PATH + DATABASE_NAME;
    database = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);
}

/** close the database */
@Override
public synchronized void close() {
    if (database != null)
        database.close();
    super.close();
}

// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(COLUMN_QUOTES, quotesText );
    initialValues.put(COLUMN_AUTHOR, author);
    initialValues.put(COLUMN_FAV, fav);
    return database.insert(TABLE_NAME, null, initialValues);
}

// updates a user
public boolean updateUser(long rowId, String quotesText, String author,
                          String fav) {
    ContentValues args = new ContentValues();
    args.put(COLUMN_QUOTES, quotesText);
    args.put(COLUMN_AUTHOR, author);
    args.put(COLUMN_FAV, fav);
    return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
                    COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
            COLUMN_ID + " = " + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }

    return mCursor;
}

// delete a particular user
public boolean deleteContact(long rowId) {
    return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieves all users
public Cursor getAllUsers() {
    return database.query(TABLE_NAME, new String[] { COLUMN_ID,
                    COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
            null, null, null);
}

@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

}
public class QuotesActivity extends AppCompatActivity {

TextView title;
Typeface myFont;
ListView quotesList;
ListView favLV;
DatabaseOpenHelper myDbHelper;
DatabaseAccess databaseAccess;

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

    myDbHelper = new DatabaseOpenHelper(this);

    try {
        // check if database exists in app path, if not copy it from assets
        myDbHelper.create();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    try {
        // open the database
        myDbHelper.open();
        myDbHelper.getWritableDatabase();
    } catch (SQLException sqle) {
        throw sqle;
    }

    populateListView();



    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    toolbar.setNavigationIcon(R.drawable.back_button);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    title = (TextView) findViewById(R.id.titleQuote);
    myFont =  Typeface.createFromAsset(getAssets(), "Montserrat-Bold.otf");
    title.setTypeface(myFont);
    title.setTextSize(20);
    title.setTextColor(Color.rgb(240, 239, 223));

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

private void populateListView() {
    Cursor cursor = myDbHelper.getAllUsers();
    String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
    int[] to = new int[] {R.id.quoteLV, R.id.authorLV};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
    quotesList = (ListView) findViewById(R.id.quotesList);
    quotesList.setAdapter(myCursorAdapter);
}
}
quoteActivity.java

public class DatabaseOpenHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";

private SQLiteDatabase database;

private final Context context;

// database path
private static String DATABASE_PATH;

/** constructor */
public DatabaseOpenHelper(Context ctx) {
    super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = ctx;
    DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
            + "/databases/";

}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public void create() throws IOException {
    boolean check = checkDataBase();

    SQLiteDatabase db_Read = null;

    // Creates empty database default system path
    db_Read = this.getWritableDatabase();
    db_Read.close();
    try {
        if (!check) {
            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 = DATABASE_PATH + DATABASE_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    } 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 = context.getAssets().open(DATABASE_NAME);

    // Path to the just created empty db
    String outFileName = DATABASE_PATH + DATABASE_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();

}

/** open the database */
public void open() throws SQLException {
    String myPath = DATABASE_PATH + DATABASE_NAME;
    database = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);
}

/** close the database */
@Override
public synchronized void close() {
    if (database != null)
        database.close();
    super.close();
}

// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(COLUMN_QUOTES, quotesText );
    initialValues.put(COLUMN_AUTHOR, author);
    initialValues.put(COLUMN_FAV, fav);
    return database.insert(TABLE_NAME, null, initialValues);
}

// updates a user
public boolean updateUser(long rowId, String quotesText, String author,
                          String fav) {
    ContentValues args = new ContentValues();
    args.put(COLUMN_QUOTES, quotesText);
    args.put(COLUMN_AUTHOR, author);
    args.put(COLUMN_FAV, fav);
    return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
                    COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
            COLUMN_ID + " = " + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }

    return mCursor;
}

// delete a particular user
public boolean deleteContact(long rowId) {
    return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieves all users
public Cursor getAllUsers() {
    return database.query(TABLE_NAME, new String[] { COLUMN_ID,
                    COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
            null, null, null);
}

@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

}
public class QuotesActivity extends AppCompatActivity {

TextView title;
Typeface myFont;
ListView quotesList;
ListView favLV;
DatabaseOpenHelper myDbHelper;
DatabaseAccess databaseAccess;

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

    myDbHelper = new DatabaseOpenHelper(this);

    try {
        // check if database exists in app path, if not copy it from assets
        myDbHelper.create();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    try {
        // open the database
        myDbHelper.open();
        myDbHelper.getWritableDatabase();
    } catch (SQLException sqle) {
        throw sqle;
    }

    populateListView();



    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    toolbar.setNavigationIcon(R.drawable.back_button);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    title = (TextView) findViewById(R.id.titleQuote);
    myFont =  Typeface.createFromAsset(getAssets(), "Montserrat-Bold.otf");
    title.setTypeface(myFont);
    title.setTextSize(20);
    title.setTextColor(Color.rgb(240, 239, 223));

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

private void populateListView() {
    Cursor cursor = myDbHelper.getAllUsers();
    String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
    int[] to = new int[] {R.id.quoteLV, R.id.authorLV};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
    quotesList = (ListView) findViewById(R.id.quotesList);
    quotesList.setAdapter(myCursorAdapter);
}
}
Content\u quotes.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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: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="hendrasetiawan.mqn.QuotesActivity"
tools:showIn="@layout/activity_quotes">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/quotesList"
            android:layout_gravity="right"
            android:layout_weight="1" />

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/favList"
            android:layout_weight="6" />


    </LinearLayout>



</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/quoteLV"
    android:textSize="20dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/authorLV"
    android:textSize="20dp"/>
</LinearLayout>

quotes\u listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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: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="hendrasetiawan.mqn.QuotesActivity"
tools:showIn="@layout/activity_quotes">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/quotesList"
            android:layout_gravity="right"
            android:layout_weight="1" />

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/favList"
            android:layout_weight="6" />


    </LinearLayout>



</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/quoteLV"
    android:textSize="20dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/authorLV"
    android:textSize="20dp"/>
</LinearLayout>

Android不提供任何使用外部SQLite数据库(存储在资产文件夹中)的方法或API。然而,有一天我发现一个图书馆可以解决你的问题。以下是链接:

从网页下载此库并将其添加到Android Studio中的项目中。一、 我个人没有使用过这个图书馆。然而,这个库包含一些有用的示例或演示代码,StackOverflow上肯定会有人使用它。他们也许能帮助你

希望这个图书馆能解决你的问题,祝你好运