Hi I'm new to Android Java and SQLite, I'm trying to make an onClick listener change the value in the column from 1 to 2 but I'm confused about what I need to do. I tried doing some research on it but seem to get the basic way of updating your entries you added. Can anyone help me with this?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (database.updateReserved() == 1) {
database.updateReserved(reserved);
}
}
});
public void updateReserved(Integer reserved){
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("reserved",reserved);
String tableName="cars"; //Table Name
db.update(tableName , contentValues, "=" + reserved,null) ;
}
If you want to make sure that only rows with reserved = 1 will be updated, change updateReserved() so that both the current value and the new value of reserved are passed as arguments.
So, in the 3d argument of update(), which is the WHERE clause, pass the current value:
public void updateReserved(int oldReserved, int newReserved) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("reserved", newRreserved);
String tableName = "cars";
db.update(tableName, contentValues, "reserved = ?", new String[] {String.valueOf(oldReserved)}) ;
}
Now you can simplify the click listener like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
database.updateReserved(1, reserved);
}
});
Related
So, in my app you have to add eletrical equipment to every room in the house so it can measure how much energy you spend and etc.
What I want is when I click the button to remove a specific equipment, that equipment will be deleted from the database where it was stored, and this would be with only the name of the equipment as entry.
I have a code but when I hit the remove button the app kinda crashes and goes back to the home activity.
Can someone help pls?
That's the button:
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button2.setVisibility(View.GONE);
tableLayout1.setVisibility(View.GONE);
imageView1.setVisibility(View.GONE);
textView12.setVisibility(View.GONE);
DatabaseOperations DOP;
String equipamento;
equipamento = textView12.getText().toString();
DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getUserInfo(DOP, equipamento);
CR.moveToFirst();
DOP.deleteEquip(DOP, equipamento);
Toast.makeText(getBaseContext(),"O equipamento foi removido com sucesso.", Toast.LENGTH_LONG).show();
}
});
And this is the class:
public Cursor getUserInfo (DatabaseOperations DOP, String equipamento){
SQLiteDatabase SQ = DOP.getReadableDatabase();
String selection = TableData.TableInfo.EQUIPAMENTO +" LIKE ?";
String coloumns[] = {TableData.TableInfo.POTENCIA, TableData.TableInfo.QUANT, TableData.TableInfo.HORAS, TableData.TableInfo.SIMULT};
String args [] = {equipamento};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, selection, args, null, null, null);
return CR;
}
public void deleteEquip(DatabaseOperations DOP, String equipamento){
String selection = TableData.TableInfo.EQUIPAMENTO;
String args[] = {equipamento};
SQLiteDatabase SQ = DOP.getWritableDatabase();
SQ.delete(TableData.TableInfo.TABLE_NAME, selection, args);
}
#EngWatt this code is in the DBHelper Class you will need to change the rowid to reflect the name of the item you want to delete. I assume that is equipamento
We hope you have a MVP design to make all this easy
/* Delete a record from database table named "TABLE_INFO" */
/* based on the selected records id in Col_ID*/
public void deleteDBRow(String rowid){
db = this.getWritableDatabase();
db.delete(TABLE_INFO, Col_ID + " = ?", new String[] { rowid });
db.close();
return;
}
I have a method in my activity class which should print a random role to the player (stores in an SQLite database). I am getting a success message but it is not being carried out. I only have 1 record in my SQLite database so far and will be adding a while loop after to populate each row.
This is my my activity class:
public class StartGame extends AppCompatActivity implements View.OnClickListener {
DatabaseHelper myDb;
Button btnRoles;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startgame);
myDb = new DatabaseHelper(this);
btnRoles = (Button) findViewById(R.id.btnAssignRoles);
assignRoles();
}
public String RandomNumber() {
List < String > roles = Arrays.asList("Mafia", "Mafia", "Angel", "Detective", "Civilian", "Civilian", "Civilian");
Collections.shuffle(roles);
return roles.get(0);
}
public void assignRoles() {
btnRoles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
boolean isUpdated = myDb.updateRole(RandomNumber().toString());
if (isUpdated == true)
Toast.makeText(StartGame.this, "Roles assigned, keep them secret!", Toast.LENGTH_LONG).show();
else
Toast.makeText(StartGame.this, "UNSUCCESSFUL!", Toast.LENGTH_LONG).show();
}
}
}
);
}
And this is the method in my Database Helper class:
public boolean updateRole(String role){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_ROLE, role);
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
return true;
}
What am I doing wrong?
You got an error in this line:
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
You are updating all the rows in the table where Role = {role} to have the column Role the value {role}. So obviously this will have no effect.
You need to have some thing like id and use that in your where statement, some thing like this:
db.update(TABLE_NAME, contentValues, "id =?", new String[] {id});
I'm trying to create something like favorite thing in my app
I have made activity with restaurant which can be set as favorite, I've made imagebutton for making restaurant favorite and it's working, cause I have second activity where list is getting info from database and everything is ok. Titles match, adresses match cities too, so database should match too.
I have problem with changing OnClickListener, I want to use info from database to check if String called "database_name" is matching with any string from database.
There is code for it :
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selection = {FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE};
favoriteButton = (ImageButton) findViewById(R.id.favoriteRestaurant);
Cursor cursor = db.query(FeedReaderContract.FeedEntry.TABLE_NAME, selection,
null, null, null, null, null);
if(cursor.getCount() != 0) {
cursor.moveToFirst();
do {
if(cursor.getString(0).toLowerCase() == database_name.toLowerCase()){
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
isFavorite = 1;
}
} while (cursor.moveToNext());
}
It's changing background of this favorite button to filled heart, at least it's supposed to do so. In default it's not filled.
Then I'm changing onClickListener, code for it looks like this :
if(isFavorite == 0) {
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isntFavorite();
}
});
} else {
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFavorite();
}
});
}
isFavorite look like this :
private void isFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoriteu));
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE + " LIKE ?";
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selectionArgs = new String[] { database_name };
db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isntFavorite();
}
});
}
And code for isntFavorite looks like this:
private void isntFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, restaurantName);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ADRESS, restaurantAdress);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CITY, restaurantCity);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE, database_name);
long newRowId;
newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,
null, values);
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFavorite();
}
});
}
The thing is that it's always changing onClickListener to isntFavorite and it's not changing image background to filled heart, even if there is matching data in database. I was trying to change matching title from database to title from activity, and I was sure that they're matching cause there was in list title with the same String as title from activity where I was trying to match them.
You don't need to change OnclickListener just create a boolean to save the state:
final boolean state = isFavorite == 0;
favoriteButton.setOnClickListener(new View.OnClickListener() {
boolean mState = state;
#Override
public void onClick(View v) {
if(mState)isntFavorite();
else isFavorite();
mState=!mState;
}
});
private void isFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoriteu));
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE + " LIKE ?";
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selectionArgs = new String[] { database_name };
db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
}
private void isntFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, restaurantName);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ADRESS, restaurantAdress);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CITY, restaurantCity);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE, database_name);
long newRowId;
newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,
null, values);
}
I am developing an android app, and i want to display the primary key in the textview so that every-time I edit a textfield, I will be using the primary key to update.can anyone help me with this? below is the inserting of data in the sqlite. My problem is how to get the primary key...
public class UsedataActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
ImageButton evsave;
EditText evname;
EditText evtime;
EditText evdate;
EditText evcode;
TextView evadmin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onetoone);
evsave = (ImageButton)findViewById(R.id.event_save);
evname = (EditText)findViewById(R.id.eventname);
evtime = (EditText)findViewById(R.id.time1);
evdate = (EditText)findViewById(R.id.eventdate);
evcode = (EditText)findViewById(R.id.eventcode);
evadmin = (TextView)findViewById(R.id.adminname_1to1);
evsave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Events addev =
new Events(evname.getText().toString(),evcode.getText().toString(),evdate.getText().toString(),Integer.parseInt(evtime.getText().toString()),evadmin.getText().toString());
db.addEvents(addev);
Toast.makeText(getApplicationContext(), "Event: "+ evname.getText()+" successfully save",
Toast.LENGTH_SHORT).show();
}
});
}
database handler class:
public void addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close();
}
As it can be observed from the docs for the SQLiteDatabase, db.insert will return the id of the newly created object. Just make addEvents return it (instead of being `void).
PS: Please paste code in edits of the question, not in comments. In comments they really look awful!
EDIT
public long addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
long id = db.insert(TABLE_EVENTS, null, values);
db.close();
return id;
}
And then:
long id = db.addEvents(addev);
Toast.makeText(getApplicationContext(),
"Event with id: "+ id + " successfully saved",
Toast.LENGTH_SHORT).show();
public void updateEntry(long id, String perce)
{
ContentValues editCon = new ContentValues();
editCon.put(KEY_PERCENT, perce);
open();
db.update(DATABASE_TABLE, editCon, "_id=" + id, null);
close();
}
Above is my code inside database and it is called to update 1st entry in my activity as
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
long i=0;
objectDBAdapter.updateEntry(i, "2%" );
}
});
My problem is even if update method is called no change occurs in database. Please tell me where is the problem.The same update code works in a sample application, but i want to call it as stated.