Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/214.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Android Studio中使用SQLite创建数据库_Java_Android_Database_Sqlite - Fatal编程技术网

Java 如何在Android Studio中使用SQLite创建数据库

Java 如何在Android Studio中使用SQLite创建数据库,java,android,database,sqlite,Java,Android,Database,Sqlite,我基本上想创建一个数据库,我认为这个代码会这样做,但它从来没有创建数据库,因为当我在我的计算机上查找数据库文件时,没有创建数据库。我也不确定数据库是在哪里创建的,所以如果能指出这一点,我们也将不胜感激。我有数据库助手、提供者和登录活动的代码,因为我认为这就是我的问题所在。我也不知道这是否与我使用直接查询有关,因为我在其他部分使用ContentValues,但是如果您想查看其他代码,请告诉我。谢谢大家! 数据库提供者 public class ChargerPointsProvider exten

我基本上想创建一个数据库,我认为这个代码会这样做,但它从来没有创建数据库,因为当我在我的计算机上查找数据库文件时,没有创建数据库。我也不确定数据库是在哪里创建的,所以如果能指出这一点,我们也将不胜感激。我有数据库助手、提供者和登录活动的代码,因为我认为这就是我的问题所在。我也不知道这是否与我使用直接查询有关,因为我在其他部分使用ContentValues,但是如果您想查看其他代码,请告诉我。谢谢大家!

数据库提供者

public class ChargerPointsProvider extends ContentProvider {

    @Override
    public boolean onCreate(){
        return true;
    }

    /** URI matcher code for the content URI for the userInfo table */
    private static final int USER_INFO = 100;

    /** URI matcher code for the content URI for a single user in the userInfo table */
    private static final int USER_INFO_ID = 101;

    /** URI matcher code for the content URI for the couponInfo table */
    private static final int COUPON_INFO = 102;

    /** URI matcher code for the content URI for a single coupon in the couponInfo table */
    private static final int COUPON_INFO_ID = 103;

    /** URI matcher code for the content URI for the points table */
    private static final int POINTS_INFO = 104;

    /** URI matcher code for the content URI for a single user in the points table */
    private static final int POINTS_INFO_ID = 105;

    /** URI matcher code for the content URI for the userCouponsInfo table */
    private static final int USER_COUPONS_INFO = 106;

    /** URI matcher code for the content URI for a single user in the userCouponsInfo table */
    private static final int USER_COUPONS_INFO_ID = 107;

    /**Tag for the log messages*/
    public static final String LOG_TAG = ChargerPointsContract.class.getSimpleName();

    private ChargerPointsDbHelper mDbHelper;

    /**
     * UriMatcher object to match a content URI to a corresponding code.
     * The input passed into the constructor represents the code to return for the root URI.
     * It's common to use NO_MATCH as the input for this case.
     */
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    // Static initializer. This is run the first time anything is called from this class.
    static {
        // The calls to addURI() go here, for all of the content URI patterns that the provider
        // should recognize. All paths added to the UriMatcher have a corresponding code to return
        // when a match is found.

        // The content URI of the form "content://com.example.android.chargerpoints/userInfo" will map to the
        // integer code {@link #USER_INFO}. This URI is used to provide access to MULTIPLE rows
        // of the userInfo table.
        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_USER_INFO, USER_INFO);

