delete item from local database function doesn't work - java

//the following function 'listens to the click' - here we are using an 'item click listener' which gives you a number of which one was clicked
lv_customerList.setOnItemClickListener((parent, view, position, id) -> {
//getting the customer that was just clicked to send it to the method to delete
//the parent of the listener is the listview
CustomerModel clickedCustomer = (CustomerModel) parent.getItemAtPosition(position); //this tells me which person was just clicked
//now we call the "deleteOne" function from the databaseHelper class
dataBaseHelper.deleteOne(clickedCustomer);
//now we update the list view
ShowCustomersOnListView(dataBaseHelper);
Toast.makeText(MainActivity.this, "Deleted" + clickedCustomer,Toast.LENGTH_SHORT).show();
});
This is the code in the MainActivity
//creating a new function that will delete contents from a database
public boolean deleteOne(CustomerModel customerModel) {
//find customerModel in the database. if is is found, delete it and return true, otherwise return false
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM" + CUSTOMER_TABLE + "WHERE" + CUSTOMER_ID + " = " + customerModel.getId();
Cursor cursor = db.rawQuery(queryString, null);
if (cursor.moveToFirst()) {
return true;
}
else {
return false;
}
}
And this is the code from the DatabaseHelper activity
I followed the https://youtu.be/312RhjfetP8 tutorial and copied the code exactly (although the android IDE suggested to change the...
new AdapterView.OnItemClickListener()
to a lambda (in the method in mainactivity)
But now whenever I click one of the rows (see video to understand what i mean) in the app - the app just crashes and I'm not sure why :(
Could someone please help me out?
Thank you so much!

I'm pretty sure that you miss a lot of space characters in the query String.
String queryString = "DELETE FROM" + CUSTOMER_TABLE + "WHERE" + CUSTOMER_ID + " = " + customerModel.getId();
should be changed to
String queryString = "DELETE FROM " + CUSTOMER_TABLE + " WHERE " + CUSTOMER_ID + " = " + customerModel.getId();

DeleteBuilder<CustomerModel, Integer> deletebuilder =
mcustomermodel.deleteBuilder();

Related

Checking that conditions are met before adding the order to the database

