Concatenate 2 columns Android SQLite - android

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";

Related

Android .query does not get the data from db when I used where clause

I used .query to select some specific row from SQLite db table but when I used the where clause it does not retrieve data, and if I use null instead of where clause, it retrieve the last row.
public String[] getAllData(){
hoqooqdb = this.getReadableDatabase();
String[] columns = new String[] {"_id", "title", "content"};
Cursor cursor = hoqooqdb.query("unmanshor", columns, "_id = 1", null, null, null, null);
String[] result = new String[2];
while (cursor.moveToNext()){
int iTitle = cursor.getColumnIndex("title");
int iContent = cursor.getColumnIndex("content");
result[0] = cursor.getString(iTitle);
result[1] = cursor.getString(iContent);
}
return result;
}
Try like this:
String where = "_id=?";
String[] whereArgs = new String[]{String.valueOf(1)};
String[] columns = new String[] {"_id", "title", "content"};
Cursor cursor = hoqooqdb.query("unmanshor", columns, where, whereArgs, null, null, null);
Sorry, but my stupid case, In db my id was in persian language and in my code it was english and the code had not any porblem.
Sorry Again

filter listView containing sms list with contacts

I have a listView created using SimpleCursorAdapter.
lv = (ListView) findViewById(R.id.myList);
lv.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
//Cursor c = this.getContentResolver().query(Uri.parse( "content://sms/conversations?simple=true"), null, null, null, "normalized_date desc" );
final Uri inboxURI = Uri.parse("content://mms-sms/conversations/");
final String[] reqCols = new String[] { "_id", "address", "body" };
final String[] projection = new String[]{"*"};
cr = getContentResolver();
Cursor c = cr.query(inboxURI, projection, null, null, Telephony.Sms.Inbox.DEFAULT_SORT_ORDER);
madapter = new simpleLayout(this, R.layout.list_row, c, new String[] { "body", "address" }, new int[] {R.id.text_msg, R.id.phone_number });
lv.setAdapter(madapter);
lv.setTextFilterEnabled(true);
I have also added filter to the listview
madapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return getContentResolver().query(inboxURI, reqCols, "address" + " LIKE '" + constraint + "%'", null, null);
}
});
before the listView only contained the address but now I have mapped them with real contact numbers so the filter is not working any more. How should I return the query so that it will work again

Getting multiple entries for SELECT DISTINCT sqlite android?

I am trying to get the unique column name and show it as a list adapter.
public String[] getAllUsers() {
String[] contactList = new String[100];
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS, new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE }, null, null, KEY_NAME, null, null, null);
int i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contactList[i] = cursor.getString(1);
i++;
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
The above is method in my database class.
And from mainActivity I call this method
private void updateUserList() {
// TODO Auto-generated method stub
String[] contactList = new String[100];
contactList = db.getAllUsers();
Log.d("User List",contactList[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, contactList);
setListAdapter(adapter);
}
The list is getting updated ,but list is getting repeated as a whole
I don't know if I fully understood your question.
If you want to get columns KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE from all rows in database without KEY_NAME repetitions use this query:
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE },
null, null, null, null, null, null);
In your methods do not use Array instead use ArrayList<String>
public ArrayList<String> getAllUsers() {
ArrayList<String> contactList = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE },
null, null, null, null, null, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contactList.add(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
And updateUserList():
private void updateUserList() {
// TODO Auto-generated method stub
ArrayList<String> contactList;
contactList = db.getAllUsers();
Log.d("User List", contactList.get(0));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, contactList);
setListAdapter(adapter);
}
As you only use the column KEY_NAME from cursor the query can be simplified to return only that column.
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] {KEY_NAME}, null, null, null, null, null, null);
The problem was with initializing the String array as 100. I wrote a method to get the total number of counts and it works fine.
public int getUsersCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS, new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE }, null, null, KEY_NAME, null, null, null);
//cursor.close();
// return count
return cursor.getCount();}

index out of bound exception with sqlite database

I try to implement the following code
In the activity.java file
DatabaseEvent mDbHelper = new DatabaseEvent(getApplicationContext());
mDbHelper.open();
Cursor notesCursor = mDbHelper.fetchEvent();
startManagingCursor(notesCursor);
String[] from = new String[]{DatabaseEvent.KEY_ETITLE, DatabaseEvent.KEY_DISTANCE, DatabaseEvent.KEY_IMGNAME, DatabaseEvent.KEY_DESCRIPTION, DatabaseEvent.KEY_EID};
int[] to = new int[]{R.id.title, R.id.duration, R.id.list_image, R.id.artist, R.id.id};
SimpleCursorAdapter event =
new SimpleCursorAdapter(getApplicationContext(), R.layout.list_row, notesCursor, from, to);
In the DatabaseEvent.java
public long createEvent(String title, String distance, String imgname, String description, String eid) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ETITLE, title);
initialValues.put(KEY_DISTANCE, distance);
initialValues.put(KEY_IMGNAME, imgname);
initialValues.put(KEY_DESCRIPTION, description);
initialValues.put(KEY_EID, eid);
Log.v("INFO1","inserting db");
return mDb.insert(EVENT_TABLE, null, initialValues);
}
public Cursor fetchEvent() {
Log.v("INFO1","fetching db");
Cursor mCursor = mDb.query(EVENT_TABLE, new String[] {KEY_ROWID, KEY_ETITLE, KEY_DISTANCE,
KEY_IMGNAME, KEY_DESCRIPTION, KEY_EID}, null, null,null,null, KEY_DISTANCE+" ASC");
return mCursor;
}
On the logcat, I can clearly see that the log message "inserting db" is printed three times mean the data date really added to the database, but the log message "fetching db" printed once and give me the flowing error says:
CursorIndexOutOfBoundException index -1, requsted, with a size of 60,
I tried different function like moveToFirst() and moveToNext() but still couldn't solve the problem, any one could give me hand, any help will be greately appreciated!
you forgot to include mCursor.moveToFirst();
Change your code to
public Cursor fetchEvent() {
Log.v("INFO1","fetching db");
Cursor mCursor = mDb.query(EVENT_TABLE, new String[] {KEY_ROWID, KEY_ETITLE, KEY_DISTANCE,
KEY_IMGNAME, KEY_DESCRIPTION, KEY_EID}, null, null,null,null, KEY_DISTANCE+" ASC");
mCursor.moveToFirst();
return mCursor;
}

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