Delete specific row in SQLite Database - android

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

Related

How to display only selected record in listview?

I want to display only one record from the database in listview. (ENTERED PASSWORD RECORD FROM LOGIN).
DATABASE FILE CODE [DatabaseHelper.java]
public static final String TABLE_NAME = "Master";
public static final String ColumnID = "user_id";
public static final String Column_2 = "f_name";
public static final String Column_3 = "l_name";
public static final String Column_4 = "password";
SELECT RECORD CODE IN DATABASE FILE
public Cursor SelectRecord(String pass) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c=db.rawQuery("SELECT * FROM TABLE_NAME WHERE password = ?",new String[]{pass});
if (c != null)
c.moveToFirst();
return c;
}
JAVA FILE CODE (CODE TO BE EXECUTED) [Edit.java]
final DatabaseHelper db=new DatabaseHelper(getApplicationContext());
Cursor c =db.SelectRecord(t1.setText(getIntent().getStringExtra("text")));
String[] from={"_id","f_name","l_name","password"};
int[] to={R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(Edit.this,R.layout.list_data,c,from,to);
//ListView lv=(ListView)findViewById(R.id.listview1);
// lv.setAdapter(adapter);
LOG IN FILE CODE [LogIn.java]
if (database.checkdata(e1.getText().toString().trim()))
{
Intent i=new Intent(Login.this,Edit.class);
i.putExtra("text",e1.getText().toString());
startActivity(i);
Toast.makeText(getApplicationContext(), "Login Successfully Done", Toast.LENGTH_LONG).show();
e1.getText().clear();
}
I want to get Only one record in listview which password I entered while login.
Edit
Now this code is correct
Cursor c =db.SelectRecord(getIntent().getStringExtra("text"));
If you want to get only one record based on the password, you need to pass a parameter to SelectRecord method.
Assume one of the user password is "pass"
Cursor c = db.SelectRecord("pass");
Select record code
public Cursor SelectRecord(String pass) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM YOUR_TABLE_NAME
WHERE password = ? LIMIT 1", new String[]{pass});
if (cursor != null)
cursor.moveToFirst();
return cursor;
}
Edit
From our conversation:
The Error is in the cursor line : Cursor c =
db.SelectRecord(t1.setText(getIntent().getStringExtra("text")));
The error says SelectRecord (Java.lang.String) in DatabaseHelper
cannot be applied to (void)
The error is in this line
Cursor c =db.SelectRecord(t1.setText(getIntent().getStringExtra("text")));
You need to pass key "text" from Log In to Java File code, so modify this line to
Cursor c =db.SelectRecord(getIntent().getStringExtra("text"));
No need to have setText.

Run query in android SQLite database

I've a database in android studio that has a table name EMP_TABLE with columns E_NAME, E_AGE and E_DEPT.
My fragment layout has two editText fields, a button and a TextView field. I want to perform a query on that database such that when I enter the E_NAME attribute in 1st edittext field, E_AGE attribute in 2nd edittext field and press the button the corresponding attribute of E_AGE field appear in textView field.
The query looks like SELECT E_AGE FROM EMP_TABLE WHERE E_NAME=a1 AND E_DEPT=a2. I'm not so familier with the cursor and the query, help me with this.
This is what I did so far in my OnClick method. Any help will be appreciated.
actTextView1 = (AutoCompleteTextView) view.findViewById(R.id.acTextView1);
actTextView2 = (AutoCompleteTextView) view.findViewById(R.id.acTextView2);
result = (TextView) view.findViewById(R.id.resultField);
calculateButton = (Button) view.findViewById(R.id.calBtn);
calculateButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
DatabaseHelper myDBhelper = new DatabaseHelper(getActivity());
String a1 = actTextView1.getText().toString();
String a2 = actTextView2.getText().toString();
c = myDBhelper.query("EMP_TABLE", null, null, null, null, null, null);
if (c.moveToFirst()) {
do {
Toast.makeText(getActivity(), "Age is: " + c.getString(0), Toast.LENGTH_LONG).show();
} while (c.moveToNext());
}
To insert:
public void insertIntoTable(String E_NAME_VALUE, String E_AGE_VALUE,String E_DEPT_VALUE) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(E_NAME, E_NAME_VALUE);
cv.put(E_AGE, E_AGE_VALUE);
cv.put(E_DEPT, E_DEPT_VALUE);
db.insert(EMP_TABLE , null, cv);
}
To Fetch stored value from database:
public String fetchValueFromTable(String E_NAME_VALUE,String E_DEPT_VALUE) {
String E_AGE_VALUE="" ;
SQLiteDatabase db = this.getWritableDatabase();
SELECT E_AGE FROM EMP_TABLE WHERE E_NAME=a1 AND E_DEPT=a2
String query = "SELECT * FROM " + EMP_TABLE + " WHERE " + E_NAME+ "='" + E_NAME_VALUE+ "' ANd "+ E_DEPT+ "='" + E_DEPT_VALUE;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
E_AGE_VALUE=cursor.getString(cursor.getColumnIndex(E_AGE));
}
return E_AGE_VALUE;
}

