Java Android-基于ToggleButton图像更改SQLite值
我想制作一个报价应用程序,其中显示报价、作者和fav按钮 我有一个自定义的ListView,它有两个文本视图和一个切换按钮 我正在使用带有预填充数据的SQLite(因此我已经拥有了所有数据) 我可以使用SimpleCursorAdapter用我的报价(来自报价表)和作者(来自作者表)填充我的2个文本视图 问题是,我有一个ToggleButton,它有:Java Android-基于ToggleButton图像更改SQLite值,java,android,sqlite,listview,android-studio,Java,Android,Sqlite,Listview,Android Studio,我想制作一个报价应用程序,其中显示报价、作者和fav按钮 我有一个自定义的ListView,它有两个文本视图和一个切换按钮 我正在使用带有预填充数据的SQLite(因此我已经拥有了所有数据) 我可以使用SimpleCursorAdapter用我的报价(来自报价表)和作者(来自作者表)填充我的2个文本视图 问题是,我有一个ToggleButton,它有: 未选择灰色心脏图像(值0) 选定时的红心图像(值1) 我想要的是 当用户单击灰色心脏图像(fav按钮)时,图像将变为红色心脏图像,并将SQ
- 未选择灰色心脏图像(值0)
- 选定时的红心图像(值1)
- 当用户单击灰色心脏图像(fav按钮)时,图像将变为红色心脏图像,并将SQLite中的fav表从0更新为1
- 当用户单击红色心脏图像(fav按钮)时,图像将变为灰色心脏图像,并将SQLite中的fav表从1更新为0
- 当用户退出并再次转到我的应用程序时。我希望用户之前已经喜欢的引用(值1)仍然具有红心图像
public class DatabaseOpenHelper extends SQLiteAssetHelper {
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";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
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();
}
/** Start DB from here */
/** 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 fav) {
ContentValues args = new ContentValues();
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);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
@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;
}
quotesList = (ListView) findViewById(R.id.quotesList);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.genre_array, R.layout.spinner_item);
// Specify the layout to use when the list of choices appears
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//ALL
if (id == 0) {
populateListView();
}
//Entrepreneur
else if (id == 1) {
populateListViewEntrepreneur();
}
//Love
else if (id == 2) {
populateListViewLove();
}
//Work
else if (id == 3) {
populateListViewWork();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Call Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
//Custom Image Back Button
toolbar.setNavigationIcon(R.drawable.back_button);
setSupportActionBar(toolbar);
//To make the title from Android Manifest appear, comment the code below
getSupportActionBar().setDisplayShowTitleEnabled(false);
//Make the app only portrait
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.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewEntrepreneur() {
String testing = "Entrepreneur";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewLove() {
String testing = "Love";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewWork() {
String testing = "Work";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
引用\u列表视图(自定义列表视图)
quoteActivity.java
public class DatabaseOpenHelper extends SQLiteAssetHelper {
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";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
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();
}
/** Start DB from here */
/** 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 fav) {
ContentValues args = new ContentValues();
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);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
@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;
}
quotesList = (ListView) findViewById(R.id.quotesList);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.genre_array, R.layout.spinner_item);
// Specify the layout to use when the list of choices appears
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//ALL
if (id == 0) {
populateListView();
}
//Entrepreneur
else if (id == 1) {
populateListViewEntrepreneur();
}
//Love
else if (id == 2) {
populateListViewLove();
}
//Work
else if (id == 3) {
populateListViewWork();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Call Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
//Custom Image Back Button
toolbar.setNavigationIcon(R.drawable.back_button);
setSupportActionBar(toolbar);
//To make the title from Android Manifest appear, comment the code below
getSupportActionBar().setDisplayShowTitleEnabled(false);
//Make the app only portrait
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.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewEntrepreneur() {
String testing = "Entrepreneur";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewLove() {
String testing = "Love";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewWork() {
String testing = "Work";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
public class quotes活动扩展了appcompative活动{
ListView引用列表;
数据库OpenHelper myDbHelper;
arraylistarrquotes;
QuotesAdapter适配器;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper=新数据库OpenHelper(此);
试一试{
//检查应用程序路径中是否存在数据库,如果不存在,请从资产复制数据库
myDbHelper.create();
}捕获(ioe异常ioe){
抛出新错误(“无法创建数据库”);
}
试一试{
//打开数据库
myDbHelper.open();
myDbHelper.getWritableDatabase();
}捕获(SQLException sqle){
抛出sqle;
}
quotesList=(ListView)findViewById(R.id.quotesList);
微调器微调器=(微调器)findViewById(R.id.Spinner);
//使用字符串数组和默认微调器布局创建ArrayAdapter
ArrayAdapter spinnerAdapter=ArrayAdapter.createFromResource(此,
R.array.genre_数组,R.layout.spinner_项);
//指定显示选项列表时要使用的布局
spinnerAdapter.setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项);
//将适配器应用于微调器
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(新的AdapterView.OnItemSelectedListener(){
@凌驾
已选择公共视图(AdapterView父视图、视图视图、整型位置、长id){
//全部
如果(id==0){
populateListView();
}
//企业家
else if(id==1){
PopulateListViewEnterpriser();
}
//爱
else if(id==2){
大众主义爱情();
}
//工作
else if(id==3){
populateListViewWork();
}
}
@凌驾
未选择公共无效(AdapterView父级){
}
});
//调用工具栏
工具栏=(工具栏)findViewById(R.id.tool\u栏);
//自定义图像返回按钮
工具栏.setNavigationIcon(R.drawable.back_按钮);
设置支持操作栏(工具栏);
//要显示Android清单中的标题,请注释下面的代码
getSupportActionBar().setDisplayShowTitleEnabled(false);
//将应用程序设置为仅纵向
setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u Picture);
}
私有void populateListView(){
Cursor Cursor=myDbHelper.getAllUsers();
String[]from=新字符串[]{myDbHelper.COLUMN_QUOTES,myDbHelper.COLUMN_AUTHOR};
int[]to=newint[]{R.id.txtQuote,R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter=新的SimpleCursorAdapter(getBaseContext(),R.layout.quotes_listview,cursor,from,to,0);
setAdapter(myCursorAdapter);
}
私有void populateListViewEnterpriser(){
字符串测试=“企业家”;
Cursor Cursor=myDbHelper.getSure(测试);
String[]from=新字符串[]{myDbHelper.COLUMN_QUOTES,myDbHelper.COLUMN_AUTHOR};
int[]to=newint[]{R.id.txtQuote,R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter=新的SimpleCursorAdapter(getBaseContext(),R.layout.quotes_listview,cursor,from,to,0);
setAdapter(myCursorAdapter);
}
私人空间populateListViewLove(){
字符串测试=“爱”;
Cursor Cursor=myDbHelper.getSure(测试);
String[]from=新字符串[]{myDbHelper.COLUMN_QUOTES,myDbHelper.COLUMN_AUTHOR};
int[]to=newint[]{R.id.txtQuote,R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter=新的SimpleCursorAdapter(getBaseContext(),R.layout.quotes_listview,cursor,from,to,0);
setAdapter(myCursorAdapter);
}
私有void populateListViewWork(){
字符串测试=“工作”;
Cursor Cursor=myDbHelper.getSure(测试);
String[]from=新字符串[]{myDbHelper.COLUMN_QUOTES,myDbHelper.COLUMN_AUTHOR};
int[]to=newint[]{R.id.txtQuote,R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter=新的SimpleCursorAdapter(getBaseContext(),R.layout.quotes_listview,cursor,from,to,0);
setAdapter(myCursorAdapter);
}