How to retrieving specific records from SQlite (Need Query) - android

I am working on apps in which I need retrieve specific records from one position to another. I have table Track_Detail with 20 records.
How to retrieve records from 1 to 10 in one list and 11 to 20 in another list?
Here my source code:
retrieve record from Track table in list view
public List<CatSetGet> getMainListRecords() {
List<CatSetGet> list = new ArrayList<CatSetGet>();
String selectQuery = "SELECT * FROM " + TRACK;
// like limit what query I needed here
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
} while (cursor.moveToNext());
}
db.close();
return list;
}
db.openDataBase();
mainlist= db.getMainListRecords();
azAdapter = new MySimpleArrayAdapter(Main.this,
new int[] { R.layout.common_list_item }, mainlist);
lv.setAdapter(azAdapter);
lv.setOnItemClickListener(this);

Use limit query.
Example of query:
SELECT * FROM myTable WHERE mColoumnID >= 1 AND mColoumnID <= 10;

Related

Query Database with an array list and get an array list of results back

I have setup an application which currently can lookup an input id with one on the database to then give a single result. E.g. user enters id = 1 , database contains a record with an id of 1 then returns the name or number etc...
Now I want to improve the system slightly by querying my database with an arraylist which contains a range of id's e.g. 3, 456, 731 etc... which I want my database to search for. I have also grouped multiple values to certain id's for example the database might search for an id of 3 it will then find 5 results I want it to return the telephone number of each one of those results into another arraylist which I can print to the logs.
I hope I have explained this enough, but please ask questions if you require more information.
The code below demonstrates the modified version of the query used to gain a single result, but I cannot see what I'm doing wrong to gain multiple results.
Activity....
// New array list which is going to be used to store values from the database
ArrayList<String> contactsList;
// This arrayList has been received from another activity and contains my id's
ArrayList<String> contacts = intent.getStringArrayListExtra("groupCode");
// The database which i'm using
ContactDBHandler contactDBHandler = new ContactDBHandler(getApplicationContext(), null, null, 1);
//getAllValues is used to pass my arraylist id's to the database.
contactsList = contactDBHandler.GetAllValues(contacts);
// Simple log statement to loop and display results
for (int i = 0; i < contactsList.size(); i++){
Log.i("Numbers", contactsList.get(i));
}
ContactDBHandler
Query
// I'm telling it to get the contact number from the contact_list
// when the groupcode matches the code recieved.
public ArrayList<String> GetAllValues(ArrayList groupCode)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
String alarmName = "";
ArrayList<String> list = new ArrayList<>();
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code=?", new String[]{groupCode+ ""});
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}
Thanks
Can you see where I have gone wrong?
Try this:
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (" + TextUtils.join(",", Collections.nCopies(groupCode.size(), "?")) + ")", groupCode.toArray(new String[groupCode.size()]));
Your current code fails to pass the list in the sql-format: = does only support single values, for lists you have to use IN.
Your code would result in a query like this:
SELECT contact_number FROM contact_list WHERE grp_code=["some_id","other_id"]
But what you need (and my code produces) is:
SELECT contact_number FROM contact_list WHERE grp_code IN ('some_id','other_id')
References:
SQL query to find rows with at least one of the specified values
WHERE IN clause in Android sqlite?
IN clause and placeholders
https://developer.android.com/reference/android/text/TextUtils.html#join(java.lang.CharSequence,%20java.lang.Iterable)
You cannot pass an ArrayList to an SQLQuery. To check for multiple values in the same field you have to use the 'in' keyword.
Ex:
SELECT * FROM `table1` where column in ( 'element1', 'element2', 'element3')
In your case,
String str = "";
for(String s: groupCode){
str = str+","+"\'"+s+"\'";
}
//to remove the extra ' in the begining
str = str.substring(1);
return str;
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (?)", new String[]{str});

i want to store id and name of one table from sqlite database to spinner. i need to store two column inforamtion in one spinner

here i get only single value and save it in spinner but i want to retrieve two column value in one spinner
public List<String> getAllLabels1(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT DISTINCT WeatherPrediction.CropID as CropID, Crop.Name as Name FROM Crop INNER JOIN " +
"WeatherPrediction ON Crop.CropID = WeatherPrediction.CropID order by Name";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}

Cursor returning 0