I am trying to make sure that the user has selected a waiter id (The first if statement) and that the id is valid and relates to a record in the database(The else if statement).
I am collecting the id from a Number (GUI Text in Android) and selecting the Number value like so
EditText waiter_id;
waiter_id = (EditText) findViewById(R.id.waiter_id);
TextUtils.isEmpty(waiter_id.getText() checks to make sure a value has been entered and displays a message if not this works.
After I am calling a method created in the DataBaseHelper isEmployee(String id) class which uses the id entered by the user to search the database for that record. If the id is not found in the database then a message should appear to alert the user.
Order onClick OrderActivity
order.setOnClickListener(new View.OnClickListener() {
Order order;
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(waiter_id.getText())) {
Toast.makeText(OrderActivity.this, "Please select waiter id", Toast.LENGTH_SHORT).show();
// This is where the method which returns the boolean is called using
// the value in the Number field in xml file
} else if (!dbHelp.isEmployee(String.valueOf(waiter_id))){
Toast.makeText(OrderActivity.this, "Id not valid", Toast.LENGTH_SHORT).show();
}
});
Method for querying the database DataBaseHelper Class
public Boolean isEmployee(String id){
SQLiteDatabase db = this.getReadableDatabase();
String findEmployeeUsingId = "SELECT * FROM " + EMP_TABLE +
" WHERE " + ID_EMP + " = " + id;
Cursor cursor = db.rawQuery(findEmployeeUsingId, null);
if (cursor.getCount() == 0) {
return false;
}
else
return true;
}
The error message I am receivingis:
com.example.dropit E/SQLiteLog: (1) near ".": syntax error in "SELECT * FROM EMP_TABLE WHERE ID = androidx.appcompat.widget.AppCompatEditText{93d8cbb VFED..CL. .F...... 249,193-829,317 #7f08011f app:id/waiter_id aid=1073741824}"
android.database.sqlite.SQLiteException: near ".": syntax error (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM EMP_TABLE WHERE ID = androidx.appcompat.widget.AppCompatEditText{93d8cbb VFED..CL. .F...... 249,193-829,317 #7f08011f app:id/waiter_id aid=1073741824}
at com.example.dropit.DataBaseHelper.isEmployee(DataBaseHelper.java:283)
at com.example.dropit.OrderActivity$1.onClick(OrderActivity.java:58)
waiter_id is an EditText and not a string.
When you call isEmployee() you should pass its text:
else if (!dbHelp.isEmployee(waiter_id.getText().toString()))
Also use a ? placeholder inside rawQuery() instead of concatenating the parameter:
String findEmployeeUsingId = "SELECT * FROM " + EMP_TABLE + " WHERE " + ID_EMP + " = ?";
Cursor cursor = db.rawQuery(findEmployeeUsingId, new String[] {id});

How to load data associated with a specific item from SQLite Android Database?

On the click of X semester I want my app to load the classes associated with that specific semester, which I'm trying to do with the following piece of code:
public void openSemestersActivity() {
final Intent semester = new Intent(this, SemesterActivity.class);
semesterListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// This works if nothing is deleted. If something is deleted we would have to add another +1 to the position
semester.putExtra("semester", db.getSemesterNameString(position + 1));
Log.d("Semester Name", db.getSemesterNameString(position + 1));
startActivity(semester);
}
});
}
Now, I want to load the classes associated with that specific semester on the SemesterActivity, which I'm trying to do with the following code:
// Retrieving the Extra and determining the semester we want to load
Intent myIntent = getIntent();
String semester = myIntent.getStringExtra("semester");
// Creating the Database and loading the ListView
db = new DataBaseHelperC(this);
myCourses.addAll(db.getAllCoursesForThisSemester(semester));
customCourseAdapter = new CourseAdapter(getApplicationContext(), R.layout.course_row, myCourses);
courseListView.setAdapter(customCourseAdapter);
customCourseAdapter.notifyDataSetChanged();
This is the method, located on my DatabaseHelper class, that's supposed to get all the courses for that specific semester:
public List<Course> getAllCoursesForThisSemester(String semester) {
List<Course> courses = new ArrayList<>();
// Select all query
String selectQuery = "SELECT * FROM " + Course.TABLE_NAME + " ORDER BY " + Course.COLUMN_ID + " ASC";
SQLiteDatabase db = this.getWritableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.rawQuery(selectQuery, null);
// Looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Course course = new Course();
course.setNameOfCourse(cursor.getString(cursor.getColumnIndex(Course.COLUMN_COURSE)));
course.setCodeOfCourse(cursor.getString(cursor.getColumnIndex(Course.COLUMN_COURSECODE)));
course.setCreditsOfCourse(cursor.getString(cursor.getColumnIndex(Course.COLUMN_COURSECREDITS)));
course.setNameOfBackground(cursor.getString(cursor.getColumnIndex(Course.COLUMN_BACKGROUND)));
course.setId(cursor.getInt(cursor.getColumnIndex(Course.COLUMN_ID)));
courses.add(course);
}
while (cursor.moveToNext());
}
// Close db connection
db.close();
return courses;
}
I'm passing a String semester as parameter, but can't figure out how to actually use this parameter to only get the courses for that specific semester. This is my first time working with a Database and it is worth noting that I'm having a hard time with it and haven't gotten the hang of it just yet so any help would be really appreciated since I've been stuck here for around 2 weeks now.
Right now, by using the code that I currently have, if I add a course in X semester and then open Y semester, the courses added on X semester are loaded on the Y semester too. This is what I'm trying to fix with that method that receives a String semester as parameter.
The sql statement:
SELECT * FROM " + Course.TABLE_NAME + " ORDER BY " + Course.COLUMN_ID + " ASC"
needs a WHERE clause.
If the column containing the semester has a name like semester, you can do it like this:
String selectQuery = "SELECT * FROM " + Course.TABLE_NAME +
" WHERE semester = ?" + // replace with the actual column name
" ORDER BY " + Course.COLUMN_ID + " ASC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[] {semester});

SQLite seems not to be executed in Android RecyclerView with onCheckedChanged

I have a list inflated by a RecyclerView, which is extracted by an SQLite database. I use a onCheckedChanged to manipulate the data.
If I click the CheckBox, method setItem() is called.
private void setItem(int position, boolean checked) {
// update entries in sqLiteDatabase at click position
// set the database-cursor to current entry
cursor.moveToPosition(position);
// convert boolean to integer, because SQLite does not support boolean values
int iSelected = checked ? 1 : 0;
// create SQL-query-string
String SQLQuery = "" +
"UPDATE country " +
"SET selected=" + iSelected +
" WHERE id='" + cursor.getString(cursor.getColumnIndex("id")) + "'";
// execute the query
sqLiteDatabase.execSQL(SQLQuery);
// create SQL-answer-string
String SQLAnswer = cursor.getString(cursor.getColumnIndex("name")) +
"; Id=" + cursor.getString(cursor.getColumnIndex("id")) +
"; Selected=" + cursor.getString(cursor.getColumnIndex("selected"));
Toast.makeText(context, SQLQuery + "\n\n" + SQLAnswer, Toast.LENGTH_LONG).show();
}
When I click it once on the CheckBox it shows:
SQLQuery => "UPDATE country SET selected=1 WHERE id=3"
SQLAnswer => "Czechia; id=3; selected=1"
When I click it twice:
SQLQuery => "UPDATE country SET selected=0 WHERE id=3"
SQLAnswer => "Czechia; id=3; selected=1"
...and this alters. So the query switches between 0 and 1 (depending on CheckBox), but the answer never becomes 0.
When I close the app and restart it, the database-entries are done well, but it's not updated during runtime.
Has someone an idea (never had such probs with PHP)?
I found a way:
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM country WHERE id='" + cursor.getString(cursor.getColumnIndex("id")) + "'", null);
c.moveToFirst();
System.out.println(c.getString(c.getColumnIndex("selected")));
Thank you for the comments and help.
I think, that "cursor" was generated in MainAktivity to inflate the adapter, so, fetching a row in the adapter from cursor, will retrieve the state, when the adapter was created and cannot be modified later by the adapter.
I cannot even understand this weird construct with the recyclerView or viewHolder. They changes checkboxes, which are cought by onClickListener, only by scrolling, and the programmer has to correct this mistakes. They are really stupid to handle. In my opinion, a list should be inflated, and the os (android) has to optimized it internally.