Retrieving specific data based on ID from SQLite in ANDROID

I wrote a code in which i can retrieve the data from the database but when i run it and try to search something. The application crashes as soon as i press Submit
public class search extends AppCompatActivity {
Button SearchButton;
EditText SearchText;
TextView SearchResult;
SQLiteDatabase db;
String builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
SearchButton=(Button)findViewById(R.id.searchbutton);
SearchText=(EditText)findViewById(R.id.Searchtext);
SearchResult=(TextView)findViewById(R.id.SearchCourse);
db=this.openOrCreateDatabase("Courses", Context.MODE_PRIVATE,null);
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int GetID = Integer.valueOf(SearchText.getText().toString());
Cursor TuplePointer = db.rawQuery("Select from Course where ID="+GetID+"",null);
TuplePointer.moveToFirst();
String Course = TuplePointer.getString(TuplePointer.getColumnIndex("Course"));
SearchResult.setText(Course);
}
});
}
}
Replace this line
Cursor TuplePointer = db.rawQuery("Select from Course where ID=" + GetID + "", null);
with
Cursor TuplePointer = db.rawQuery("Select Course from Course where ID=" + GetID + "", null);
Where Course is your column name
Write your code within try catch first. Afterthat try to catch exact exception. you will be clear what are you doing wrong.
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " Where " + KEY_APP_BOOKINGID + " = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Please Try this
SQLiteDatabase db = this.getReadableDatabase();
String GetID = SearchText.getText().toString();
Cursor cursor = db.rawQuery("SELECT * FROM Course WHERE ID = ?", new String[]{String.valueOf(GetID)}, null);
if (cursor.moveToFirst()) {
do {
String Course = cursor.getString(cursor.getColumnIndex("Course"));
SearchResult.setText(Course);
} while (cursor.moveToNext());
}
Thank You everyone I figured out what i was doing wrong on the get Column index i targeted course but what i didnt realize is that there was no such field as course :)
Keep practice like below code you will debug proper
public void getFirstName(String id) {
String sql = "select first_name from basic_info WHERE contact_id="+ id;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
Log.e("Result =>",FirstName);
}
c.close();
}
return data;
}
public Cursor fetchData(String sql) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(sql, null);
}

how to retrieve single row according to specific condition?

here my coding:-
DatabaseHelper.java
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String selection = Menu.NewMenuInfo.MENU_ID + "=" + a1;
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,null);
return cursor;
}
Menu1.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuset1);
s_id = (TextView) findViewById(R.id.idSet1);
s_name = (TextView) findViewById(R.id.nameSet1);
s_drink = (TextView) findViewById(R.id.drinkSet1);
s_price = (TextView) findViewById(R.id.priceSet1);
set1 = (Button) findViewById(R.id.buttonOrderSet);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getinnformationSet1(sqLiteDatabase);
if (cursor != null){
cursor.moveToFirst();
String id = cursor.getString(0);
String name = cursor.getString(1);
String drink = cursor.getString(2);
String price = cursor.getString(3);
s_id.setText(id);
s_name.setText(name);
s_drink.setText(drink);
s_price.setText(price);
}
}
}
basically i want to display id,name,drink,price according to id="f1".
example: if id="f1" then display all the information without using any searching or click button.
when i run this coding the application has stopped
You need to pass the selection arguments as an array, but in the selection string you should put ? mark. Change your getinnformationUser method like this:
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String selection = Menu.NewMenuInfo.MENU_ID + "= ?";
String[] selectionArgs = new String[] {a1};
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,selectionArgs,null,null,null,null);
return cursor;
}
You can read more about the query method here.
basically your select query is wrong....its like below
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String whereclause = Menu.NewMenuInfo.MENU_ID + "= ?";
String where_args[] = {a1};
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,whereclause,where_args,null,null,null);
return cursor;
}
Will work perfectly...
Use orderBy. In orderBy pass any value for order the rows for example if you want to order by id then pass id and add limit 1
i.e
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,"id limit 1");
This will select only one row.
Correction
You can use query() (link provided by Eric B.) also for passing limit as parameter

