Access a column from database - android

Now I want to access an entire column from database and then compare it with some text that I have stored...but I am getting no idea on how to do that..So can someone please help me with this...

Entire column? You mean all the values for a given column accross all records?
You should iterate the ResultSet obtained and start comparing the values (for example - if you iterate using "rs" object of ResultSet, you should compare:
String valueFromDB = rs.getString("myColumn");
String someTextStored = .... //the text being stored
if (valueFromDB != null) {
if (someTextStored.equals(valueFromDB) {
//Comparison succeeded - implement some logic here for handling success
}
}
And the above code should be inside a loop code that iterates over the ResultSet and
uses the "next" method to obtain the next record.

Hope this helps you
public ArrayList<String> getValues(){
Cursor cursor = null;
SQLiteDatabase db = getReadableDatabase();
Log.v("done","getting rows ");
cursor = db.rawQuery("SELECT YourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
list_values.add(cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
return list_values;
}
Now you are having all the values of a particular column you can compare it from this array list.

Related

displaying the value of a particular row

I am trying to display value of a particular row in android to check if a particular updation. Can I made it successful or not? But as the return type is cursor I don't know how to fetch it. So pls help me.
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
return res;
}
Try this...
ArrayList<HashMap<String, String>> dataList = new ArrayList<>();
call your method to get data as arraylist of hashmap
dataList.addAll(loginDataBaseAdapter.getData(id));
or
dataList = loginDataBaseAdapter.getData(id);
in db_class
public ArrayList<HashMap<String, String>> getData(String id) {
ArrayList<HashMap<String, String>> returnArray = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
if (res != null && res.getCount() > 0) {
if (res.moveToLast()) {
do {
HashMap<String, String> getdatamap = new HashMap<String, String>();
getdatamap.put("KEY_ONE", res.getString(1));
getdatamap.put("KEY_TWO, res.getString(2));
returnArray.add(getdatamap);
}while (res.moveToPrevious());
}
}
res.close();
return returnArray;
}
Now you can use the values in arraylist to make your view
You can follow the below code:
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
if (res != null) {
res.moveToFirst();
}
String firstColumnValue = res.getString(0);
String secondColumnValue = res.getString(1);
And close the database after retrieving values:
db.close();
If you want to get column value by its name, then use the following code:
String value = res.getColumnIndex("column_name");
Get row value as a String. Then return string value.
public String getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
if (res.getCount() > 0) {
res.moveToFirst();
String s = res.getString(res.getColumnIndex("id"));
return s;
}
There are two factors that need to be considered when retrieving data from a cursor; which row (position within the cursor) and then column and it's type.
To position the Cursor you use one of the Cursor's move methods. These are :-
move, which moves the cursor relevant to it's current position.
moveToFirst
moveToLast
moveToNext
moveToPosition and
moveToPrevious
All return true if the move could be performed otherwise false.
A cursor can be empty and have no rows, so movetoFirst would return false.
One of the more common usages is :-
while (cursor.moveToNext) {
.... cursor action(s) here.
}
A Cursor will initially be positioned to before the first row i.e. it's position is -1 and can be set using moveToPosition(-1).
The Cursor's getPosition method will retrieve the current position, noting that the first row is position 0.
Column's in rows are accessed according to the offset (which column) and the Cursor's get???? (where ???? represents type) methods are used to retrieve the data from the row/column (there are other get.... methods e.g. getPosition as above). The methods for retrieving the data are:-
getBlob (retrieves a byte array).
getDouble
getFloat
getInt
getLong
getShort
getString
All take a single parameter, an integer that is the column's offset within the cursor (which is not necessarily the offset in the table).
You can use any on any type of data, with the exception of blobs. An attempt to use any, except getBlob, on a BLOB will result in an exception.
However, the results, can vary e.g. if you use get, for example assuming column with offset 0 contains *rumplestilskin then :-
cursor.getString(0) will return rumplestiltskin
cursor.getDouble(0) will return 0 as a double.
cursor.getInt(0) will return 0 as a float.
.....
In short, you should use the appropriate get method, otherwise the results could be confusing.
Hard coding column column offsets, often results in issues therefore it is generally better to use column names in conjunction with the Cursor's getColumnIndex method. This takes a String, the column name, as a parameter and returns the offset of the column.
Applying the above to the question:-
Code that could be useful (i.e. it retrieves data) could be :-
Cursor csr = db.getData(myid);
while (csr.moveToNext) {
long id_of_the_row = csr.getLong(csr.getColumnIndex(yourDatabaseHelperClass.id));
}
Noting:-
if (moveToFirst(myid)) { .... } could be considered more correct but assuming that just a single row exists bot moveToFirst and moveToNext, as coded, produce the same result.
Assuming that the id column is an alias of the rowid, then rowid is stored as a long and should properly be extracted as a long.
yourDatabaseHelperClass.id will not be correct, rather you would replace it with the class that extends SQLiteOpenHelper (the class that contains your getData method), it also assumes that variable id has public access.
Links that may be useful or of interest:-
Cursor
How flexible/restricive are SQLite column types?
(includes examples of how some of the Cursor get???? methods retrieve data)
Are there any methods that assist with resolving common SQLite issues?

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});

how to retrieve a single row data from cursor android?

I want to retrieve the data from cursor when pressing the button. For the first time I want to show first row data, after pressing button I need to show second row data. How can I achieve this? I have more number of rows in my database.
While I am using following code I am getting last row data.
for(int i=0;i<cursor.getColumnCount();i++){
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
}
For the first timebutton click,
cursor.moveToFirst();
Then keep on using,
cursor.moveToNext()
until end of the row.
To be more specific:
if (cursor.moveToFirst()) {
do {
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
} while(cursor.moveToNext();
}
You forgot to move your cursor to first row. Please try this:
if (cursor.moveToFirst())
{
do
{
String path=cursor.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(cursor.getString(1));
brewerimage.setImageBitmap(bitmap);
} while (cursor.moveToNext());
}
You can take first row of data like this
Replace 0 in
cursor.getString(0);
with your value;
if (cursor.moveToFirst())
{
do
{
String path=cursor.getString(0);
title.setText(path);
} while (cursor.moveToNext());
}
Try this hope it will help you:
try {
if (cursorOne.moveToFirst()) {
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
//no need to look up column index since you already know it due to the projection used
}
} finally {
cursorOne.close();
}
Try this..
if (cursor.getCount() > 0) {
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
}
}
After read your comments i have one idea. That is leave the query as like now.
Step 1
Save your data in static ArrayList or POJO class
Step 2:
Whenever you want to click button just increase the cont +1 and save it. Use this count as position and easily get values.
You can get particular at the given position as like.
public void getRowAt(int posAt){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+tableName+" LIMIT 1 OFFSET "+posAt, null);
int count = cursor.getCount();
while (cursor.moveToNext()){
// here your can get your row data.
}
cursor.close();
db.close();
}
Are you using database so you getting record from database am i right ?
so you getting record in cursor so from which column you getting data you have to pass that column name in your cursor so you are getting result .
example :
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
myDatarecordModel = new DataRecordModel();
myDatarecordModel.setStrDataRecordingID(cursor.getString(cursor.getColumnIndex(AppStackFields.DATARECORDING_ID)));
} while (cursor.moveToNext());
}
cursor.close();

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

