Get values from database to ListView - android

I have written this fetchData() method to fill ListView with the values from database.
public void fetchData() {
database = helper.getReadableDatabase();
Cursor c = database.query(db.TABLE, null, null, null, null, null, null);
String[] fromDB={db.FULLNAME,db.YEAR};
int[] toView={R.id.tvName_lv,R.id.tv_birthday_lv};
adapter = new SimpleCursorAdapter(this, R.layout.listview_all, c, fromDB, toView);
lv.setAdapter(adapter);
}
It works fine. But when I try to use it this way, it gives an error.
public void fetchData() {
database = helper.getReadableDatabase();
Cursor c = database.query(db.TABLE, null, null, null, null, null, null);
String birthday=db.YEAR+" "+db.MONTH+" "+db.DAY;
String[] fromDB={db.FULLNAME,birthday};
int[] toView={R.id.tvName_lv,R.id.tv_birthday_lv};
adapter = new SimpleCursorAdapter(this, R.layout.listview_all, c, fromDB, toView);
lv.setAdapter(adapter);
}
I want to get [db.YEAR+" "+db.MONTH+" "+db.DAY] to the view [R.id.tv_birthday_lv]
Thanks in advance.
UPDATE:Error is "Unfortunately, App has stopped". FATAL EXCEPTION on LogCat

Related

How do you Populate ListView With SQLite?

My program crashes every time I try to run this method:
private void populateListView() {
Cursor cursor = myDB.getAllRows();
startManagingCursor(cursor);
String[] from = new String[] {ProductContract.ProductEntry.INPUT, ProductContract.ProductEntry.DATE};
int[] to = new int[] {R.id.t_input, R.id.t_date};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.display_row, cursor, from, to, 0);
ListView myList = (ListView) findViewById(R.id.display_listview);
myList.setAdapter(myCursorAdapter);
}
Here's my getAllRows method:
public Cursor getAllRows() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(true, ProductContract.ProductEntry.TABLE_NAME, ProductContract.ProductEntry.ALL_KEYS,
null, null, null, null, null, null);
if(c != null) {
c.moveToFirst();
}
return c;
}

retrivininbg single column from the Sqlite database to display it in listview

This is my cursor in database handler class for displaying single coloumn in a list view
public String getAllStringValues() {
ArrayList<String> yourStringValues = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(true, TABLE_PATIENT_GENERAL,
new String[] { KEY_PATIENT_NAME }, null, null, null, null,
null, null);
if (result.moveToFirst()) {
do {
yourStringValues.add(result.getString(result
.getColumnIndex(KEY_PATIENT_NAME)));
} while (result.moveToNext());
} else {
return null;
}
return KEY_PATIENT_NAME;
}
as I m fresher in android please tell me the exact flow and code thanks.

Concatenate 2 columns Android SQLite

So far I have this:
Cursor cursor = dbHelper.getAllPatients();
String[] data = new String[]{DBHelper.KEY_LNAME,
DBHelper.KEY_FNAME, DBHelper.KEY_DIAGNOSIS};
int[] to = new int[] {R.id.fullname, R.id.diagnosis};
dataAdapter = new SimpleCursorAdapter(this, R.layout.custom_row, cursor, data, to, 0);
dbHelper.close();
lv.setAdapter(dataAdapter);
lv.setTextFilterEnabled(true);
getAllPatients() method
public Cursor getAllPatients()
{
Cursor localCursor =
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_FNAME, KEY_LNAME, KEY_DIAGNOSIS }, null, null, null, null, null);
if (localCursor != null)
localCursor.moveToFirst();
return localCursor;
}
I want the columns FNAME, and LNAME to be as one but I'm confused how and where to put the concatenate operator + in the String array. Do you have any idea to do this? I would gladly appreciate your help. Thanks.
Do the following when you query
Cursor localCursor =
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_FNAME +"||"+ KEY_LNAME, KEY_DIAGNOSIS }, null, null, null, null, null);
And while assigning values using your adapter do as follows,
String[] data = new String[]{DBHelper.KEY_LNAME +"||"+ DBHelper.KEY_FNAME, DBHelper.KEY_DIAGNOSIS};
int[] to = new int[] {R.id.fullname, R.id.diagnosis};
try this
SELECT CONCAT(ColA, ColB) AS ColC FROM Table
or
String query = "select" +ColA+"+"+ColB +"as CompleteAddress from YourTable";