        // The content URI of the form "content://com.example.android.chargerpoints/userInfo/#" will map to the
        // integer code {@link #USER_INFO_ID}. This URI is used to provide access to ONE single row
        // of the userInfo table.
        //
        // In this case, the "#" wildcard is used where "#" can be substituted for an integer.
        // For example, "content://com.example.android.chargerpoints/userInfo/3" matches, but
        // "content://com.example.android.chargerpoints/userInfo" (without a number at the end) doesn't match.
        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_USER_INFO + "/#", USER_INFO_ID);

        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_COUPON_INFO, COUPON_INFO);
        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_COUPON_INFO + "/#", COUPON_INFO_ID);

        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_POINTS_INFO, POINTS_INFO);
        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_POINTS_INFO + "/#", POINTS_INFO_ID);

        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_USER_COUPONS_INFO, USER_COUPONS_INFO);
        sUriMatcher.addURI(ChargerPointsContract.CONTENT_AUTHORITY, ChargerPointsContract.PATH_USER_COUPONS_INFO + "/#", USER_COUPONS_INFO_ID);

    }

    /**
     * Perform the query for the given URI. Use the given projection, selection, selection arguments, and sort order.
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                        String sortOrder) {

        // Get readable database
        SQLiteDatabase database = mDbHelper.getReadableDatabase();

        // This cursor will hold the result of the query
        Cursor cursor;

        // Figure out if the URI matcher can match the URI to a specific code
        int match = sUriMatcher.match(uri);
        switch (match) {
            case USER_INFO:
                // For the USER_INFO code, query the userInfo table directly with the given
                // projection, selection, selection arguments, and sort order. The cursor
                // could contain multiple rows of the userInfo table.
                cursor = database.query(ChargerPointsContract.UserInfoEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case USER_INFO_ID:
                // For the USER_INFO_ID code, extract out the ID from the URI.
                // For an example URI such as "content://com.example.android.chargerpoints/userInfo/3",
                // the selection will be "_id=?" and the selection argument will be a
                // String array containing the actual ID of 3 in this case.
                //
                // For every "?" in the selection, we need to have an element in the selection
                // arguments that will fill in the "?". Since we have 1 question mark in the
                // selection, we have 1 String in the selection arguments' String array.
                selection = ChargerPointsContract.UserInfoEntry._ID + "=?";
                selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };

                // This will perform a query on the userInfo table where the _id equals 3 to return a
                // Cursor containing that row of the table.
                cursor = database.query(ChargerPointsContract.UserInfoEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case COUPON_INFO:
                cursor = database.query(ChargerPointsContract.CouponInfoEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case COUPON_INFO_ID:
                selection = ChargerPointsContract.CouponInfoEntry._ID + "=?";
                selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
                cursor = database.query(ChargerPointsContract.CouponInfoEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case POINTS_INFO:
                cursor = database.query(ChargerPointsContract.PointsEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case POINTS_INFO_ID:
                selection = ChargerPointsContract.PointsEntry._ID + "=?";
                selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
                cursor = database.query(ChargerPointsContract.PointsEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case USER_COUPONS_INFO:
                cursor = database.query(ChargerPointsContract.UserCouponsEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case USER_COUPONS_INFO_ID:
                selection = ChargerPointsContract.UserCouponsEntry._ID + "=?";
                selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
                cursor = database.query(ChargerPointsContract.UserCouponsEntry.TABLE_NAME, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Cannot query unknown URI " + uri);
        }
        return cursor;
    }

    /**
     * Insert new data into the provider with the given ContentValues.
     */
    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        final int match = sUriMatcher.match(uri);
        switch (match) {
            case USER_INFO:
                return insertUserInfo(uri, contentValues);
            case COUPON_INFO:
                return insertCouponInfo(uri, contentValues);
            case USER_COUPONS_INFO:
                return insertUserCouponsInfo(uri, contentValues);
            case POINTS_INFO:
                return insertPointsInfo(uri,contentValues);
            default:
                throw new IllegalArgumentException("Insertion is not supported for " + uri);
        }
    }

    @Override
    public int delete(Uri uri, String s, String[] strings) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
        return 0;
    }

    /**
     * Insert a user into the database with the given content values. Return the new content URI
     * for that specific row in the database.
     */
    private Uri insertUserInfo(Uri uri, ContentValues values) {

        // Check that the username is not null
        String username = values.getAsString(ChargerPointsContract.UserInfoEntry.COLUMN_USERNAME);
        if (username == null) {
            throw new IllegalArgumentException("Username Required");
        }

        // Check that the password is valid
        String password = values.getAsString(ChargerPointsContract.UserInfoEntry.COLUMN_PASSWORD);
        if (password == null) {
            throw new IllegalArgumentException("Password Required");
        }

        //Get writable database
        SQLiteDatabase database = mDbHelper.getWritableDatabase();

        //Insert the new user with the given values
        long id = database.insert(ChargerPointsContract.UserInfoEntry.TABLE_NAME, null, values);

        //If the id is -1, then the insertion failed. Log an error and return null
        if (id == -1) {
            Log.e(LOG_TAG, "Failed to insert row for " + uri);
            return null;
        }

        // Once we know the ID of the new row in the table,
        // return the new URI with the ID appended to the end of it
        return ContentUris.withAppendedId(uri, id);
    }

    /**
     * Insert a coupon into the database with the given content values. Return the new content URI
     * for that specific row in the database.
     */
    private Uri insertCouponInfo(Uri uri, ContentValues values) {

        // Check that the coupon is not null
        Byte coupon = values.getAsByte(ChargerPointsContract.CouponInfoEntry.COLUMN_COUPON);
        if (coupon == null) {
            throw new IllegalArgumentException("Coupon Required");
        }

        //Get writable database
        SQLiteDatabase database = mDbHelper.getWritableDatabase();

        //Insert the new coupon with the given values
        long id = database.insert(ChargerPointsContract.CouponInfoEntry.TABLE_NAME, null, values);

        //If the id is -1, then the insertion failed. Log an error and return null
        if (id == -1) {
            Log.e(LOG_TAG, "Failed to insert row for " + uri);
            return null;
        }

        // Once we know the ID of the new row in the table,
        // return the new URI with the ID appended to the end of it
        return ContentUris.withAppendedId(uri, id);
    }

    /**
     * Insert a coupon a user has into the database with the given content values. Return the new content URI
     * for that specific row in the database.
     */
    private Uri insertUserCouponsInfo(Uri uri, ContentValues values) {

        // Check that the userId is not null
        int userId = values.getAsInteger(ChargerPointsContract.UserCouponsEntry._ID);
        if (userId == 0) {
            throw new IllegalArgumentException("User ID required");
        }

        // Check that the name is not null
        int couponId = values.getAsInteger(ChargerPointsContract.UserCouponsEntry.COUPON_ID);
        if (couponId == 0) {
            throw new IllegalArgumentException("Coupon ID required");
        }

        boolean couponRedeemed = values.getAsBoolean(ChargerPointsContract.UserCouponsEntry.COLUMN_REDEEMED);
        if (couponRedeemed == true) {
            throw new IllegalArgumentException("Coupon already redeemed");
        }

        //Get writable database
        SQLiteDatabase database = mDbHelper.getWritableDatabase();

        //Insert the new pet with the given values
        long id = database.insert(ChargerPointsContract.UserCouponsEntry.TABLE_NAME, null, values);

        //If the id is -1, then the insertion failed. Log an error and return null
        if (id == -1) {
            Log.e(LOG_TAG, "Failed to insert row for " + uri);
            return null;
        }

        // Once we know the ID of the new row in the table,
        // return the new URI with the ID appended to the end of it
        return ContentUris.withAppendedId(uri, id);
    }

    /**
     * Insert a pet into the database with the given content values. Return the new content URI
     * for that specific row in the database.
     */
    private Uri insertPointsInfo(Uri uri, ContentValues values) {

        // Check that the name is not null
        int points = values.getAsInteger(ChargerPointsContract.PointsEntry.COLUMN_POINTS);
        if (points == 0) {
            throw new IllegalArgumentException("Points Required");
        }

        //Get writable database
        SQLiteDatabase database = mDbHelper.getWritableDatabase();

        //Insert the new pet with the given values
        long id = database.insert(ChargerPointsContract.PointsEntry.TABLE_NAME, null, values);

        //If the id is -1, then the insertion failed. Log an error and return null
        if (id == -1) {
            Log.e(LOG_TAG, "Failed to insert row for " + uri);
            return null;
        }

        // Once we know the ID of the new row in the table,
        // return the new URI with the ID appended to the end of it
        return ContentUris.withAppendedId(uri, id);
    }

    /**
     * Returns the MIME type of data for the content URI.
     */
    @Override
    public String getType(Uri uri) {
        return null;
    }
}
数据库助手

