How does Cursor work in android [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm having a hard time exactly visualizing 'Cursor' functionality in my program. I kind of get the jist of it, but can anyone explain it's functionality in detail?
By Cursor, I mean the Cursor interface.
I can't simply understand the role it plays with anything.
http://developer.android.com/reference/android/database/Cursor.html

A Cursor object is returned from a query on a SQLite database.
It will return all rows that the query returns.
Say you have a table called names in your database database configured as such:
_id _name
1 Space Ghost
2 Zorak
3 Moltar
4 Brak
If you want to get all data from this table and use it, you would do
something like this:
public HashMap<Integer, String> getNames(){
HashMap<Integer, String> data = new HashMap<Integer, String>();
try{
SQLiteOpenHelper helper = new MyOpenDbHelper(context);
SQLiteDatabase db = helper.getReadableDatabase();
String selectQuery = "SELECT * FROM names";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
do{
int mID = cursor.getInt(0); //column 0 for the current row
String mName = cursor.getString(1); //column 1 for the current row
data.put(mID, mName);
} while (cursor.moveToNext()); //move to next row in the query result
}
} catch (Exception ex) {
Log.e("MyApp", ex.getMessage());
} finally
{
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return data;
}
Usually you will create your own class to extend SQLiteOpenHelper, as such:
public class MyOpenDbHelper extends SQLiteOpenHelper {
//........
}

From Wikipedia
In computer science, a database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator.
From Here
A cursor is a tool that allows you to iterate the records in a set. It has concepts of order and current record.
From The documentation you pointed yourself
provides random read-write access to the result set returned by a database query.
So don' t think Cursor as a functionality, but as a mean for reaching records in a more efficient way from any database.

Are you reffering to this Cursor usage?
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();

Related

Android Studio Query Function how to add WHERE clause? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am currently trying to display a report for out of stock items. I have the function readOutData() implemented into my report activity and it displays all of the products but how can I edit my function to only show products whose quantity is 0? Here is the code for my current function that just reads all of the product data. I added a comment showing what I want it to do, I'm just not sure how to format it.
Cursor readOutData() {
String query = "SELECT * FROM " + TABLE_NAME; //WHERE quantity = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
This code should work, assuming that the columns are correct
String query = "SELECT * FROM " + TABLE_NAME + " WHERE quantity = 0";
Although use of a PreparedStatement would be better.

SQLite returns only first row through SELECT * Statement

I am saving some records in my sqlite table and records are being saved absolutely fine. Problem comes when I try to retrieve those records. Let's say I have 3 records in my sqlite so when I retrieve those records, it returns me the first record 3 times. Count is correct but why it returns me only first record 3 times?
This is how I am retrieving the records:
public ArrayList<Cursor> getAllBookings() {
ArrayList<Cursor> bookingsList = new ArrayList<>();
SQLiteDatabase readableDatabase = this.getReadableDatabase();
Cursor cursor = readableDatabase.rawQuery("SELECT * FROM " + BOOKING_TABLE, null);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
bookingsList.add(cursor);
cursor.moveToNext();
}
return bookingsList;
}
Please note that I have checked the table in Mozilla SQLiteManager and all records are successfully stored.
The problem is that you are adding the cursor itself to your booking list when you should extract and add the values that each cursor row contains.
So if you have a class Booking the method should be declared as
public List<Booking> getAllBookings() {
Also I think it is better to have a do/while loop here and run it until cursor.moveToNext returns false and inside the loop extract all values using getString or similar methods
List<Booking> bookingsList = new ArrayList<>();
//...
do {
Booking booking = new Booking();
booking.setSomething(cursor.getString("somethingColumn"));
//... other columns
bookingsList.add(booking);
} while (cursor.moveToNext());
If you don't have a custom class then you could use an array or a List for each row.

I cant start this sqlite select code

This sourch code for my app:
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Note where Username = '"+acc+"'", null);
//Cursor cursor = db.rawQuery("SELECT * FROM Note ", null);
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}
This function return nothing , but in debug mode , every single item was set .
Should it return a list of what i selected , i don't understand why and how it's not . Thanks for your help .
Use getReadableDatabase() for query purposes as follows.
SQLiteDatabase db = this.getReadableDatabase();
Please Read SQLiteOpenHelper documentation here for getReadableDatabase()
Create and/or open a database. This will be the same object returned
by getWritableDatabase() unless some problem, such as a full disk,
requires the database to be opened read-only. In that case, a
read-only database object will be returned. If the problem is fixed, a
future call to getWritableDatabase() may succeed, in which case the
read-only database object will be closed and the read/write object
will be returned in the future.
Read SQLiteOpenHelper documentation here for getWritableDatabase()
Create and/or open a database that will be used for reading and
writing. The first time this is called, the database will be opened
and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int)
and/or onOpen(SQLiteDatabase) will be called.
Once opened successfully, the database is cached, so you can call this
method every time you need to write to the database. (Make sure to
call close() when you no longer need the database.) Errors such as bad
permissions or a full disk may cause this method to fail, but future
attempts may succeed if the problem is fixed.
According to the getWritableDatabase() documentation, it clearly mentions that it will cache the database. So it's possible to retrieve data from a cached copy of your database. As same as make sure you've closed the database connection after your transaction.
Finally your code would be like this
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Note where Username = '"+acc+"'", null);
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}
Try this
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT * FROM Note where Username " + " LIKE '%" + acc + "%'";
Cursor cursor = database.rawQuery(selectQuery, null);
int count = cursor.getCount();
database.close();
if(count==0)
{
return result;
}
else
{
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}

