在将记录插入SQLite表之前检查记录是否存在

时间:2018-05-24 17:47:05

标签: java android android-contentprovider

我试图为Android应用程序的SQLite数据库实现select查询,以检查表中是否存在电影的id,如果它不存在于表中则决定插入它,如果它不存在则不插入它#39 ; s之前已经插入过 所以这是我在MoviesProvider.java中编写的代码:

public class MoviesProvider extends ContentProvider {

    public static final int CODE_MOVIES = 200;
    public static final int CODE_MOVIES_WITH_ID = 201;

    private static final UriMatcher sUriMatcher = buildUriMatcher();

    MoviesDbHelper mOpenHelper;

    public static UriMatcher buildUriMatcher() {

        final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
        final String authority = MoviesContract.CONTENT_AUTHORITY;

        matcher.addURI(authority, MoviesContract.PATH_MOVIES, CODE_MOVIES);

        matcher.addURI(authority, MoviesContract.PATH_MOVIES + "/#", CODE_MOVIES_WITH_ID);

        return matcher;
    }

    @Override
    public boolean onCreate() {
        mOpenHelper = new MoviesDbHelper(getContext());
        return true;
    }


    @Override
    public Uri insert(@NonNull Uri uri, ContentValues values) {

        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();

        int match = sUriMatcher.match(uri);
        Uri returnUri;

        switch (match) {

            case CODE_MOVIES: {

                String bookmarksMovieId = uri.getLastPathSegment();
                String[] selectionArguments2 = new String[]{bookmarksMovieId};

                String Query = "SELECT * FROM" + MoviesContract.MoviesEntry.TABLE_NAME
                        + "WHERE" + MoviesContract.MoviesEntry.COLUMN_SHASHA_ID + "=" + selectionArguments2;
                Cursor cursor = db.rawQuery(Query, null);
                if (cursor.getCount() <= 0) {
                    cursor.close();
                } else {

                    long id = db.insert(TABLE_NAME, null, values);
                    if (id > 0) {
                        returnUri = ContentUris.withAppendedId(MoviesContract.MoviesEntry.CONTENT_URI, id);
                    } else {
                        throw new android.database.SQLException("Failed to insert row into " + uri);
                    }

                    break;
                }
            }

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);

        return returnUri;
    }

}

MoviesContract.java:

public class MoviesContract {

    public static final String CONTENT_AUTHORITY = "giga.net.world.GN";

    public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);

    public static final String PATH_MOVIES = "shasha";

    public static final class MoviesEntry implements BaseColumns {

        public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
                .appendPath(PATH_MOVIES)
                .build();

        public static final String TABLE_NAME = "shasha";

        public static final String COLUMN_SHASHA_ID = "id";
        public static final String COLUMN_SHASHA_TITLE = "title";
        public static final String COLUMN_SHASHA_CATEGORY = "category";

        public static Uri buildMoviesUriWithId(long id) {
            return CONTENT_URI.buildUpon()
                    .appendPath(Long.toString(id))
                    .build();
        }

    }
}

MoviesDBHelper.java:

public class MoviesDbHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "shasha.db";

private static final int DATABASE_VERSION = 3;

public MoviesDbHelper(Context context) {

    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        final String SQL_CREATE_MOVIES_TABLE =

                "CREATE TABLE " + MoviesContract.MoviesEntry.TABLE_NAME + " (" +

                        MoviesContract.MoviesEntry._ID               + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        MoviesContract.MoviesEntry.COLUMN_SHASHA_ID + " INTEGER NOT NULL, "                 +
                        MoviesContract.MoviesEntry.COLUMN_SHASHA_TITLE + " TEXT NOT NULL, "                 +
                        MoviesContract.MoviesEntry.COLUMN_SHASHA_CATEGORY + " TEXT NOT NULL);";

        sqLiteDatabase.execSQL(SQL_CREATE_MOVIES_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MoviesContract.MoviesEntry.TABLE_NAME);
        onCreate(sqLiteDatabase);

    }
}

最后是onClick方法:

public void onClickFavorite(View view) {

        ContentValues contentValues = new ContentValues();
        contentValues.put(MoviesContract.MoviesEntry.COLUMN_SHASHA_ID, MovieId);
        contentValues.put(MoviesContract.MoviesEntry.COLUMN_SHASHA_TITLE, MovieTitle);
        contentValues.put(MoviesContract.MoviesEntry.COLUMN_SHASHA_CATEGORY, MovieCategory);

        Uri uri = getContentResolver().insert(MoviesContract.MoviesEntry.CONTENT_URI, contentValues);

        if (uri != null) {
            Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show();
        }

    }

问题是当我点击任何电影里面的收藏按钮时,应用程序刚崩溃,我从logcat收到以下消息:

  

无法执行android的方法:onClick引起:SQL(查询)   错误或丢失数据库。(接近&#34; FROMshashaWHEREid&#34;:语法错误   (代码1):,编译时:SELECT *   FROMshashaWHEREid = [Ljava.lang.String; @ cdbe7d7)

为什么我得到这样的id:

  

WHEREid = [Ljava.lang.String; @ cdbe7d7)

2 个答案:

答案 0 :(得分:2)

您需要在查询构建字符串上添加一些空格。

String Query = "SELECT * FROM" + MoviesContract.MoviesEntry.TABLE_NAME
                    + "WHERE" + 

就是这一部分,

{{1}}

答案 1 :(得分:1)

您需要在每个单词之间添加空格:

String Query = "SELECT * FROM " + MoviesContract.MoviesEntry.TABLE_NAME + " WHERE " + MoviesContract.MoviesEntry.COLUMN_SHASHA_ID + " = " + selectionArguments2;