cursor return column names instead of values

I want to fetch data from table "student" in SQLite android database
and here is the method that I use to retrieve the data
public Cursor getAllStudent(){
SQLiteDatabase db= helper.getWritableDatabase();
String[] columns={"_id",
"'reg_number'",
"'School_id'",
"'class_id'",
"'first_name'",
"'last_name'",
"'PPN'",
"'photo'",
"'CyncStatus'"};
Cursor cursor=null;
try {
cursor = db.query("student",columns,null, null,null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("select student failed: %d", e.toString());
}
return cursor;
}
and this is how I iterate through the result
Cursor c1 = studentHelperAdapter.getAllStudent();
c1.moveToFirst();
while (!c1.isAfterLast()){
String reg = c1.getString(1); // return column name not value
String name = c1.getString(4); //return name column not value
String reg = c1.getString(5); //return name column not value
c1.moveToNext();
}
c1.close();
and I have tried to add this line below to see cursor content and I realized that no data was fetched there are only column names
Log.d("AB cursor ",android.database.DatabaseUtils.dumpCursorToString(c1));
Anyway, there 2 similar questions but none of the solutions solved my problem
Get the field value with a Cursor
How to get field value instead of column name?
I look forward to see your answer here, thanks
I think your column names should just be strings.
"reg_number" not "'reg_number'"
also make sure that you are using correct types. Is the value stored in column "reg_number" really a String?

Categories

Resources