Filling the list - android

In the below code I get data from database and add them to the court class, finally add the court class to the courtList.
But the final courtList's items are the same . All the data are the last data in the database.
How can I solve it? Where is my mistake?
Thank's
public List<Court> getListOfCourt(){
List<Court> courtList;
Court court= new Court();
String[] col= new String[]{
CourtTable.OFFICE_FILE_CODE,
CourtTable.CLIENT_ID,
CourtTable.COURT_DATE
};
SQLiteDatabase sd= getReadableDatabase();
Cursor cur= sd.query(CourtTable.TABLE_NAME, col, null, null, null, null,null);
courtList = new ArrayList<Court>() ;
if(cur!=null && cur.getCount()>0){
cur.moveToFirst();
do{
court.setOfficeFileCode(cur.getInt(cur.getColumnIndex(CourtTable.OFFICE_FILE_CODE)));
court.setClientId(cur.getInt(cur.getColumnIndex(CourtTable.CLIENT_ID)));
court.setCourtDate(cur.getString(cur.getColumnIndex(CourtTable.COURT_DATE)));
courtList.add(court);
}
while(cur.moveToNext());
}
return courtList;
}

Put this line " Court court= new Court(); " inside do block as first statement.

Related

Getting only the last value from cursor of sqlite android

Cursor getting first value as this
But returning last value as this.
Code for getting from cursor
BillInfo getContact(String date) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor query
Cursor cursor = db.query(TABLE_ID, new String[] { KEY_ID,
KEY_NAME, KEY_PRICE, KEY_DATE }, KEY_DATE + "=?",
new String[] { String.valueOf(date) }, null, null, null, null);
BillInfo contact = null ;
Array bill type
BillInfo bill[]=null;
int i=0;
Cursor code
if ( cursor.moveToFirst() ) {
bill=new BillInfo[cursor.getCount()];
do {
//Since both are in different classes
contact = new BillInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
bill[i]=contact;
}while(cursor.moveToNext());
}
return bill[i];
}
Code for loading the values on click
public void Load1(View v){
date1=date.getText().toString();
Doubleme d=new Doubleme(this);
BillInfo s;
Returning the value from get contact
s= d.getContact(date1);
info.append( s.toString());
}
Looks like, the value of i is fixed:
int i=0;
But inside of the cursor iteration loop you each time override the bill[i] with a new BillInfo reference. No wonder why the line:
return bill[i];
fetches the last row instead of the first one. I suggest getting rid of the while loop if you only need the first row.

SELECT and WHERE in android (SQlite)

I want to search if there are exact course_no, semester ,and year value in the table.
I problem is that I can only filter course_no.
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=?", new String[] { notiItem.getCourseNo() }, null, null, null);
When I tried to add other filter it doesn't seems to work
[Edited] Sorry for being not informative, the problem is that when I pass the below code filter don't work. Note that notiItem.getCourseNo() and notiItem.getYear() is a String.
The following column in the table is a TEXT.
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=? AND "+DatabaseHelper.KEY_COURSE_YEAR+"=?", new String[] { notiItem.getCourseNo() ,notiItem.getYear()}, null, null, null);
This is code the method I tried
public CourseItem searchToCourse(NotificationItem notiItem){
/**Check if exact course_no, semester, year of notiItem exist in Course Table
* return null if not found
*
*/
String [] columns = new String[]{ "*"};
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=?", new String[] { notiItem.getCourseNo() }, null, null, null);
Log.i("DATA SOURCE", "AFTER QUERY ");
if (cursor != null) {
cursor.moveToFirst();
}
CourseItem courseItem = CourseItemDataSource.cursorToCourseItem(cursor);
return courseItem;
}
How can I search multiple column at a time??

Android Sqlite concat two columns

I have made the concatenation so far, but in the results, it displays
UncleSam.
What I want to do is to put a space between the two columns so the result would be
Uncle Sam.
This is the code I'm working on:
public Cursor getAllPatients()
{
Cursor localCursor = //
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_FNAME + "||" + KEY_LNAME, KEY_DIAGNOSIS, KEY_LASTFFUP }, null, null, null, null, null);
if (localCursor != null)
localCursor.moveToFirst();
return localCursor;
}
from DBHelper.java
and
Cursor cursor = dbHelper.getAllPatients();
String[] data = new String[]{
DBHelper.KEY_FNAME + "||" + DBHelper.KEY_LNAME, DBHelper.KEY_DIAGNOSIS, DBHelper.KEY_LASTFFUP};
//
int[] to = new int[] {R.id.fullname, R.id.diagnosis, R.id.lastffup};
dataAdapter = new SimpleCursorAdapter(this, R.layout.custom_row, cursor, data, to, 0);
from my MainActivity.
Any help will do. Thanks.
You can concat like this:
Cursor localCursor = this.myDataBase.rawQuery("SELECT (KEY_FNAME || ' ' || KEY_LNAME) AS fullname, KEY_ID, KEY_DIAGNOSIS, KEY_LASTFFUP FROM DB_TABLE");
Your concated full name will be in the cursor column 'fullname'.
In main activity:
String[] data = new String[]{ "fullname", DBHelper.KEY_DIAGNOSIS, DBHelper.KEY_LASTFFUP};
(You should probably assign a DBHelper constant for "fullname").
Android Sqlite concat two columns
After a little conversation with author of this thread i suggest you to don't concat columns (you really don't need it) and concat Strings retrieved from Cursor. Your statement will be more human-readable and solution cleaner.
Explanation:
Generally is very useful and efficient approach to represent your table on application layer with objects which will represent tables. For example if you had table User, so create new class User and columns in table will be equal to properties in this class. This way is i guess pretty elegant (if someone else will see your code, he won't be confused and scared)
Finally you can simply concat fname and lname when you'll add them to ListAdapter
So i prefer this way:
List<User> users = new ArrayList<User>();
User u = null;
String query = "select * from Table";
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
do {
u = new User();
u.setFirstName(c.getString(c.getColumnIndex("fname")));
u.setLastName(c.getString(c.getColumnIndex("lname")));
...
users.add(u);
} while (c.moveToNext());
}
And then somewhere in ListAdapter you can do:
textView.setText(u.getFirstname() + " " + u.getLastName());
Hope it helps.
I finally got it working.
public Cursor getAllPatients()
{
Cursor localCursor = //
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_FNAME + "|| ' ' ||" + KEY_LNAME, KEY_DIAGNOSIS, KEY_LASTFFUP }, null, null, null, null, null);
if (localCursor != null)
localCursor.moveToFirst();
return localCursor;
}
and
Cursor cursor = dbHelper.getAllPatients();
String[] data = new String[]{
DBHelper.KEY_FNAME + "|| ' ' ||" + DBHelper.KEY_LNAME, DBHelper.KEY_DIAGNOSIS, DBHelper.KEY_LASTFFUP};
//
int[] to = new int[] {R.id.fullname, R.id.diagnosis, R.id.lastffup};
dataAdapter = new SimpleCursorAdapter(this, R.layout.custom_row, cursor, data, to, 0);

