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());
}
Related
Hello i get Null Array List From this Code:
public List<IndiviualUser> findBloodByBloodGroup(String final_blood_group)
{
List<IndiviualUser> userlist = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
String select = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL_4 + " = ' "+ final_blood_group + " ' " ;
Cursor cursor = db.rawQuery(select,null);
Log.d("FIND", "findBloodByBloodGroup"+ select);
if(cursor.moveToFirst())
{
do
{
IndiviualUser user = new IndiviualUser();
user.setName(cursor.getString(1));
user.setPassword(cursor.getString(2));
user.setBlood_Group(cursor.getString(3));
user.setBlood_Quantity(cursor.getString(4));
user.setMobile_No(cursor.getString(5));
user.setLat2(cursor.getDouble(6));
user.setLong2(cursor.getDouble(7));
userlist.add(user);
}
while (cursor.moveToNext());
}
Log.d("SELECT","THE MSG WAS SELECTED SUCCESSFULLY " + userlist);
return userlist;
}
And I Will Receive This userlist in Another Activity The Code is Below:
DataBaseHelper DBHepler;
String str1,s1,s2,s5;
double s3,s4;
DBHepler = new DataBaseHelper(Find_Blood_Now_Result.this);
List<IndiviualUser> indiviualUsers = DBHepler.findBloodByBloodGroup(str1);
for(IndiviualUser user: indiviualUsers)
{
s1 = user.getName();
s2 = user.getMobile_No();
s3 = user.getLat2();
s4 = user.getLong2();
s5 = user.getBlood_Group();
}
When i will SetText of All Strings it will give me Null Values,i hope you someone have Solution for this Thank You.
i have retrieved some values from DB using the query which is given below.
public Cursor getcredittranscation(String date)
{
String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
+ "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
+ "WHERE T.Trans_Date =? AND T.Trans_Type=? ORDER BY T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{date, "credit"});
return cursor;
}
And in main activity i want to show these results as a report. Activity code is as given below.
try{
db.open();
Cursor c = db.getdebittranscation(temp);
if (c.moveToFirst()) {
do {
DisplayDebitDetails(c);
debittotal(c);
} while (c.moveToNext());
}
db.close();
}catch (Exception e) {
// TODO: handle exception
Log.e("Retrive Debit Error ", " "+e.getMessage());
}
private void DisplayDebitDetails(Cursor c) {
String tempdebit = debitView.getText().toString() + " ";
tempdebit= " \t"+tempdebit+ "\n\t" +c.getString(0) + "\t\t\t"
+ c.getString(1) + "\t\t\t" + c.getString(2);
debitView.setText(tempdebit);
Log.e("debit", "Acc No :"+c.getString(0) +"Name :"+c.getString(1)+ "Trans Amnt :"+c.getString(2));
}
}
private void debittotal(Cursor c){
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
Retrieving and viewing all values is ok... But i need the sum of all values in String(2) . which is given in method debittotal(Cursor c). what is the error in that part ?? I am not getting total
you can use getCount() method
int number_of_records = cursor.getCount();
try this and make sure that debitTotalView.getText().toString() is not blank or null
initially that field value must be 0 otherwise it will give you NumberFormatException for invalid int value
replace
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
with
int tmp = Integer.parseInt(debiTotalView.getText().toString().trim());
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp+"");
Im trying to get the data of an entire column into a string array. My database contains two columns Id and Names. I want to read all the entries of the names column and put it into a array. Please help.
EDIT #1:
Im using the following code but i can get only one name with this code.
String query = "Select * FROM " + TABLE_APPS + " WHERE " + COLUMN_NAME + " = \"" + productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
cursor.moveToFirst();
name = cursor.getString(1);
cursor.close();
} else {
name = null;
}
db.close();
int total=0;
Cursor csr=sdb.query("tablename", null, null,null,null,null,null);
csr.moveToFirst();
while(!csr.isAfterLast())
{
total++;
csr.moveToNext();
}
String strarray[] = new String[total];
Cursor csrs=sdb.query("tablename", null, null,null,null,null,null);
csrs.moveToFirst();
int aray=0;
while(!csrs.isAfterLast())
{
strarray[aray]=csrs.getString(1);
aray++;
csrs.moveToNext();
}
I built a table in the database, and now I want to access the all of the values in a certain column. Finally, I want to put the data into byte[].
Part of my code:
db.execSQL("create table thing(id integer primary key" +
" autoincrement, name varchar(20))");
List<Integer> all = new ArrayList<Integer>();
String sql = " SELECT id from " + DB_NAME;
Cursor result = this.db.rawQuery(sql, null);
for (result.moveToFirst(); result.isAfterLast(); result.moveToNext()) {
all.add(result.getInt(0));
}
String[] fstr = (String[]) all.toArray();
for (String bstr : fstr) {
byte[] bbs = bstr.getBytes();
}
Use this code
String[] fstr = new String[result.getCount()] ;
do {
int posi = result.getPosition();
fstr[posi] =result.getString(0);
}while (result.moveToNext());
try this
Cursor c=this.db.rawQuery(sql, null);
if(c.getCount()>0)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
String str=c.getInt(0));// or c.getString();
}
}
else
{
Log.d(" Null value in cursor ", " null ");
}
c.close();
dbhelper.close();
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();
}