Deleting data from SQLite Database is not working

I am working with SQLite and I am having trouble deleting data.
First and foremost, this is how I add data to the database:
public void addRecipe (QueryVars Recipee){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_Recipe, Recipee.getRecipe());
db.insert(TABLE_Recipes, null, values);
db.close();
}
And this is how I get data from the database:
public List<QueryVars> getAllBooks() {
List<QueryVars> recipes = new LinkedList<QueryVars>();
String query = "SELECT * FROM " + TABLE_Recipes;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
QueryVars Recipe = null;
if (cursor.moveToFirst()) {
do {
Recipe = new QueryVars();
// Recipe.setId(Integer.parseInt(cursor.getString(0)));
Recipe.setRecipe(cursor.getString(1));
recipes.add(Recipe);
} while (cursor.moveToNext());
}
return recipes;
}
Saving and querying for data is working perfectly fine, but when I try to delete rows with the following code it just doesn't work.
public void deleteRecipes(QueryVars Recipe) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Recipes, KEY_ID + " = ?", new String[] { String.valueOf(Recipe.getId()) });
db.close();
}
This is the query I use to create the table:
private static final String CREATE_BOOK_TABLE =
"CREATE TABLE Recipes ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "Recipe TEXT"
+ ")";
And the constants I use in my code above are defined like this:
private static final TABLE_Recipes = "Recipes";
private static final String KEY_ID = "id";
private static final String KEY_Recipe = "Recipe";
private static final String[] COLUMNS = {KEY_ID,KEY_Recipe};
There are two issues in your code which could potentially be the source of the error, but both have the same cause: You are letting SQLite generate the ids of your Recipe objects but you are never setting that id to your objects.
When you add something to the database the add() method returns the id which was generated for that row. You can just set this id to the Recipe object otherwise that Recipe object won't have an id until you reload it from the database.
public void addRecipe (QueryVars Recipee){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_Recipe, Recipee.getRecipe());
final long id = db.insert(TABLE_Recipes, null, values);
Recipee.setId(id);
db.close();
}
When you are reading the Recipe objects from the database you are not setting the id value on the object, so no Recipe object you read from the database has an id which means you cannot delete them from the database. The fix is again pretty simple:
public List<QueryVars> getAllBooks() {
List<QueryVars> recipes = new LinkedList<QueryVars>();
String query = "SELECT * FROM " + TABLE_Recipes;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
final int idIndex = cursor.getColumnIndex(KEY_ID);
final int recipeIndex = cursor.getColumnIndex(KEY_Recipe);
QueryVars Recipe = null;
if (cursor.moveToFirst()) {
do {
Recipe = new QueryVars();
Recipe.setId(cursor.getLong(idIndex));
Recipe.setRecipe(cursor.getString(recipeIndex));
recipes.add(Recipe);
} while (cursor.moveToNext());
}
return recipes;
}
This uses getColumnIndex() to reliably get the correct index of each column and then reads the id and the recipe from the cursor and sets them to the Recipe object.
Please note that your Recipe object needs to have a long id! int ids are not compatible with the SQLiteDatabase!
You don't capture the database-generated id of your recipes and the id is zero. It doesn't match any rows in the delete.
Uncomment the
// Recipe.setId(Integer.parseInt(cursor.getString(0)));
(consider using cursor.getInt() instead)
Possibly also store the return value of insert() as the recipe id.

Categories

Resources