I am trying to get the checkbox I created in a custom adapter for a list to update the database upon clicking on it. I implemented the onclicklistener on the checkbox inside the customAdapter (code below). I also added a Toast to check if it works. The problem is that the Toast displays the right information for each row (the name of the item i click on); however the database doesn't get updated.
datasource = new MySQLiteHelper((AssTasksActivity) context);
CB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Task Ta = task; //Task is an object with a separate class that is stored in the sqlite db.
if(CB.isChecked()){
Ta.setState(0);
datasource.updateTask(Ta);
//Toast T;
Toast.makeText(context, Ta.getTaskName(),
Toast.LENGTH_LONG).show();
}
else{
Ta.setState(1);
datasource.updateTask(Ta);
Toast.makeText(context, Ta.getTaskName(),
Toast.LENGTH_LONG).show();
}
}
});
Here is the sqlite code for the update
public int updateTask(Task task){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.T_COLUMN_TASK_ID, task.getId());
values.put(MySQLiteHelper.T_COLUMN_TASKNAME, task.getTaskName());
values.put(MySQLiteHelper.T_COLUMN_DESCRIPTION, task.getDescription());
values.put(MySQLiteHelper.T_COLUMN_STATE, task.getState());
values.put(MySQLiteHelper.T_COLUMN_PK, task.getAssignmentId());
values.put(MySQLiteHelper.T_COLUMN_ERROR_DESCRIPTION, task.getErrorDescription());
return database.update(TABLE_TASKS, values, T_COLUMN_ROWID + " = ?",
new String[] { String.valueOf(task.getId()) });
}
T_COLUMN_ROWID in the return statement should be T_COLUMN_TASK_ID. Silly mistake.
Related
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.
I have an sqlite database that collects data from the user and can delete it as well.
Here is it being created:
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, DATA TEXT UNIQUE) ");
Here's the code for the adding data and removing data
public boolean insertData(String data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cValues = new ContentValues();
cValues.put(Col_2, data);
long result = db.insert(TABLE_NAME, null, cValues);
if (result == -1)
return false;
else
return true;
}
public boolean deleteData(String data){
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_NAME, "DATA = ?", new String[]{data});
ContentValues cValues = new ContentValues();
if (result == 0)
return false;
else
return true;
}
Here is the java button im trying to use
public void changeData(){
favBtn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = myDB.insertData(textView.getText().toString());
if(isInserted == true)
Toast.makeText(randomApp.this, "Added Data", Toast.LENGTH_LONG).show();
else
Toast.makeText(randomApp.this, "Data was deleted", Toast.LENGTH_LONG).show();
myDB.deleteData(textView.getText().toString());
}
}
);
}
The issue is that when this button is clicked it adds data but then will not remove said data. It will just continue playing the "added data" toast and add said data to the database- there is a unique constraint with the data
column but I'm not really sure what I'm doing wrong or missing as I understand it should not be added twice. It should remove the data if that is already added and vice versa.
According to your code the delete data code will always execute. And the data you are inserting will immediately deleted, hence the unique constraint won't break ever. You didn't put any {} in your else case and it contains two statements; first one considered as the statement inside else and second one will be considered as a statement outside the if and else case. So for fixing this issue you need to put {} properly. (Personal opinion : Try to put {} in if and else cases even if there is only one statement)
You should change that to:
if(isInserted == true)
{
Toast.makeText(randomApp.this, "Added Data", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(randomApp.this, "Data was deleted", Toast.LENGTH_LONG).show();
myDB.deleteData(textView.getText().toString());
}
You are calling myDB.insertData on every click first, for every insert it will return true, so isInserted will be true always, thats why do you add multiple times the same data. Try this:
private isInserted = false;
public void changeData(){
favBtn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(!isInserted){
Toast.makeText(randomApp.this, "Added Data", Toast.LENGTH_LONG).show();
myDB.insertData(textView.getText().toString());
}
else{
Toast.makeText(randomApp.this, "Data was deleted", Toast.LENGTH_LONG).show();
myDB.deleteData(textView.getText().toString());
}
isInserted = !isInserted;
}
}
);
}
This question already exists:
how to insert data into sq-lite database at run-time [closed]
Closed 9 years ago.
I built an application that uses sq-lite database and within the application at run-time i made a button that when pressed added a new Edit-Text i'm wondering how can i save the values in the new Edit-Text into my database? please help me
Use this method :
public long saveData(Context context, String editTextValue) {
long x = -1;
appDb = new AppDatabase(context);
sqliteDb = appDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("monthOfBirth", editTextValue);
try {
if (sqliteDb.isOpen()) {
x = sqliteDb.insert("password", null, values);
if (x >= 0)
{
Toast.makeText(context, "Password Save", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
return x;
}
Call this method in your button's onClickListener()
button.setOnCLickListener(new View.OnClickListener())
{
#override
public void onClick(View v)
{
if(editText.getText().toString.equals(""))
{
Toast.makeText(context, "Fill Value first.", Toast.LENGTH_SHORT).show();
return;
}
saveData(YourActivity.this, editText.getText().toString());
}
}
Have you created the class extending SQLiteOpenHelper? If you have it, then use the constructor and get an object of this class:
dbHelper = new SQLiteHelper(context, getString(R.string.db_name_dev), null, DB_VERSION);
And then for example:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("term", term);
db.insert("Search", null, cv);
Simply make a String which contains insert query of SQL. Then call the method
db.execSQL(sql);
on your datebase refence variable.
String sql =
"INSERT INTO <TABLE_NAME> VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);
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();
I want my Onclick method that is used used to insert data into a database to first check if data exist. If there is data, a toast message appears. how can I accomplish this. My OnClick is below. I just it to verify there is a username and password. If there is, the user receives a toast.
#Override
public void onClick (View v) {
rUsername = rName.getText().toString();
rPasscode = rCode.getText().toString();
RegDetails regDetails = new RegDetails();
regDetails.setrName(bundleRegName);
regDetails.setpCode(bundleRegCode);
if(v.getId()==R.id.rtn_button){
finish();
}else if(v.getId()==R.id.reg_button){
insertCredentials(regDetails);
}
}
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
sqliteDB.close();
finish();
}
}
The sqliteDB.insert return long value on success and -1 on error. The long value indicates the row number for newly inserted row in db. You can check this return value and display toast accordingly.
Please look at the detailed explanation here, http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)
In short, modify your code to be like this,
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
if(affectedColumnid != -1){
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
}else{
// Display error dialog or smthg
}
sqliteDB.close();
finish();
}
Read your database . If cursor.getCount() >0 thats mean data exists.
Cursor cursor = getDbEntries();
if( cursor.getCount() > 0 ){
// data exists
}
else{
// data doesnt exist
}