I have a ListView in my class, I have a cursor regarding a number x which is incrementing each time, I am using this cursor in a ListView but at the time when I am using this x only one row is showing in the ListView. I want to show all the lists regarding the incrementing value. My code is as follows:
if (cursor.moveToFirst()) {
do {
do {
int x = cursor.getInt(cursor.getColumnIndex("trainId"));
String s1 = "SELECT * FROM route_table WHERE trainId=" + x + " AND stationId=" + FromStationId + ";";
String s2 = "SELECT * FROM route_table WHERE trainId=" + x + " AND stationId=" + ToStationId + ";";
final Cursor c1 = SQ.rawQuery(s1, null);
final Cursor c2 = SQ.rawQuery(s2, null);
if (c1 != null && c1.moveToFirst()) {
i = c1.getInt(c1.getColumnIndex("_id"));
c1.close();
}
if (c2 != null && c2.moveToFirst()) {
j = c2.getInt(c2.getColumnIndex("_id"));
c2.close();
}
if (i < j) {
Toast.makeText(this, "My Train is:" + x, Toast.LENGTH_SHORT).show();
String fstring = "SELECT * FROM train_table WHERE _id=" + x + ";";
final Cursor c3 = SQ.rawQuery(fstring, null);
final ListView lv = (ListView) findViewById(R.id.tiimetable_list);
CursorAdapterTimeTable myc = new CursorAdapterTimeTable(this, c3);
lv.setAdapter(myc);
// List(x);
}
break;
} while (cursor.moveToNext());
continue;
} while (cursor.moveToNext());
Only one row is showing, because every time the query is executed a new adapter is created.
Try this to get all items where "_id" are greater than 0:
String fstring = "SELECT * FROM train_table WHERE _id > 0";
final Cursor c3 = SQ.rawQuery(fstring, null);
final ListView lv = (ListView) findViewById(R.id.tiimetable_list);
CursorAdapterTimeTable myc = new CursorAdapterTimeTable(this, c3);
lv.setAdapter(myc);
Related
I already did my code based on WIllJBD's suggestion
I want the table refresh the data when its clicked according to spinner, but my toast gave "Database Error". Here is the code for the selected item on spinner
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String tam = spDealer.getSelectedItem().toString();
String dealerID = in.getDealID(tam);
String queryrow = in.MatchDealerID(dealerID);
if (queryrow == dealerID)
{
Cursor c = in.getViewInfoBilling(queryrow);
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
mytable.addView(row);
}
in.close();
} else
{
Toast.makeText(Billing.this, "Data Error!!",Toast.LENGTH_LONG).show();
}
}
And here is my method:
public Cursor getViewInfoBilling(String id){
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID = id", null);
return mcursor;}
public String getDealID(String dealName) throws SQLException{
Cursor mCursor = db.query(Dealer_TABLE, null, ""+Col_DealerName+"=?", new String[]{dealName}, null, null,null);
if(mCursor.getCount()<1){
mCursor.close();
return "Not Exist";
}
mCursor.moveToFirst();
String tampDealID = mCursor.getString(mCursor.getColumnIndex(Col_DealerID));
mCursor.close();
return tampDealID;}
public String MatchDealerID(String tam){
String matchquery = "SELECT DealerID FROM SODashboard, Dealer " +
"WHERE SODashboard.TampDealerIDSOD = tam";
return matchquery;
}
Isnt the ID selected on spinner already same with the ID thats on DB? I already created MatchDealerID and getDealID to compare them.. what should I do make the table refreshes after clicked? Please help me to solve this issue... thank you
There is something wrong in this method.
public Cursor getViewInfoBilling(String id){
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID =" + id, null);
//OR
/*
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID =?", new String[] { id });
*/
return mcursor;}
There are two versions , try both , have good luck
I have a List of contacts with check box.When the user checks the check box i have updated my table field selectedValue with value=1 .Now what i want is i wamna get all the contacts in comma seperated way where selectedValue=1.So for that i have written a query.But my result is not desired.
For eg
I have 4 contacts A,B,C,D in a list.Now if user selects A and C from the list and when i fire that query to get the contacs comma seperated,this is what i get
A,A,C,C
I dont know why 2 values of A and C are comming
Code
public StringBuilder getCheckedContact() {
database = getWritableDatabase();
StringBuilder values = new StringBuilder();
String query = "Select * From " + contactTable + " where " + selectedContact + "=1";
Cursor c = database.rawQuery(query, null);
while (c.moveToNext()) {
for (int i = 0; i < c.getCount(); i++) {
values.append(c.getString(c.getColumnIndexOrThrow(contactName)));
if (i != c.getCount() - 1) {
values.append(",");
}
}
}
c.close();
database.close();
return values;
}
Your while loop loops over the results once, then the for loop loops over the results second time. If you select 4 contacts, you'd get 4*4=16 results.
Why did you add the inner for loop?
This could be rewritten as follows:
public StringBuilder getCheckedContact() {
database = getWritableDatabase();
StringBuilder values = new StringBuilder();
String query = "Select * From " + contactTable + " where " + selectedContact + "=1";
Cursor c = database.rawQuery(query, null);
boolean firstItem = true;
while (c.moveToNext()) {
if(firstItem)
firstItem = false;
else
values.append(",");
values.append(c.getString(c.getColumnIndexOrThrow(contactName)));
}
c.close();
database.close();
return values;
}
I'm trying to populate a list view from a SQLite db I can create the db and add items to it and display them in a TextView but for some reason not on a ListView
Is it that sData is the wrong type of object?
Can anyone help, please?
public void DBTest() {
SQLiteDatabase myDB = null;
String TableName = "myTable";
/* Create a Database. */
try {
myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (_id integer primary key autoincrement, name text, script text, su short);");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (name, script, su)"
+ " VALUES ('hello', 'reboot', 1);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("script");
int Column3 = c.getColumnIndex("su");
// Check if our result was valid.
c.moveToFirst();
String sData="";
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData = sData + Name + " " + Script + " " + su + "\n";
} while (c.moveToNext());
}
ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, sData));
} catch (Exception e) {
Log.e("Error", "Error", e);
} finally {
if (myDB != null)
myDB.close();
}
}
You will end up with a ListView with just one single item, the value of sData. You need to create a list such as:
c.moveToFirst();
ArrayList<String> sData = new ArrayList<String>();
if (c != null) {
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData.add(Name + " " + Script + " " + su);
} while (c.moveToNext());
}
ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, sData));
I also recommend you change your cursor looping to be similar to this:
// cursor left as it came from the database because it starts at the row before the first row
ArrayList<String> sData = new ArrayList<String>();
while (c.moveToNext()) {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData.add(Name + " " + Script + " " + su);
}
because at the moment you are not checking the return value of moveToFirst, and it may return false (meaning there are no rows), however your do-while loop means the cursor will be read at least once whether or not it has 0 rows, and if there are 0 rows, you app will crash.
String sData="";
try to make sData a String array. feed that into the adapter.
sData is no array try something like
ArrayList<String> sData = new ArrayList<String>();
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
String newData = Name + " " + Script + " " + su;
sData.add(newData);
} while (c.moveToNext());
}
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();
}
sqlite query for store all the data in single array.means I have a table where 8 fields are there and I want to retrive all the data in a single array and return array.
Can I do this?
Code from the comment below:
public String[] login1(String email) throws SQLException {
/* Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME
+ " WHERE email=? AND password=?",
new String[]{username,res});
*/
try {
/*Cursor c = db.rawQuery("select * from member where email ="
+ "\""+ email.trim() + "\""+" and password="
+ "\""+ res.trim() + "\"", null);
*/
Cursor c = db.rawQuery("Select usermasterid,invalidlogincount,password,"
+ "nextpage,status,user,businessnextpage "
+ "from member where email " + "\""+ email.trim()
+ "\"", null);
There is not enough info in your question, but it should be roughly like this(assuming your data is int):
public int[] getDBRowAsArray() {
int[] myArray = new int[8];
Cursor cursor = yourSQLiteOpenHelper.rawQuery("Your SQL query here", null);
for(int i = 0; i < 8; i++) {
myArray[i] = cursor.getInt(i);
}
return myArray;
}
I assume there are 8 records and not fields in the db.
public String[] getData(){
Cursor c = db.query(args...);
if(c != null && c.moveToFirst()){
int count = c.getCount();
String[] vals = new String[count];
for(int i = 0; i < count; i++){
vals[i] = c.getString(c.getColumnIndex(Table.COLUMN));
c.moveToNext();
}
c.close();
return vals;
}
return null;
}