public String getCourse_info (String courseID) {
String[] columns = new String[] {KEY_COURSE_ID, KEY_COURSE_TITLE, KEY_COURSE_CNUMBER, KEY_COURSE_SUBJECT, KEY_COURSE_DAYS,
KEY_COURSE_START_TIME, KEY_COURSE_END_TIME, KEY_COURSE_PROFESSOR, KEY_COURSE_BUILDING, KEY_COURSE_ROOM_NUMBER };
Cursor c = ourDataBase.query(DATABASE_TABLE_COURSES, columns, KEY_COURSE_ID + "=?", new String[]{courseID}, null, null, null);
String result = "";
int iCid = c.getColumnIndex(KEY_COURSE_ID);
int iCtitle = c.getColumnIndex(KEY_COURSE_TITLE);
int iCcnumber = c.getColumnIndex(KEY_COURSE_CNUMBER);
int iCsubject = c.getColumnIndex(KEY_COURSE_SUBJECT);
int iCdays = c.getColumnIndex(KEY_COURSE_DAYS);
int iCstart_time = c.getColumnIndex(KEY_COURSE_START_TIME);
int iCend_time = c.getColumnIndex(KEY_COURSE_END_TIME);
int iCprofessor = c.getColumnIndex(KEY_COURSE_PROFESSOR);
int iCbuilding = c.getColumnIndex(KEY_COURSE_BUILDING);
int iCroom_number= c.getColumnIndex(KEY_COURSE_ROOM_NUMBER);
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(iCid)+ " " +c.getString(iCtitle)+ " "+c.getString(iCcnumber)+" "+ c.getString(iCsubject) + " "+
c.getString(iCdays)+ " "+ c.getString(iCstart_time)+ " "+ c.getString(iCend_time) +" " +
c.getString(iCprofessor) + " "+ c.getString(iCbuilding) + " " + c.getString(iCroom_number)+ "\n" ;
}
Log.d("hello", result+"test2");
return result;
}
ok, I'm trying to run this code on one of the table in Database. Thing is if I pass the first course_id in database, it works perfectly. But when I try to put 2nd or any course_id after that, the string doesn't display anything.
Maybe because the condition you have used
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext())
is failing.
Means the cursor is reaching the end of the records after retrieving the first record.
Use these statements and check that its not going to the end of the table after retrieving the first record.
if (c.moveToFirst()) {
Log.d("Entering","moveToFirst");
do {
int iCid = c.getColumnIndex(KEY_COURSE_ID);
int iCtitle = c.getColumnIndex(KEY_COURSE_TITLE);
int iCcnumber = c.getColumnIndex(KEY_COURSE_CNUMBER);
int iCsubject = c.getColumnIndex(KEY_COURSE_SUBJECT);
int iCdays = c.getColumnIndex(KEY_COURSE_DAYS);
int iCstart_time = c.getColumnIndex(KEY_COURSE_START_TIME);
int iCend_time = c.getColumnIndex(KEY_COURSE_END_TIME);
int iCprofessor = c.getColumnIndex(KEY_COURSE_PROFESSOR);
int iCbuilding = c.getColumnIndex(KEY_COURSE_BUILDING);
int iCroom_number= c.getColumnIndex(KEY_COURSE_ROOM_NUMBER);
result = result + c.getString(iCid)+ " " +c.getString(iCtitle)+ " "+c.getString(iCcnumber)+" "+ c.getString(iCsubject) + " "+
c.getString(iCdays)+ " "+ c.getString(iCstart_time)+ " "+ c.getString(iCend_time) +" " +
c.getString(iCprofessor) + " "+ c.getString(iCbuilding) + " " + c.getString(iCroom_number)+ "\n" ;
}
}
while (c.moveToNext());
}
c.close();
}
If its going to the last record then it will yield ArrayIndexOutOfBoundsException.
See for sqlite query that try fro this code,
Cursor query = db.query(table, columns, selection, selectionArgs, groupBy,
having, orderBy);
if (query.getCount() > 0) {
for (int i = 0; i < query.getCount(); i++) {
int KEY_COURSE_ANY = query.getString(query.getColumnIndex(KEY_COURSE_ANY));
}
}
Related
I need (for practicing reasons) to change all the contacts to be starred. So I use this code to read all the contacts in a thread:
Looper.prepare(); //To avoid error: Can't create handler inside thread that has not called Looper.prepare
CursorLoader oCursorLoader = new CursorLoader(ContextoGlobal, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Cursor oCursor = oCursorLoader.loadInBackground();
int contactId = oCursor.getColumnIndex(ContactsContract.Contacts._ID);
contactId = oCursor.getColumnIndex(ContactsContract.RawContacts._ID);
int starred = oCursor.getColumnIndex(ContactsContract.Contacts.STARRED);
int number = oCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
int name = oCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
oCursor.moveToFirst();
if(oCursor.isAfterLast()==false) {
do {
String sId = oCursor.getString(contactId);
String phNumber = oCursor.getString(number);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + phNumber + "\nStarred: " + sStarred;
} while (oCursor.moveToNext());
}
This code works and iterates through all the contacts in the device, displaying if they are starred or not.
My problem comes when I want to modify the starred field in the loop:
...
do {
String sId = oCursor.getString(contactId);
String phNumber = oCursor.getString(number);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + phNumber + "\nStarred: " + sStarred;
ChangeStarred(sId, true); <-- HERE!!!!!!!!
} while (oCursor.moveToNext());
...
This is the ChangeStarred() function:
private boolean ChangeStarred(String sContactId, boolean bStarred){
ContentValues values = new ContentValues();
if(bStarred==true)
values.put(ContactsContract.Contacts.STARRED, 1);
else
values.put(ContactsContract.Contacts.STARRED, 0);
//int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values, ContactsContract.Contacts._ID + "= ?", new String[] { sContactId });
int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values, ContactsContract.RawContacts._ID + "= ?", new String[] { sContactId });
if(iAffectedRows == 0)
return false;
return true;
}
This function always returns FALSE. No rows are updated.
As you can see in the code comments, I have tried with Contacts._ID and RawContacts._ID
I also have WRITE_CONTACTS permission granted.
This is how I solved:
Looper.prepare(); //To avoid error: Can't create handler inside thread that has not called Looper.prepare
CursorLoader oCursorLoader = new CursorLoader(ContextoGlobal, ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Cursor oCursor = oCursorLoader.loadInBackground();
int contactId = oCursor.getColumnIndex(ContactsContract.Contacts._ID);
int starred = oCursor.getColumnIndex(ContactsContract.Contacts.STARRED);
int name = oCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
oCursor.moveToFirst();
if(oCursor.isAfterLast()==false) {
do {
String sId = oCursor.getString(contactId);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + "\nStarred: " + sStarred;
ChangeStarred(sId, true);
} while (oCursor.moveToNext());
}
And the ChangeStarred() function:
private boolean ChangeStarred(String sContactId, boolean bStarred) {
ContentValues contentValues = new ContentValues();
if(bStarred==true)
contentValues.put(ContactsContract.Contacts.STARRED, 1);
else
contentValues.put(ContactsContract.Contacts.STARRED, 0);
int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, contentValues, ContactsContract.Contacts._ID + "=" + sContactId, null);
if(iAffectedRows > 0)
return true;
return false;
}
I have two parameter (tenant_id and dateIn). with my query below I always get -1 as result. I don't know where is the issue in query statement.
Kindly note that the date format in data base is dd/MM/yyyy
public final static String ID = "id";
public final static String TENANT_ID = "tenant_id";
public final static String DEBT_CURRENT_VALUE = "debt_current_value";
public final static String DEBT_SUM = "debt_sum_value";
public final static String DEBT_DATE = "debt_date";
public long getTenantDateDebtByIdandDate(long id, String dateIn) {
long idout = -1;
String[] columns = {ID, TENANT_ID, DEBT_CURRENT_VALUE,DEBT_SUM, DEBT_DATE };
String selection = "TENANT_ID = " + id + " AND " + "DEBT_DATE < " + "date("+ dateIn+")";
Cursor cursor = mDatabase.query(TABLE_TENANT_DEBT, columns, selection, null, null, null, null);
if (cursor.moveToNext()) {
idout = cursor.getLong(cursor.getColumnIndex(DEBT_DATE));
}
cursor.close();
return idout;
}
I think there is a mistake with the column names at least
Isn't this: String selection = "TENANT_ID = " + id + " AND " + "DEBT_DATE < " + "date("+ dateIn+")"; checking columns named TENANT_ID and DEBT_DATE, when actually you want to check columns "tenant_id" and "debt_date".
So I think the selection should be instead: String selection = TENANT_ID + " = " + id + " AND " + DEBT_DATE + " < " + "date("+ dateIn+")";
I'm not so familiar with dates in sqlite, but if the date function is not working in this case, maybe you should look into the strftime function of sqlite
Also, I would recommend using the where arguments. So basically instead of saying TENANT_ID + " = " + id, you would say TENANT_ID + " = ?", and change the DEBT_DATE in similar way. Then you would give the query function one more array having the values that are then used in the places of the questionmarks in the order they are in the array. The query is safer that way, see more details why to use the where args and a complete example in this Stackoverflow thread in case you are interested.
Finally with the feedback of Peter and some resaerch I found the solution
public String getTenantDateDebtByIdandDate(long id, String dateIn) {
String idout = "";
String[] columns = {TENANT_ID, DEBT_DATE };
String selection = TENANT_ID + " = '" + id + "' AND " + DEBT_DATE + " < " + "'"+ dateIn + "'";
Cursor cursor = mDatabase.query(TABLE_TENANT_DEBT, columns, selection, null, null, null, null);
while (cursor.moveToNext()) {
idout = cursor.getString(cursor.getColumnIndex(DEBT_DATE));
}
cursor.close();
return idout;
}
hello am new at android development. am creating an app that has four columns. Student, age, number and class...but the data displayed under the columns is disorganized, how can i organize the data displayed in proper columns?
here is my code.
my database name = schooldatabase
String[] columns = new String[] { KEY_ROWID, KEY_STUDENT, KEY_AGE, KEY_ID_NUMBER, KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
ArrayList<String> mArrayList = new ArrayList<String>();
int IROW = c.getColumnIndex(KEY_ROWID);
int ISTUDENT = c.getColumnIndex(KEY_STUDENT);
int IAGE = c.getColumnIndex(KEY_AGE);
int INUMBER = c.getColumnIndex(KEY_ID_NUMBER);
int ICLASS = c.getColumnIndex(KEY_CLASS);
// ////////////////////////////////////////////////////////
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
// ////////////////////////////////////////////////////
result = result + c.getString(IROW) + " " + c.getString(ISTUDENT)
+ " " + " " + c.getString(IAGE) + " " + " "
+ c.getString(INUMBER) + " " + " " + c.getString(ICLASS)
+ "\n";
}
return result;
You can use rawQuery to query items as what you want column like:
ourDatabase.rawQuery("select <your columns order>" + from + DATABASE_TABLE,null);
And I think whether the data is ordered depends on how you resolve this data,when you get all data you can handle these as you want order.
I am trying to do Order by to fetch the records from higher to lower values , but the sorting is not happening, i am getting the records randomly.
Here is my code , please let me know , where i am going wrong:
public void fetchTopRecords() {
int i = 0;
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " ASC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
i++;
} while (c.moveToNext());
}
}
use the below code it will work :
public void fetchTopRecords() {
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " DESC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
} while (c.moveToNext());
}
}
I am currently creating a database to store a list of names and coordinates of service stations. However I cannot view the database when i click the view button. Here is my code: `
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_COORDINATES};
Cursor c = myDatabase.query(DATABASE_NAME, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iCoordinates = c.getColumnIndex(KEY_COORDINATES);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iCoordinates) + "\n";
}
return result;
}`
Does anybody see a problem with this code?
Your cursor might not contain any rows. If so, c.getString() will throw exception.
moveToFirst() returns false on error. Do your loop like this:
if (c.moveToFirst())
{
do
{
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString + "\n";
} while (c.moveToNext())
}
then you can deal with why your table has no rows if this is in fact the case...