Updating my Column in SQLite with Android - android

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});

Related

onclick update value in a row in sqlite

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);
}
});

I can't insert data

I'm making an app to insert data. But when I click on add button by giving all the details. App return me to previous page
This is the way I create insert class
public class InsertStudent extends AppCompatActivity {
Button instudent;
DBHelper dbHelper;
EditText sName,sDOB,sAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_student);
instudent = findViewById(R.id.btninsert);
sName = findViewById(R.id.insertname);
sDOB = findViewById(R.id.insertdob)
;
sAddress = findViewById(R.id.insertaddress);
Below is the way I coded to insert data
instudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userName = sName.getText().toString();
String dateB = sDOB.getText().toString();
String addr = sAddress.getText().toString();
boolean count = dbHelper.addInfo(userName,dateB,addr );
if(count =true){
Toast.makeText(InsertStudent.this, "Inserted!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(InsertStudent.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
});
This is addinfo method in DBHelper class
public boolean addInfo(String stdName, String stdDOB, String stdAddress){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(UserProfile.Users.COLUMN_STDNAME, stdName);
contentValues.put(UserProfile.Users.COLUMN_DATEOFBIRTH, stdDOB);
contentValues.put(UserProfile.Users.TABLE_ADDRESS, stdAddress);
long result = sqLiteDatabase.insert(UserProfile.Users.TABLE_NAME, null, contentValues);
if(result==1)
return false;
else
return true;
}
}
The insert method of "SQLiteDatabase" class doesn't return the
count, it's returns the id of the inserted row. so you are checking
if return result is 1, it's a true process, but it's not a way to
check the insert method. It means you need to check if there is any
return result, your insert action performed successfully, but if
there is a problem, the application will crash.
Make sure you created the table that you want to insert data in it.

how sort listview filled with sqlite by last modified?

I'm absolute beginner.
I have a listview filled with sqlite table, I have two questions:
1- How can I sort this listview by last modified item ?
2- How can I make a button on my first page to open last modified item without going to listview !?
Here are my codes:
Its listview -
public class MainActivity extends ListActivity {
// Declare Variables
public static final String ROW_ID = "row_id";
private static final String TITLE = "title";
private ListView noteListView;
private CursorAdapter noteAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stopService(new Intent(MainActivity.this, MyService.class));
// Locate ListView
noteListView = getListView();
// Prepare ListView Item Click Listener
noteListView.setOnItemClickListener(viewNoteListener);
// Map all the titles into the ViewTitleNotes TextView
String[] from = new String[]{ TITLE };
int[] to = new int[]{ R.id.ViewTitleNotes };
// Create a SimpleCursorAdapter
noteAdapter = new SimpleCursorAdapter(MainActivity.this,
R.layout.list_zekr, null, from, to);
// Set the Adapter into SimpleCursorAdapter
setListAdapter(noteAdapter);
}
// Capture ListView item click
OnItemClickListener viewNoteListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// Open ViewNote activity
Intent viewnote = new Intent(MainActivity.this, CounterActivity.class);
viewnote.putExtra(ROW_ID, arg3);
startActivity(viewnote);
}
};
#Override
protected void onResume() {
super.onResume();
// Execute GetNotes Asynctask on return to MainActivity
new GetNotes().execute((Object[]) null);
}
#Override
protected void onStop() {
Cursor cursor = noteAdapter.getCursor();
// Deactivates the Cursor
if (cursor != null)
cursor.deactivate();
noteAdapter.changeCursor(null);
super.onStop();
}
// Create an options menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Menu Title
menu.add("ذکر جدید")
.setOnMenuItemClickListener(this.AddNewNoteClickListener)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return super.onCreateOptionsMenu(menu);
}
// Capture menu item click
OnMenuItemClickListener AddNewNoteClickListener = new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Open AddEditNotes activity
Intent addnote = new Intent(MainActivity.this, AddEditNotes.class);
startActivity(addnote);
return false;
}
};
// GetNotes AsyncTask
public class GetNotes extends AsyncTask<Object, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(MainActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
// Open the database
dbConnector.open();
return dbConnector.ListAllNotes();
}
#Override
protected void onPostExecute(Cursor result) {
noteAdapter.changeCursor(result);
// Close Database
dbConnector.close();
}
}
}
its my DatabaseConnector :
public class DatabaseConnector {
// Declare Variables
private static final String DB_NAME = "database";
private static final String TABLE_NAME = "tablenotes";
private static final String TITLE = "title";
private static final String ID = "_id";
private static final String NOTE = "note";
private static final String COUNTS = "counts";
private static final String LIMITS = "limits";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase database;
private DatabaseHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseHelper(context, DB_NAME, null, DATABASE_VERSION);
}
// Open Database function
public void open() throws SQLException {
// Allow database to be in writable mode
database = dbOpenHelper.getWritableDatabase();
}
// Close Database function
public void close() {
if (database != null)
database.close();
}
// Create Database function
public void InsertNote(String title, String note, String counts, String limits) {
ContentValues newCon = new ContentValues();
newCon.put(TITLE, title);
newCon.put(NOTE, note);
newCon.put(COUNTS, counts);
newCon.put(LIMITS, limits);
open();
database.insert(TABLE_NAME, null, newCon);
close();
}
// Update Database function
public void UpdateNote(long id, String title, String note, String counts, String limits) {
ContentValues editCon = new ContentValues();
editCon.put(TITLE, title);
editCon.put(NOTE, note);
editCon.put(COUNTS, counts);
editCon.put(LIMITS, limits);
open();
database.update(TABLE_NAME, editCon, ID + "=" + id, null);
close();
}
// Delete Database function
public void DeleteNote(long id) {
open();
database.delete(TABLE_NAME, ID + "=" + id, null);
close();
}
// List all data function
public Cursor ListAllNotes() {
return database.query(TABLE_NAME, new String[]{ ID, TITLE }, null,
null, null, null, TITLE);
}
// Capture single data by ID
public Cursor GetOneNote(long id) {
return database.query(TABLE_NAME, null, ID + "=" + id, null, null,
null, null);
}
}
thanks in advance.
UPDATE !
Ok, I Created a Column in my table with name of "time"
and I can insert the time as INTEGER to it like this: 20160516100740
So now every Row of table has a time like that, NOW WHAT CAN I DO ?
Update !
Ok, I wrote this inside my list activity (MainActivity.java)
but its not working : (
public Cursor listAllSortedNotes() {
String selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY time DESC";
return database.rawQuery(selectQuery, null);
You need to add a field in the database which should be a date string (Sample: yyyy-MM-dd HH:mm:ss). And when you update the data, update it with current date and time. Then you can use select query to get the recent update data by using
SELECT *
FROM Table
ORDER BY datetime (dateColumn) DESC
In your case you can do something like this.
public Cursor listAllSortedNotes() {
String selectQuery = "SELECT * FROM "+ TABLE_NAME + " ORDER BY datetime(dateColumn) DESC";
return database.rawQuery(selectQuery, null);
}

Setting OnClickListener not working

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);
}

display primary key after inserting in database

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();

Categories

Resources