ORDER BY not sorting the records - android

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

Related

SQL in android dosent work

I want to update a row in a SQL table in a column (`click'). I can see the row in debug but it isn't recognized.
If click==0 so change to click==1.
Does someone know what is my mistake?
My code is:
public void UpdateClicked2(String name, int table) {
ContentValues values = new ContentValues();
String selectQuery = "SELECT * FROM " + MySQLiteGUESTS.TABLE_NAME
+ " WHERE " + MySQLiteGUESTS.COLUMN_TABLE + "=" + table;
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
GuestInfo comment = cursorToComment(cursor);
if (comment.getName().toString() != name)
cursor.moveToNext();
else {
if (comment.getClick() == 1) {
values.put(MySQLiteGUESTS.COLUMN_CLICK, 0);
} else
values.put(MySQLiteGUESTS.COLUMN_CLICK, 1);
}
}
String newString = MySQLiteGUESTS.COLUMN_NAME + " = " + name;
database.update(MySQLiteHelper.TABLE_NAME, values, newString, null);
}
if (comment.getName().toString() != name)
Instead of this
Use this:
if (comment.getName().toString().equals(name))
{
}

Database is not retrieving all rows instead getting only unique rows

I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.

Android sqlite select statement does not work well

I've got three table and i want make a query withe sql statement, but it does not work well because it does not give me all the possible results...
The code:
public void setsuchresultat(String pSearchword)
{
String[] table = new String[]{"tbl_A", "tbl_B", "tbl_C"};
String[] column = new String[]{"columnA", "columnB" }; // Type varchar(50) not null
String[] search = new String[]{"%" + pSearchword+ "%", pSearchword+ "%", "%" + pSearchword, pSearchword};
getdata(table,column,search);
}
public void getdata(String[] pTable, String[] pColumn, String[] pSearch)
{
for(String t:pTable)
{
for(String s : pColumn)
{
for(String k : pSearch)
{
Cursor c = this.db.rawQuery("SELECT * FROM " + t + " WHERE " + s + " LIKE '"+ k + "'", null);
if ((c.moveToFirst()) || c.getCount() > 0)
{
while(c.moveToNext())// Suchresultat abspeichern
{
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
}
}
}
}
}
}
I think problem is in your loop and if check.
Change
if ((c.moveToFirst()) || c.getCount() > 0)
{
while(c.moveToNext())// Suchresultat abspeichern
{
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
}
}
to
if (c.moveToFirst() || c.getCount() > 0) /* OR if (c != null && c.moveToFirst())*/ {
do {
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
} while(c.moveToNext());
}

Sqlite query Android

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

Garabage value in list

i'm populating a list view to view my record, i've the following code...
super.onCreate(savedInstanceState);
setContentView(R.layout.total);
ArrayList<Object> results = new ArrayList<Object>();
// -- SQLiteOpenHelper dbHelper = new DatabaseHelper(this, SAMPLE_DB_NAME, null, 1);
SQLiteDatabase myDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READONLY, null);
try {
/* Create the Database (no Errors if it already exists) */
myDB.execSQL("PRAGMA foreign_keys = ON;");
// -- openOrCreateDatabase(name, mode, factory)
// myDB = dbHelper.getReadableDatabase();
Cursor c = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAME, null, null, null, null, null, null);
Cursor d = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAMES, null, null, null, null, null, null);
/* Check if our result was valid. */
if (c != null && d != null) {
c.moveToFirst(); // it's very important to do this action otherwise your Cursor object did not get work
d.moveToFirst();
char cust_name = (char) c.getColumnIndex("cust_name");
char pro_name = (char) d.getColumnIndex("pro_name");
int pro_price = (int) d.getColumnIndex("pro_price");
/* Check if at least one Result was returned. */
if (c.isFirst() && d.isFirst()) {
int i = 0;
/* Loop through all Results */
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_name + " (" + pro_name + ": " + pro_price + ")");
} while (c.moveToNext()&& d.moveToNext());
}
}
} catch (SQLiteException e) {
} finally {
if (myDB != null)
myDB.close();
}
// -- android.R.layout.simple_list_item_1 is object which belong to ListActivity itself
// -- you only need to add list object in your main layout file
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, results));
}
total.xml
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="380dp"
android:cacheColorHint="#00000000" >
</ListView>
the data is successfully inserted to sqlite (confirmed from adb shell)...it gives me garbage value...can any one please figure out the issue....Thanks in advance
That is not garbage values references(memory) addresses, use below code it will work.
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_nameColumnIndex + " (" + pro_nameColumnIndex + ": " + pro_priceColumnIndex + ")");
} while (c.moveToNext()&& d.moveToNext());
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, (String[]) results.toArray(new String[0])));
Try changing the way you read your cursors. Something like that might be better:
//Get the indexes
int cust_name = cursor.getColumnIndex("cust_name");
int pro_name = cursor.getColumnIndex("pro_name");
int pro_price = cursor.getColumnIndex("pro_price");
try {
if(cursor.moveToFirst()){
while (!cursor.isAfterLast()) {
//Get the data
String cust_nameColumnIndex = cursor.getString(cust_name);
String pro_nameColumnIndex = cursor.getString(pro_name);
int pro_priceColumnIndex = cursor.getInt(pro_price);
//Move to next cursor item
cursor.moveToNext();
}
}
else {
Log.i(TAG, "Empty cursor");
//Do whatever
}
} catch (Exception e) {
Log.i(TAG, "Exception while reading cursor: " + e.getMessage());
//Do whatever
}
finally {
cursor.close();
}

Categories

Resources