How can I read only 10 rows from my Sql Database? - java

Hey I have a question:) How can I read only ten rows from my sql db?
here is my code:
openDB();
Cursor c = myDb.getSpalte();
List<Integer> valueList = new ArrayList<Integer>(c.getCount());
while (c.moveToNext()) {
valueList.add(c.getInt(1));
}
c.close();
closeDB();
And if it helps you here is my getSpalte method:
public Cursor getSpalte(){
String where = null;
String Order = "_id DESC";
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Thank yout for helping! And sorry for my bad englsih;P

Set the last null argument to "10". This argument is for LIMIT which limits the number of rows returned by the query.
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, "10");
Remember though that limiting must be accompanied by appropriate logic to sort the result set. Otherwise, you can get any 10 rows, which may not always be what you want.
Reference

Change your db query in your getSpalte function like this:
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, "10");

You can do this by using select TOP, limit or using ROWNUM depending on the DB you use, or you can simple handle it using a simple for loop instead of while.

You can use LIMIT for that as last argument. Here 10.
Refer here
limit - Limits the number of rows returned by the query, formatted as
LIMIT clause. Passing null denotes no LIMIT clause.

Related

Android : phone contacts query takes long time to return the result

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 can I get a value from database that has the soonest time to current time?

I keep getting a NullPointerException when I try this query:
Cursor cursor = sqLiteDatabase.query("collection", new String[] { "SELECT interval WHERE MIN(time) FROM collection" }, null, null,
null, null, null); // This is where the NPE is.
cursor.moveToFirst(); //ADD THIS!
Integer collectionInterval = cursor.getInt(0);
Is my select query right or the way I'm setting this up?
Basically above I want to select an interval where the soonest time to current time from a table. How can I do that?
In a query, FROM comes before WHERE. Also, I think you need an equality test there
SELECT interval FROM collection WHERE time = (SELECT MIN(time) FROM collection)

Android SQLite query rows from bottom to top with timestamp to equal current date