Storing data from an entire row, Android SQLite

So I have a method that allows me to get the id of a certain item by using a name i already have in an SQL Database. How would I go about getting the entire row of information and storing each item in its own variable.
Method that only works with ID
public Cursor getID(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT " + COL1 + " FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
And the method that gets the query and stores the result
Cursor data = mydb2.getID(name);
int itemId= -1;
while(data.moveToNext()){
itemId = data.getInt(0);
}
Using this method below how would i store all of the data in its own variable using this (or any other way to get data of entire row).
public Cursor rowData(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT * FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
I know this might be a dumb question, and I have tried looking at other questions, I have gotten this far I just don't know what to do next (I'm very new to Sq Lite databases and Android development)
You'd use something like :-
Cursor csr = instance_of_yourdbhelper.rowData();
while(csr.moveToNext()) {
long thisItemId = csr.getLong(csr.getColumnIndex(yourdbhelper.COL_1));
String thisName = csr.getString(csr.getColumnIndex(yourdbhelper.COL_2));
// etc for other columns
}
Notes
yourdbhelper is the class for your DatabaseHelper which is the class that extends SQLiteOpenHelper (the assumption is that the above methods are from such a class, as this is a common usage of SQLite)
instance_of_yourdbhelper is the instance of the DatabaseHelper class i.e. you may have yourdbhelper dbhlpr = new yourdbhelper(parameters);, in which case dbhlpr is the instance.
This just overwrites the same variables (thisItemId and thisName) for each row in the cursor, although there is perhaps the likliehood that the rowData method only returns one row.
You will likely encounter fewer errors using the getColumnIndex method as it returns the offset according to the column name. Miscalculated offsets is a frequent cause of problems.
You may wish to handle a no rows returned situation in which case you can use cursor.getCount(), which will return the number of rows in the cursor.

Retrieving a database value and assigning to a string value

I am making a app that incorporates login/register functionalities and I'm making a issue that I have been trying to solve.
When a user logins and the login is successful, I'd like to use the email that they signed in with to pass to the next activity using Intent (I checked that the email is in fact getting passed by displaying what is being passed through the intent) and then passing that email to a function in the Dbhelper that uses that email to look for the name of the person that signed in then displaying "Welcome (name of person)" in the current activity but I keep getting a null returned in the function which ultimately leads to the app crashing.
Here is where I'm calling the function in the activity where I want to display the name.
if(!session.loggedIn())
{
Logout();
}
else
{
Intent in = getIntent();
String email = in.getStringExtra("email");
Name.setText("Welcome " + db.findName(email));
}
And this is the function in my DbHelper.java where I'm looking for the name with a query and such.
public String findName(String user_email)
{
String query = "SELECT " + COLUMN_NAME + " FROM " + USER_TABLE + " WHERE " + COLUMN_EMAIL + " = " + "'" + user_email + "'";
SQLiteDatabase db = this.getWritableDatabase();
//reads for database
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.getCount() > 0) // if cursor is not empty
{
String n = c.getString(0);
return n;
}
else
{
return null;
}
}
As you can see, it's returning null. And yes there is entries in the database already. Also, I tried just passing the email to the function and returning what was passed and it still gave me an error.
Normally, to check for a value in a text column, you do not use the equal = sign, but rather WHERE Column LIKE '%text%'. Also, when saving to a database you should escape and "sanitize" strings. If you did this, then you should also be doing the same process when looking for them, else you won't find them.
I am telling you this since, even if you are sure there are entries in your table, the result of the query may be empty. You could just debug by printing the result of the c.getCount() call or something.

Categories

Resources