Update multiple rows in Android sqlite

I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:
METHODS FOR ANDROID SQLITE DATABASE QUERY:
public void updateUser(String newProfession, String newCountry, String sx, String ag) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
Cursor cursor = db.rawQuery(query, null);
cursor.close();
db.close();
}
public int countAll() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
db.close();
return cnt;
}
CALLING THE METHODS
public void updateUsersClicked(View view) {
int allData = db.countAll();
for (int i = 0; i < allData; i++) {
db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
System.out.println("T H I S I S T H E R E S U L T: " + i);
}
}
Use execSQL() and not rawQuery() for updates.
rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.
Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.
You don't need to do the for loop
a single QSL "Update" query is enough if you want to update All the female with age 30.
If you are new to SQL you can view a simple example here:
Simple SQL Update example
If you want to do something else - please edit your question

How to create filter

I have a database table with multiple columns
I use custom List<> and populate it from database
What i want to do is filter what will go into the list from database depending on user input
for example if i had a table like this:
name|phone|date|address
User can specify any filter(by name, by phone, by date... or all of it) and only items that matches all criteria will go into the list
Is there a way to do this?
Method that returns all items from database
public List<MoviesDatabaseEntry> getAllMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
MoviesDatabaseEntry list = new MoviesDatabaseEntry();
list.set_id(Integer.parseInt(cursor.getString(0)));
list.set_title(cursor.getString(1));
list.set_runtime(cursor.getString(2));
list.set_rating(cursor.getDouble(3));
list.set_genres(cursor.getString(4));
list.set_type(cursor.getString(5));
list.set_lang(cursor.getString(6));
list.set_poster(cursor.getString(7));
list.set_url(cursor.getString(8));
list.set_director(cursor.getString(9));
list.set_actors(cursor.getString(10));
list.set_plot(cursor.getString(11));
list.set_year(cursor.getInt(12));
list.set_country(cursor.getString(13));
list.set_date(cursor.getInt(14));
// Adding to list
lists.add(list);
} while (cursor.moveToNext());
}
// return list
db.close();
cursor.close();
return lists;
}
You can filter the entries you get in the SQL query you are building in this line:
String selectQuery = "SELECT * FROM " + table;
To filter the dataset your retrieve, you would add a WHERE clause to it. When you would, for example, only want those entries where the rating is over 3, you would change this to:
String selectQuery = "SELECT * FROM " + table + " WHERE rating > 3";
SQL is a very powerful language which offers a lot of possibilities. It's an essential skill when you work with relational databases. When you want to learn it, I can recommend you the interactive tutorial website http://sqlzoo.net/
You have to change your database query for getting specific data from the query.
You have one function that returns all rows from database like so: getAllMovies(String table)
Here you are using:
String selectQuery = "SELECT * FROM " + table;
Make a new function like this:
public List<MoviesDatabaseEntry> getSelectedMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
Cursor cursor = db.query(true, TABLE_NAME, new String[] { <your row names> },
**check condition(as string)**, null,
null, null, null, null);
...
}
Now just call this function when required with your specific query string
Make as many functions as you want!

Categories