I am using SQLite for my app and I kind of have a large database. The database has 3 columns:
id(int auto incerement)|timestamp(int)|value(string)
I want to have the latest records, which have timestamp (millisec) of the current day.
At the I have a code to query all the records in the table, but it is awfully slow:
public List<PhysicalActivity> getAllPhysicalActivities(){
List<PhysicalActivity> all = new ArrayList<PhysicalActivity>();
Cursor cursor = mDatabase.query(PhysicalActivityDatabaseHelper.TABLE_NAME, mColumns
, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
PhysicalActivity pa = cursorToPhysicalActivity(cursor);
all.add(pa);
cursor.moveToNext();
}
cursor.close();
return all;
}
I want to do ORDER BY id DESC as you would do in MySQL...I need to have something like this code:
public List<PhysicalActivity> getPhysicalActivitiesForDate(Date date){
List<PhysicalActivity> activities = new ArrayList<PhysicalActivity>();
Cursor cursor = mDatabase.query(PhysicalActivityDatabaseHelper.TABLE_NAME, mColumns
, null, null, null, null, "ORDERBY " + PhysicalActivityDatabaseHelper.COLUMN_ID +
" DESC");
cursor.moveToFirst();
while(!cursor.isAfterLast()){
PhysicalActivity pa = cursorToPhysicalActivity(cursor);
Date d = new Date(pa.getTimestamp());
if(d.getDay() == date.getDay()){
activities.add(pa);
}
cursor.moveToNext();
}
cursor.close();
return activities;
}
Another problem is that getDay() method is deprecated...what should I replace with that to have the same effect (compare the day the row's timestamp represents to the day in the date that passed as an argument).
This query should solve your problem. I´ll explain it.
long curretTime = System.currentTimeMillis()
Cursor cursor = mDatabase.query(
PhysicalActivityDatabaseHelper.TABLE_NAME, //Table name
mColumns, //Queryed columns
PhysicalActivityDatabaseHelper.TIMESTAMP + " = " currentTime, //Select
null, null, null,
PhysicalActivityDatabaseHelper.TIMESTAMP + " DESC" //Order By
);
First of all you're going to get the current time in milis so you can compare it. Then you'll retrieve all the fields of the table (only if you want), then you will retrieve only the rows matching the Select part and order that resulset in base of the Order By.
Hope it helps!

Can't find a record in a SQLiteDatabase

In my application, I create a table for my database like this :
String action;
action= "CREATE TABLE ";
action+=TABLE_LIEUX;
action+="(Name TEXT NOT NULL PRIMARY KEY);";
base.execSQL(action);
I then add a record to this table with :
ContentValues valeur;
long InsertLine=-10;
valeur=new ContentValues(1);
valeur.put("Name","'"+name+"'");
InsertLine=getWritableDatabase().insert(TABLE_LIEUX,null,valeur);
The value I get for InsertLine is 1, as expected. But when I try to search for the row added with :
result=(SQLiteCursor)getWritableDatabase().query(TABLE_LIEUX,null,"Name='"+name+"'",null,null,null,null);
the SQLiteCursor result I get has a length of -1. And when I try to add the row again, I get an SQLiteException which indicates the row should be unique (so, despite the result of the search, the row is already in the database).
Any idea?
You must force the Cursor to read the returned data (by calling moveToFirst or something like that) before you can get the cursor's record count.
Furthermore, you must not quote values when using the ContentValues put function; the value in the database now contains superfluous quotes.
Why did you cast your query result to (SQLiteCursor)?
Query statements always return a Cursor object so bother with the cast.
Cursor result = getWritableDatabase().
query(TABLE_LIEUX, null, "Name='"+name+
"'", null, null, null, null);
String mString;
if(result != null && c.moveToFirst()) {
mString = result.getString(result.
getColumnIndex("Name"));
}
hope this helps.

Fetching single value from SQLite in android

I'm developing my firs app for android right now, I am using multiple tables to get and insert data. during the development and found myself fetching data from the table with has only two columns STATS(_id, stat_name). What my problem is? I have an activity with 10 buttons, and every button correlates with one stat_name. When users presses one of the buttons application is "going" to STATS table to get correct _id and then is inputting this _id to another table GAME_STATS(_id, PlayerId (fk), GameId(fk), StatsId(fk)(andmore)) on STATS._id = GAME_STATS.StatsId and I basicly have to do similar operation for PlayerId.
Right now, I'm doing it this way:
public String getStatId(String statName){
String statId = "Error";
Cursor c = mDb.query(STAT_TABLE, new String[] {AbstractDbAdapter.STAT_ID, AbstractDbAdapter.STAT_NAME}, AbstractDbAdapter.STAT_NAME+ " = " +statName, null, null, null, null);
int count = c.getCount();
if(count == 1){
c.moveToFirst();
statId = c.getString(c.getColumnIndex(AbstractDbAdapter.STAT_ID));
}
c.close();
mDb.close();
Log.d("FootballApp","StatId =" +statId);
return statId;
}
What my problem is, that I know that there SHOULD be only one value returned, and I still have to use Cursor, to do so. Also, in my opinion, it looks way to complicated and time consuming wo write all that code just to get one id from one table. I have 9 tables in my application, and I will have to write similar method every time I need _id from different table when I have, for example, only name.
Can someone tell me if there is easier way to do all that? Please :)
thanks! :)
I think it doesn't get much simpler than that. However you can make the method more generic so you can reuse the code:
public String getFromDb(String tableName, String select, String selectBy, String selectName){
String selection = "Error";
Cursor c = mDb.query(tableName, new String[] {select}, selectBy + "=" + selectName, null, null, null, null);
if(c.getCount() == 1){
c.moveToFirst();
selection = c.getString(c.getColumnIndex(select));
}
c.close();
mDb.close();
Log.d("FootballApp", select + "=" + selection);
return id;
}
Example usage:
int statID = getFromDb(STAT_TABLE, AbstractDbAdapter.STAT_ID, AbstractDbAdapter.STAT_NAME, statName);
That is about as simple as it gets, but Cursor.moveToFirst() returns false if the cursor is empty so you can cut out the c.getCount() call and just say if(c.moveToFirst()) instead. That will save you a little bit of typing :)

Categories

Resources