I have a function where I want to get the sum of values on a MySQL database table's row. This is my code:
public int getSum(int var) {
int x=0;
// Select All Query
String selectQuery = "SELECT sum(amount) FROM donations WHERE aid = '"+aid+"'";
SQLiteDatabase db = openOrCreateDatabase("shareity", Context.MODE_PRIVATE, null);
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
x = cursor.getInt(0);
} while (cursor.moveToNext());
}
// return contact list
Log.d("id", "Id" + "," + x);
return x;
}
And I'm calling this in the onCreate() like this:
getSum(idk);
where idk is an integer. But my this returns 0. Can I know why please? The table's row I want to get the sum of, is also integer.
Finally figured it out. The problem was with the SQLite database. I had to use a php file to download the database from the mysql server to the local Sqlite server and then loop through it

java.lang.IllegalStateException: Couldn't read row 0, col 10 from CursorWindow

Please check following code:
List<Database> zaznamy = new ArrayList<Database>();
String selectQuery = "SELECT X FROM Data WHERE LEVEL_1 =-24 AND LEVEL_2 =-48 AND LEVEL_3 =-55 AND LEVEL_4 =0";
File dbfile = new File("/sdcard/rtls/Databases/"+DBName );
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
Cursor cursor = db.rawQuery(selectQuery,null);
String bodX="empty";
if (cursor.moveToFirst())
{
do {
Database zaznam = new Database();
zaznam.setX(Integer.parseInt(cursor.getString(10)));
zaznamy.add(zaznam);
} while (cursor.moveToNext());
for (Database cn : zaznamy)
{
Log.d("X: ", Integer.toString(cn.getX()));
bodX = (cn.getX()+ "//").toString();
Log.d("X", bodX);
}
}
It says it Couldn't read row 0, col 10 from CursorWindow. I´ve tested the database with SQLite browser. Database has exactly 1 X at column 10, row 0. SQL query is working correctly I believe. Can someone tell me, why it cant be read? Or where is mistake?
EDIT:
corrected the code to:
do {
Database zaznam = new Database();
zaznam.setX(cursor.getInt(10));
zaznamy.add(zaznam);
} while (cursor.moveToNext());
because of integer value of 10th column, but still no luck. Same error
Your query has only one column in projection - column 'X'. That column has index 0 in query projection so to make your code work change your loop to looks like this:
do {
Database zaznam = new Database();
zaznam.setX(cursor.getInt(0));
zaznamy.add(zaznam);
} while (cursor.moveToNext());
To avoid that kind of problems in the future use following:
cursor.getInt(cursor.getColumnIndexOrThrow("X");
Remember that column index is related to query projection and not the sequence of columns in your database, so for example when you write "select B A C from SOME_TABLE" column B will have index 0 and column A will have index 1 etc. even if in your database they are in alphabetical order A B C.
I was having the same issue. For me. A simple work around may be:
// query database and populate an ArrayList
private void getDataFromDatabase() {
Cursor cursor = dbConnector.getSomeData();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
for(int i = 0; i < cursor.getCount(); i++) {
// get column data from database and add it to ArrayList
anArrayList.add(cursor.getString(cursor.getColumnIndexOrThrow("Attr")));
cursor.moveToNext();
} // end for
} // end if
dbConnector.close();
} // end getDataFromDatabase
WHERE "Attr" is the Attribute/column name you wish to query and the anArrayList is the ArrayList you want to store the data in.

how to retrieve particular records from SQLite in android

I need to get data from DB & displayed it as list with pagination.
i.e. If i retrieved 4 items..i need to display first 2 items in first page.
When i click next button.,remaining 2 items should be displayed which replaces old 2.
How could i restrict data from DB as 2 like that?
My code..
db.open();
// db.insertTitle("Money");
//db.insertTitle("make");
//db.insertTitle("make");
//db.insertTitle("make");
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
String firstName = c.getString(c.getColumnIndex("user"));
results.add( firstName );
} while (c.moveToNext());
}
setListAdapter(new ArrayAdapter<String>(DisplayAll.this, android.R.layout.simple_list_item_1,results));
db.close();
}
My DBAdapter..
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_USER,
},
null,
null,
null,
null,
null);
}
Please try this
public Cursor getAllRecords(int page,int totalRecord)
{
return db.rawQuery("select * from your_table_name limit "+(page-1)*totalRecord+","+totalRecord, null);
}
Where limit = how many record you want at a time if you want 2 record then pass limit = 2 if 10 record then set limit = 10..
and page = first initial page variable with 1 and when second time you fetch next record increase your page variable by 1 .

Categories

Resources