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 ();
Related
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;
}
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
How do i fix this error?
I am using SQLite to store my data and I have my CursorAdapter.java and DBHelper class and I am trying to use everything on the MainActivity,here is the code for the MainActivity.java
ArrayList<ItemsHolder> array_list = new ArrayList<>();
SQLiteDatabase db = mydb.getReadableDatabase();
Cursor res = db.rawQuery("select * from Todo", new String[]{COLUMN_ID});
while(res.moveToNext()) {
ItemsHolder itemsHolder = new ItemsHolder();
itemsHolder.item = res.getString(res.getColumnIndex(ITEM_NAME));
array_list.add(itemsHolder);
}
TodoCursorAdapter todoAdapter = new TodoCursorAdapter(this, res);
// Attach cursor adapter to the ListView
lvItems.setAdapter(todoAdapter);
But I keep getting the error mentioned above, what does it even mean?please help
Your SQL ("select * from Todo") doesn't match the number of parameters you are passing to it (new String[]{COLUMN_ID}). If you are passing arguments to db.rawQuery, you must have placeholders in the SQL you are running. For example, something like:
db.rawQuery("SELECT * FROM todo WHERE column_id = ?", new String[]{COLUMN_ID});
The error you are getting is because you are passing in a parameter to the query (COLUMN_ID), but there are no parameters (question marks) to bind the value to.
i'm a newbie in android programming.
i tried searching in the internet but i can't find any possible solution.
my program below is use to split inputted string using comma (",")
*search from database using the split string
*populate into listview
my problem is that it only search using the last element in String Array(HERBALSUGGESSTIONSARRAY)
I want to populate all matches (SYMPTOMS2) using all the element in my String Array
for example :
user input: flu, cough
listview:
all possible illness with symptoms of "Flu" and "cough"
Sorry for my grammar guys , thanks in advance. More power Stackoverflow community
searchText = (EditText) findViewById (R.id.searchTexths);
String[] HerbalSuggesstionsArray = searchText.getText().toString().trim().split("\\s*,\\s*");
for(int x= 0; x<HerbalSuggesstionsArray.length;x++){
cursor = db.rawQuery("SELECT _id, name, symptoms2 FROM hsdisease WHERE symptoms2 LIKE?",
new String[]{""+ HerbalSuggesstionsArray[x]} );
adapter = new SimpleCursorAdapter(
this,
R.layout.herbalsuggestion_list_item,
cursor,
new String[] {"name", "symptoms2"},
new int[] {R.id.hsname, R.id.hssymptoms} );
setListAdapter(adapter);
searchText.getText().clear();
}
Currently you query the DB and create a new adapter for every simptom.
Instead fetch the results for all symptoms at once and then create the adapter.
String[] HerbalSuggesstionsArray = searchText.getText().toString().trim().split("\\s*,\\s*");
String query = "SELECT _id, name, symptoms2 FROM hsdisease WHERE symptoms2 LIKE ?"
// Append as many WHERE clauses as necessary
for(int x= 0; x<HerbalSuggesstionsArray.length - 1; x++) {
query += " OR symptoms2 LIKE ?";
}
cursor = db.rawQuery(query, HerbalSuggesstionsArray);
adapter = new SimpleCursorAdapter(
this,
R.layout.herbalsuggestion_list_item,
cursor,
new String[] {"name", "symptoms2"},
new int[] {R.id.hsname, R.id.hssymptoms} );
setListAdapter(adapter);
searchText.getText().clear();
thanks to sir/maam #user3249477
here's the working code:
String[] HerbalSuggesstionsArray = searchText.getText().toString().trim().split("\\s*,\\s*");
String query = "SELECT _id, name, symptoms2 FROM hsdisease WHERE symptoms2 LIKE?";
// Append as many WHERE clauses as necessary
for(int x= 0; x<HerbalSuggesstionsArray.length - 1; x++) {
query += " OR symptoms2 LIKE ?";
}
cursor = db.rawQuery(query, HerbalSuggesstionsArray);
adapter = new SimpleCursorAdapter(
this,
R.layout.herbalsuggestion_list_item,
cursor,
new String[] {"name", "symptoms2"},
new int[] {R.id.hsname, R.id.hssymptoms} );
setListAdapter(adapter);
searchText.getText().clear();
I would like to get values from the database in this format
1 Audi
3 Nissan
But I am getting like this as of now. I don't need to get to include the _id in the output.But I couldn't eliminate as it throws a NullPointerException when I remove it.
id MAKE
=========
1 Audi
2 Audi
3 Nissan
4 Audi
this is my query I have used in
cursor = db.rawQuery(
"SELECT DISTINCT _id,MAKE FROM "+SQLiteAdapter.MYDATABASE_TABLE+
" WHERE MAKE || ' ' || MODEL LIKE ?", new String[]{"%" + "" + "%"}
);
Do have I to change the sequence entirely to get the output or make changes on the above code.Thanks.
my code
cursor = db.rawQuery("SELECT DISTINCT SERIES FROM "+SQLiteAdapter.MYDATABASE_TABLE+" WHERE YEAR=2012 AND MAKE='Audi' AND MODEL=?", new String[]{"A6"});
adapter = new SimpleCursorAdapter(this, R.layout.employee_list_item, cursor, new String[] {"series"}, new int[] {R.id.firstName});
employeeList.setAdapter(adapter);
try:
select min(id), min(make) from cars group by make
you can use SQLiteQueryBuilder's buildQueryString method:
buildQueryString (boolean distinct, String tables, String[] columns, String where, String groupBy, String having, String orderBy, String limit)