动态创建SQLite TABLES?

时间:2017-02-21 16:16:36

标签: android database sqlite android-sqlite

我有一个流视频应用。在我的应用程序中,我有DB和一个表" SAVED PLAYLISTS"。当用户点击按钮" SAVE PLAYLIST"它将播放列表保存到该TABLE中。 我现在需要创建新的TABLE,用户点击视频" SAVE VIDEO"并选择播放列表保存的位置,如果没有播放列表,则需要创建一个播放列表。所以它是这样的:

TABLE SAVED PLAYLISTS

TABLE_ID | TABLE_NAME | TABLE_DATA
         |            |


TABLE SAVED VIDEOS

VIDEO_ID | VIDEO_NAME | VIDEO_DATA | PLAYLIST_ID 
         |            |

我的SAVED PLAYLISTS表有以下代码:

    private static final String SELECT_PLAYLISTS_SQL_QUESTION = "SELECT * FROM " + DatabaseDefinition.TABLE_SAVED_PLAYLISTS;

 public void insertNewPlaylist(String playlistName, String playlistData) {
        ContentValues contentValuesNew = new ContentValues();
        contentValuesNew.put(DatabaseDefinition.COLUMN_PLAYLIST_NAME, playlistName);
        contentValuesNew.put(DatabaseDefinition.COLUMN_PLAYLIST_DATA, playlistData);
        try {
            openWritableInstance();
            databaseInstance.insert(DatabaseDefinition.TABLE_SAVED_PLAYLISTS, null, contentValuesNew);
            closeDatabaseInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 public List<DatabasePlaylistObject> getPlaylists() {
        List<DatabasePlaylistObject> resultList = new ArrayList<DatabasePlaylistObject>();
        try {
            openReadableInstance();
            Cursor cursorNew = databaseInstance.rawQuery(SELECT_PLAYLISTS_SQL_QUESTION, null);
            if (cursorNew.moveToFirst()) {
                do {
                    DatabasePlaylistObject tempPlaylistObject = new DatabasePlaylistObject();
                    tempPlaylistObject.setId(cursorNew.getInt(0));
                    tempPlaylistObject.setPlaylistName(cursorNew.getString(1));
                    tempPlaylistObject.setPlaylistData(cursorNew.getString(2));
                    resultList.add(tempPlaylistObject);
                }
                while (cursorNew.moveToNext());
            }
            closeDatabaseInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

 public void removePlaylist(int playlistId) {
        try {
            openWritableInstance();
            databaseInstance.delete(DatabaseDefinition.TABLE_SAVED_PLAYLISTS, DatabaseDefinition.COLUMN_ID_PLAYLIST + "=" + playlistId, null);
            closeDatabaseInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

在MainActivity中:

 private View.OnClickListener btnSavePlaylistListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (gridCustomAdapter.getPlaylistId() == -1) {
                String playlistDataTemp = new Gson().toJson(gridCustomAdapter.getCurrentPlaylist());
                dbHandler.insertNewPlaylist(currentSearchContent, playlistDataTemp);
                onSwipeRight();
            }
        }
    };

0 个答案:

没有答案