Retrieve data from SQLite database

inHow do i retrieve data from sqlite database from adapter class and insert to listview???
I'm having difficulty, been coding day & night and googling non-stop but i just don't understand the links when i open them up. I just start learning android programming recently on my own...
I have attach my code below
public Cursor RetrieveActivityCursor(String NRIC){
String where = NRIC;
Cursor cursor = _db.query(DATABASE_TABLE,new String[]{ MOBILE_HOUSE_VISIT_ID, ELDERLY_NAME,
ELDERLY_NRIC, ELDERLY_DATE_TIME, PHYSICAL_HEALTH_STATUS, MENTAL_HEALTH_STATUS} , where, null, null, null, null);
//Cursor cursor = _db.query(DATABASE_TABLE, new String[] { ELDERLY_NAME,
//ELDERLY_NRIC, DATE_TIME, PHYSICAL_HEALTH_STATUS, MENTAL_HEALTH_STATUS }, null, null, null, null, null);
return cursor;
}
this code is from my adapter class and have to pass in nric and return datetime value inserted into listview
im not too sure how to code to call this method.
If you are extending the SqliteOpenHelper for the database handling and using another class to which extends Activity, in which you have your ListView then, in your Activity class make the object of your class like,
YourDBClass helperDB;
helperDB = new HelperDB(YourActivityClass.this);
And to retrive the data from the Database.
Make Cursor reference like,
Cursor cursor;
And then, do like this,
cursor = helperDB.RetrieveActivityCursor(NRIC);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
// here you have to collect the data in the collection object.
cursor.moveToNext();
}
cursor.close();
That's it! And you have done with retriving data from database
you need iterate cursor, like this:
Cursor cursor = RetrieveActivityCursor(NRIC);
if (cursor != null && cursor.moveToNext())
do {
String str = cursor.getString(cursor.getColumnIndex("your_column"));
// do something, your code
} while (cursor.moveToNext());
Where you like to retrieve the date value do the below over there.
Cursor cursor = RetrieveActivityCursor(NRIC);
if(mCursor.moveToFirst()) {
do{
String date_time = cursor.getString(cursor.getColumnIndex(column_name));
} while(mCursor.moveToNext());
}
cursor.close();

Android- Getting a single value from a database table using cursor

I'm using cursors to retrieve data from a database. I know how to retrieve entire columns to use on listviews and such, but I'm struggling to find a way to retrieve a single value.
Let's say I have a table with two columns ("_id" and "Name") and I have ten records (rows) in that table. How would I get, for example, the Name in the third row? Considering I defined a cursor that reads that table:
public Cursor getMyNameInfo() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "MyNames";
qb.setTables(sqlTables);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToFirst();
return c;
}
Instead of c.moveToFirst() use c.moveToPosition(2) (Cursor indexes are zero-based hence '2' is the third record).
Remember to check that the Cursor has valid data first though.
EDIT:
Once you've moved the cursor to the 3rd record as I explain above, use the following to just get the value of the "Name" column.
String theName = c.getString(getColumnIndex("Name"));
Cursor cursor = dbHelper.getdata();
System.out.println("colo" + cursor.getColumnCount() + ""
+ cursor.getCount());
cursor.moveToFirst();
if (cursor != null) {
while (cursor.isAfterLast() == false) {
String chktitle = title.trim().toString();
String str = cursor.getString(cursor.getColumnIndex("title"));
System.out.println("title :: "
+ cursor.getString(cursor.getColumnIndex("title")));
System.out.println("date :: "
+ cursor.getString(cursor.getColumnIndex("date")));
System.out.println("desc :: "
+ cursor.getString(cursor.getColumnIndex("desc")));
if (chktitle.equals(str) == true) {
tvAddfavorite.setText("Remove Favorite");
break;
}
cursor.moveToNext();
}
}
cursor.close();
Add a WHERE clause:
qb.appendWhere("_id = 2");
Thanks to the answers above I created the following method to give the value of an item from another column but in the same row.
public String getValueFromColumn(int position, String tableName, String columnToGetValueFrom) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tableName);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToPosition(position);
String neededValue = c.getString(c.getColumnIndex(columnToGetValueFrom));
return neededValue;
}
Hope it helps anyone.

Categories

Resources