/*Database helper for Charger Points app. Manages database creation and version management.*/
public class ChargerPointsDbHelper extends SQLiteOpenHelper {

    public static final String LOG_TAG = ChargerPointsDbHelper.class.getSimpleName();

    /* Name of the database file */

    private static final String DATABASE_NAME = "chargerPoints.db";

    /* Database version. If you change the database schema, you must increment the database version.*/

    private static final int DATABASE_VERSION = 1;

    /*Constructs a new instance of {@link ChargerPointsDbHelper}. @param context of the app */

    public ChargerPointsDbHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    /*This is called when the database is created for the first time.*/

    @Override

    public void onCreate(SQLiteDatabase db) {

        // Create a String that contains the SQL statement to create the User Info table

        String SQL_CREATE_USER_INFO_TABLE =  "CREATE TABLE " + UserInfoEntry.TABLE_NAME + " ("

                + UserInfoEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "

                + UserInfoEntry.COLUMN_USERNAME + " TEXT NOT NULL, "

                + UserInfoEntry.COLUMN_PASSWORD + " TEXT NOT NULL);";

        // Create a String that contains the SQL statement to create the Coupon Info table

        String SQL_CREATE_COUPON_INFO_TABLE =  "CREATE TABLE " + CouponInfoEntry.TABLE_NAME + " ("

                + CouponInfoEntry.COUPON_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "

                + CouponInfoEntry.COLUMN_COUPON + " BLOB NOT NULL);";

        // Create a String that contains the SQL statement to create the Points table

        String SQL_CREATE_POINTS_TABLE =  "CREATE TABLE " + PointsEntry.TABLE_NAME + " ("

                + PointsEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "

                + PointsEntry.COLUMN_POINTS + " INTEGER NOT NULL);";

        // Create a String that contains the SQL statement to create the UserCoupons table

        String SQL_CREATE_USER_COUPONS_TABLE =  "CREATE TABLE " + UserCouponsEntry.TABLE_NAME + " ("

                + UserCouponsEntry._ID + " INTEGER NOT NULL, "

                + UserCouponsEntry.COUPON_ID + " INTEGER NOT NULL, "

                + UserCouponsEntry.COLUMN_REDEEMED + " BOOLEAN NOT NULL);";

        // Execute the SQL statement

        db.execSQL(SQL_CREATE_USER_INFO_TABLE);

        db.execSQL(SQL_CREATE_COUPON_INFO_TABLE);

        db.execSQL(SQL_CREATE_POINTS_TABLE);

        db.execSQL(SQL_CREATE_USER_COUPONS_TABLE);

    }

    /*This is called when the database needs to be upgraded.*/

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // The database is still at version 1, so there's nothing to do be done here.
    }
}
登录活动

(很抱歉,这里有一个链接)


尝试卸载应用程序,以便删除创建的数据库。清理并重新安装应用程序,或将数据库版本升级到2。

当我在我的计算机上查找数据库文件时
你在哪里查找?怎么做?数据库(由deault)未公开。它是在应用程序的私人空间中创建的。除非你没有一个根设备,否则你无法将它从那里取出。如果您正在使用IDE,只需在通常的位置(
/data/data/…
)即可找到它。移动到realm,其速度更快、效率更高且易于使用。