Check Db column data - android

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
}

Related

Static Method error on fetching data in Android Studio through Sqlite

I'm new in this programming in Android Studio.I have a problem with this code that I write from a tutorial.
public void onClick(View v){
if (editusername.getText().toString().trim().length() == 0 || editpassword.getText().toString().trim().length() ==0) {
Toast.makeText(getApplicationContext(), "Semua Kolom harus Diisi", Toast.LENGTH_SHORT).show();}
else try{ String username = editusername.getText().toString().trim();
String password = editpassword.getText().toString().trim();
String query = "Select * From User where username = '"+username+"'";
if(DbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
DbManager.insert(username, password);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
e.printStackTrace();
}
In the 'fetch' and 'insert' Method there was an error of 'cannot be referenced as static method'.
This is the code in the corresponding class DbManager
public void insert(String usn, String pwd) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.USERNAME, usn);
contentValue.put(SQLiteHelper.PASSWORD, pwd);
this.database.insert(SQLiteHelper.TABLE_NAME_USER, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_USER, new String[]{SQLiteHelper._ID, SQLiteHelper.USERNAME, SQLiteHelper.PASSWORD}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
You never created an instance of the DbManager class.
Adding an DbManager manager = new DbManager(); and then using manager.fetch() and manager.insert(params...) should solve your problem.
Doing Class.Method() is only possible if Method() was declares as public static void Method(). If it wasn't, you need to first create an object, then call the method on that object like I showed you above.

How do I use one button to swap between adding and deleting data from an sqlite database?

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

how to insert data into an sq-lite database at runtime [duplicate]

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

how to apply filters in inserting data to sqlite in android

I have created an application to insert data to sq-lite . i want if i enter same data again it should give e toast massage and then it only update that data not re-insert.
what should i do.....
now data is been re-inserted
method code of SQLiteOpenHelper.....
public void insertdata(String name,String ph,String area){
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
sd=this.getWritableDatabase();
sd.insert("location", null, cv);
sd.close();
method use in Activity class......
public void onClick(View v) {
// TODO Auto-generated method stub
help=new MyHelper(getApplicationContext());
help.getWritableDatabase();
String myname=name.getText().toString();
String call=phone.getText().toString();
String myarea=area.getText().toString().trim();
help.insertdata(myname, call, myarea);
Toast.makeText(getApplicationContext(), "data saved ", Toast.LENGTH_SHORT).show();
}
});
The data is being reinserted because you're methods never check to see if it already exists in the databse. You need to add a query for some unique combination - probably name and phone number. If that query returns a result you can prompt the user to enter the data.
String query = "SELECT * FROM " + TABLE_NAME + " WHERE name = " + name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor != null && cursor.moveToFirst()){ //if cursor has entry then don't reinsert
//prompt user with dialog
} else {
//insert data
}
Also you cannot use a Toast for this. What you want is a Dialog. If the data exists you can display a custom Dialog to the user that you could use to allow them to (1) enter new data (2) edit existing data (3) choose to reinsert the data they are posting. A Toast will just display a message to them like - "reinserting data". It does not sound like that is the functionalty you want to achieve.
To update the database you can just use an update statment depending on what fields you want to change.
String query = "UPDATE " + TABLE_NAME + " SET";
if(!name.isEmpty(){
query += " name = " + name;
}
if(!phone.isEmpty(){
query += " phone = " + phone;
}
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(CREATE_CONTACTS_TABLE)
I put the if statments in to check for which fields are being changed and add them to the query accordingly. In the alternative you could use something like this
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
While I havnet modified it to fit your example you can see the basic approach. Hhere you can use conditionals to check if values are being supplied, if they are you add them to the ContentVlues list which will update them in the DB.
You can try something like this:
ContentValues values=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
if (db == null) {
db = getWritableDatabase();
}
if (isNameExists(name)) { //check if name exits
id = db.update(TABLE_NAME, values, name + " = ?",
new String[] {name});
} else {
id = db.insert(TABLE_NAME, null, values);
}
public boolean isNameExists(String name) {
Cursor cursor = null;
boolean result = false;
try {
String[] args = { "" + name };
StringBuffer sbQuery = new StringBuffer("SELECT * from ").append(
TABLE_NAME).append(" where name=?");
cursor = getReadableDatabase().rawQuery(sbQuery.toString(), args);
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
} catch (Exception e) {
Log.e("AppoitnmentDBhelper", e.toString());
}
return result;

clear editText input after saving info to database

My question is how can i clear the editText field after i have saved what i have written to it to the database? I currently can input text using the nameEditText field but when i click the InsertButton, it does not clear the for. I just want to clear the form not the value or string in the Database...This is the insert button i want to also use as a clear method:
class InsertButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
if("".equals(nameEditText.getText().toString()))
{
Toast toast = Toast.makeText(Entername.this, "Sorry, you must input both the name and the address!", Toast.LENGTH_LONG);
toast.show();
}
else
{
long flag = 0;
int id = 1;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("user_name", new String[]{"count(*) ID"}, null, null, null, null, null);
while(cursor.moveToNext())
{
int idFromDatabase = cursor.getInt(cursor.getColumnIndex("ID"));
if(idFromDatabase != 0)
{
id = 1 + idFromDatabase;
}
}
ContentValues values = new ContentValues();
values.put("ID", id);
values.put("name", nameEditText.getText().toString().trim());
//values.put("address", addressEditText.getText().toString().trim());
flag = db.insert("user_name", null, values);
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this, "You have successful inserted this record into database! ", Toast.LENGTH_LONG);
toast.show();
db.close();
return;
}
else
{
Toast toast = Toast.makeText(Entername.this, "An error occured when insert this record into database!", Toast.LENGTH_LONG);
toast.show();
db.close();
return;
}
}
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
You need to call:
nameEditText.setText("");
addressEditText.setText("");
So, do the following change in your if condition when adding to database is successful:
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this,
"You have successful inserted this record into database! ",
Toast.LENGTH_LONG);
toast.show();
db.close();
//clearing edittexts
nameEditText.setText("");
addressEditText.setText("");
return;
}
you last insert after editText in to set null values
EditText text;
text.setText("");

Categories

Resources