Android SQLite get data from database to an array

i want to get the value from the cursor without the SimpleCursorAdapter part.here is the code
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2,KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
and the activity side code
cursor = mySQLiteAdapter.queueAll();
from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
i am getting the pkg value correct.but i want to get the values directly from the cursor while removing SimpleCursorAdapter part the code doesn't work.
any help would be appreciated :)
You can get values without declaring adapters. Adapters are need if you want to show the data in the list widgets. So your can be the following:
cursor = mySQLiteAdapter.queueAll();
if (cursor == null) {
//check if there are errors or query just return null
}
if (cursor.moveToFirst()) {
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
}
First you must count how many rows are in your table. Then assign that count to variable and it use to create an array. For array size you can use that count variable. Then create a for loop and use that count variable for rounds. After create your query and assign values to your arrays. 100% worked!.
int sqlcount;
Cursor mFetch;
SQLiteDatabase mydb = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
mydb.execSQL("create table if not exists customer(name varchar,email varchar)");
Cursor mCount = mydb.rawQuery("select count(*) from customer", null);
mCount.moveToFirst();
sqlcount = mCount.getInt(0);
mCount.close();
String cname[] = new String[sqlcount];
String cemail[] = new String[sqlcount];
for(int i=0;i<sqlcount;i++) {
mFetch= mydb.rawQuery("select name,email from customer", null);
mFetch.moveToPosition(i);
cname[i] = mFetch.getString(0);
cemail[i] = mFetch.getString(1);
}
mFetch.close();
Toast.makeText(MainActivity.this,String.valueOf(cname[0]),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,String.valueOf(cemail[1]),Toast.LENGTH_SHORT).show();

SQL cursor error

I have been using the notepad SQLhelper (notesDBadapter) as a model, some of it works, some doesn't. I can get a cursor for 'fetchallrecords() but it crashes if I try a call passing an argument and using the 'WHERE'. The argument is passed but the cursor fails. My code in activity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listselectedfile);
//Button ID clicked in previous activity
Bundle bundle = getIntent().getExtras();
int BtnId = bundle.getInt("ButtonID");
Toast.makeText(this, "ButtonID selected in Main:= " + BtnId, Toast.LENGTH_LONG) .show();
mDbHelper = new SectionsDbAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData() {
// Get all of the notes from the database and create the item list
//Cursor c = mDbHelper.fetchAllRecords(); <=== works fine
Cursor c = mDbHelper.fetchRecordsbySource("UK"); <=== fails in DBhelper
startManagingCursor(c);
String[] from = new String[] { SectionsDbAdapter.KEY_DESC };
//String[] from = new String[] { SectionsDbAdapter.KEY_SOURCE }; <=== can fetch this column from table
int[] to = new int[] { R.id.tv_full_width }; //the R.id.xxx= view in the .xml file
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
}
In the DBhelper;
This call works and returns the full table;
public Cursor fetchAllRecords() {
return mDb.query(DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_DESC, KEY_DEPTH, KEY_TWEB,
KEY_BF1, KEY_TF1, KEY_BF2, KEY_TF2,
KEY_IMAJOR, KEY_IMINOR,
KEY_PLMAJOR, KEY_PLMINOR,
KEY_JTORSION, KEY_AREA,
KEY_WARPING, KEY_CYCHANNEL,
KEY_SHAPE, KEY_SOURCE,
KEY_UNITS},null, null, null, null, null);
}
This call fails on the cursor (the argument is passed successfully);
public Cursor fetchRecordsbySource(String source) throws SQLException {
Log.v("In fetchRecordsbySource", "source = " +source);
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = " + source, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
There is nothing obvious to me in the Eclipse debug, but, as a newby, I probably have not got the necessary perspective.
Can anyone spot the error?
In the code you have, if source is a non-numeric value, it needs to surrounded by single quotes, like this:
KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = '" + source + "'", null, null, null, null, null)
But you will be better off if you pass your filter arguments as ?; this avoids (among other things) SQL injection attacks
KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = ?", new String[] { source }, null, null, null, null)

Categories

Resources