I'm trying to fetch data from sqlite database and update a custom recycler view with these data. I've created a method in my Database helper class that returns an ArrayList of items fetched from the database.
This is how I expect the method to work:
query the database, store the result set in a Cursor object.
Loop through the result set in the Cursor object and add each item to the end of an ArrayList object.
Return the ArrayList object containing the items fetched from the database.
But this is how the method is working:
queries the database, stores the result set in a Cursor object. Correct.
On the first iteration of the result set, the first item in the result set is added at index 0 of the ArrayList object. Just as expected. But on the second iteration, the second item in the result set replaces the already added item in the ArrayList at index 0, and it's also added at index 1. Furthermore, on the third iteration, the third item in the result set replaces all the items in the ArrayList such that we now have only the third item at indices 0, 1 and 2 instead of having the first item at index 0, second at index 1 and third at index 2. I'd really appreciate all the help I can get on this.
Below is the snippet of the method that does the item fetching from the database
public ArrayList<RechargeCard> getCard(){
ArrayList<RechargeCard> list = new ArrayList<>();
RechargeCard card = new RechargeCard();
SQLiteDatabase database = getReadableDatabase();
String query = "SELECT * FROM " + RechargeEntry.TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndexOrThrow(RechargeEntry.NAME_COLUMN));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(RechargeEntry.PRICE_COLUMN));
double quantity = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.QUANTITY_COLUMN));
double total = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.TOTAL));
card.setName(name);
card.setPrice(price);
card.setQuantity(quantity);
card.setTotal(total);
list.add(card);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
What you code is doing is that it is only updating RechargeCard card = new RechargeCard(); for every iteration that the while loop is doing.
You should put RechargeCard card = new RechargeCard(); inside the do while loop
so it will create new instances every iteration
public ArrayList<RechargeCard> getCard(){
ArrayList<RechargeCard> list = new ArrayList<>();
SQLiteDatabase database = getReadableDatabase();
String query = "SELECT * FROM " + RechargeEntry.TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
RechargeCard card = new RechargeCard();
String name = cursor.getString(cursor.getColumnIndexOrThrow(RechargeEntry.NAME_COLUMN));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(RechargeEntry.PRICE_COLUMN));
double quantity = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.QUANTITY_COLUMN));
double total = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.TOTAL));
card.setName(name);
card.setPrice(price);
card.setQuantity(quantity);
card.setTotal(total);
list.add(card);
}while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
Related
I have a table in which name and number of people are stored. Now I want to make a method in sqlite helper class which will return the number of particular person whose name I will pass in the method
There is something wrong with my code.
Here is my code
public String fetchGroup(SQLiteDatabase inDatabase, String valueCheck){
String query = "SELECT * FROM groups WHERE groupname='" + valueCheck;
Cursor cursor = inDatabase.rawQuery(query,null);
String place = cursor.getString(cursor.getColumnIndex("contactid"));
return place;
Take care to use cursor.moveToFirst() command before reading datas
Else, instead counting the number of people in Java, you can just modify your query to have only this number return.
Something like this :
public String fetchGroup(SQLiteDatabase inDatabase, String valueCheck){
String query = "SELECT COUNT(id) FROM groups WHERE groupname=\"" + valueCheck + "\"";
Cursor cursor = inDatabase.rawQuery(query, null);
cursor.moveToFirst();
int place = cursor.getInt(0);
return String.valueOf(place);
}
After your query do
int count = 0;
while (cursor.moveToNext()) {
// increment variable
count++;
}
after iterating you will get number of count
I'm working on Voip app ,So i have to show all contacts for user to call it .
So i used the following function :
public void GetContactsIntoArrayList(){
int i = 0 ;
cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
HashSet<String> tempHash = new HashSet<String >();
while (cursor.moveToNext()) {
Person per = new Person();
Bitmap bit_thumb ;
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactId = cursor.getColumnIndex(ContactsContract.Contacts._ID);
per.setName(name);
per.setNumber(phonenumber);
//
if(tempHash.add(name) ){
i++ ;
StoreContacts.add(per );
}
}
Toast.makeText( getActivity()," "+i , Toast.LENGTH_LONG).show();
cursor.close();
adapter = new ContactListViewAdapter(getContext() , StoreContacts) ;
contactsListView.setAdapter(adapter);
}
Everything was good when my contacts count was less than 5000 contact .
But now i have 20000 contact on my phone it takes about 13 second to retrieve the result it so much .
can anyone help me to improve .
Assume that you've 100,000 contacts in your phone and it takes one minute for the cursor to load, and this much loading time is irritating in respect to user.
One solution is to fetch contacts using a limit, like
SELECT * FROM TABLE LIMIT 0,30
and then populate the listview(RecyclerView).
This way is much meaningful than fetching
SELECT * FROM TABLE
because we can't show 100,000 contacts at the same time,
while the user starts scrolling and reaches the bottom of first limit of elements, fetch the next limit of contacts and update the listview.
Since in our case we are not dealing with SQL Tables ,
To set limit in ContentProvider;
Cursor c = resolver.query(
MyTable.CONTENT_URI,
MyTable.PROJECTION,
null,
null,
" limit 1 offset 2");
I solved my problem by separate the cursor variables initialization
It was look like this :
cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
And I replace it with following code :
String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
String orderBy = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
cursor = getActivity().getContentResolver().query( uri, projection, null, null, orderBy) ;
And now its works 20,000 contact takes 1 second
I am working on SQLite database. I have retrieved values using select query.
Now I have to save these values in variable for comparison with user entered email ans password.
How can I save it in a variable in Login.java
Query(MYSQLiteHelper.java)
public user_reg getemail(String ema) {
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_USERREGISTRATION, // a. table
COLUMNS, // b. column names
" email = ?", // c. selections
new String[] {
String.valueOf(ema)
}, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
user_reg user = new user_reg();
user.setEmail(cursor.getString(3));
user.setPassword(cursor.getString(4));
Log.d("getUser(" + ema + ")", user.toString());
// 5. return book
return user;
}
Login.java
MySQLiteHelper db = new MySQLiteHelper(getApplicationContext());
emailval= email.getText().toString();
db.getemail(emailval);
You can get data from cursor by this way :
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
user_reg user = new user_reg();
// I am expecting email and password as column name
user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
Log.d("getUser(" + ema + ")", user.toString());
// 5. return book
return user;
You need to check like this for your username if exist or not ..
if(ema.equals(cursor.getString(3))){
user.setEmail(cursor.getString(3));
user.setPassword(cursor.getString(4));
} else{
.....
}
This is my Android Project and got stacked
My App has a DataBase with a column(subname) and two raw or query(Physics, Chemistry)
String[] subjects = {};
Cursor c = db.rawQuery("SELECT * FROM subs", null);
if(c.moveToFirst()){
subjects[0] = c.getString(0);
}
I want output as two subjects as an array {"Physics", "Chemistry"}
But its only returning the first query Physics and its not returning the other column Chemistry.
How can I get the second value?
Since, number of rows can be 1, 2 or more, so we are not sure about the size of array. In this scenario, I would suggest to use List and then convert list to Array
List<String> lst = new ArrayList<>();
Cursor c = db.rawQuery("SELECT * FROM subs", null);
if(c.moveToFirst())
{
lst.add (c.getString(0));
}
Now convert List to Array
String[] arr = lst.toArray ();
I am building an application where the user can save some information into an sqlite database. What I now want to do is be able to get the data from the sqlite database and store each row in its own string.
Note
There is only one column in the database.
So, algoritm is not difficult, just create Cursor and in loop you will be retrieving data from it and then save them to List for example.
So try this snippet of code:
final String SELECT_QUERY = "Select column from Table";
List<String> data = new ArrayList<String>();
String member = null;
Cursor c = db.rawQuery(SELECT_QUERY, null);
if (c.getCount() > 0 && c.moveToFirst()) {
do {
member = new String(c.getString(0));
data.add(member);
}
while (c.moveToNext());
}