SimpleCursorAdapter isnt binding data to listView - android

How do I bind information from my database to a TextView? The ListView Isnt showing the information from the Cursor. Do I need to use the adapter I have created?
I'm trying to display the results in TextViews withing the List.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactform);
Cursor cursor = getCursor();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this, //Context
R.layout.contactform, //xml definintion of each listView item
cursor, //Cursor
new String[] {"FirstName", "LastName", "Phone", "Email"}, //Columns to select From
new int[] {R.id.contact_firstname, R.id.contact_lastname, R.id.contact_phone, R.id.contact_email} //Object to bind to
);
}
private Cursor getCursor()
{
String TABLE_NAME = "exampleContacts";
String[] FROM = {"_id", ""FirstName", "LastName", "Phone", "Email"} ;
dbManager = new DatabaseManager(this);
SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, "ContactID=?", new String[] {PrContactID}, null, null, null);
startManagingCursor(cursor);
return cursor;
}

It looks like you're pulling back a single record. In that case, you don't need to be using the SimpleCursorAdapter, as that is generally used for assigning multiple records to a ListView. Why not just grab the info you need and manually set them to your TextView(s)?
Also, you shouldn't need to use a manage cursor. Just get the values you need and then close the cursor like so:
TextView textView = (TextView) findViewById(R.id.textView01);
Cursor cursor = db.query("exampleContacts", new String[] {"FirstName", "LastName", "Phone", "Email"}, "ContactID=?", new String[] {PrContactID}, null, null, null);
cursor.moveToFirst();
String text = cursor.getString(0) + " " + cursor.getString(1) + " " + cursor.getString(2) + " " + cursor.getString(3);
textView.setText(text);
cursor.close();
Sorry for any typos... this code is just for example and hasn't been tested.

The reason it wasnt being mapped to the ListView is because setListAdapter(); wasnt being used.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactform);
Cursor cursor = getCursor();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this, //Context
R.layout.contactform, //xml definintion of each listView item
cursor, //Cursor
new String[] {"FirstName", "LastName", "Phone", "Email"}, //Columns to select From
new int[] {R.id.contact_firstname, R.id.contact_lastname, R.id.contact_phone, R.id.contact_email} //Object to bind to
);
setListAdapter(adapter);
}

Related

Sort ListView by String Item

I have serveral objects in my DB with three Strings attributes. One of the shows a date information, eg. 1.4.2016, 20.10.2017. I list these objects in a ListView, but before I want to sort them by their dates.
//
//Show all Data on ListView
//
private void displayListView() {
Cursor cursor = datasource.fetchAllData();
// The desired columns to be bound
String[] columns = {
DatabaseHelper.COLUMN_TITLE,
DatabaseHelper.COLUMN_DESCRIPTION,
DatabaseHelper.COLUMN_DEADLINE,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.processobject_title,
R.id.processobject_description,
R.id.processobject_deadline,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.listview_viewlayout,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listview);
ArrayList <ProcessObject> arrayList = new ArrayList<>();
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
activateAddButton();
OnItemClickListener();
};
I see two oppurtinities: sorting the cursor, or sorting the Array to[]. But I don't know how.
public Cursor fetchAllData(){
Cursor cursor = database.query(DatabaseHelper.TABLE_DATABASE, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Solved it:
String orderBy = DatabaseHelper.COLUMN_DEADLINE + " ASC";;
Cursor cursor = database.query(DatabaseHelper.TABLE_DATABASE, columns, null, null, null, null, orderBy);

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

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)

Android: Set contact photo in a ListView with name and number

I'm creating an app that needs to display the phone contacts with its photo, name and number. I've created a ListView and can show contacts and numbers with a generic photo, but I can't show contat's picture. This is my code:
Cursor cursor = getContacts();
String[] fields = new String[] {Contacts.DISPLAY_NAME, Phone.NUMBER};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
fields, new int[] {R.id.contactEntryText, R.id.contactEntryNumber});
mContactList.setAdapter(adapter);
private Cursor getContacts()
// Run query
Uri uri = Phone.CONTENT_URI;
String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
Phone.NUMBER,
Contacts.PHOTO_ID
};
//String selection = Contacts.HAS_PHONE_NUMBER + "='1'";
String selection = null;
String[] selectionArgs = null;
String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
How can I attach the contact's picture in the SimpleCursorAdapter? Is there another?
Thank you very much.
I figured it out. If someone had the same problem, this is how i did it:
In an activity that extends ListActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor names = getNamesAndPictures();
names.moveToFirst();
ListAdapter adapter = new MySimpleCursorAdapter(this, R.layout.contacts,
names, new String[] {Phones.NAME, Phones.NUMBER}, new int[] {
R.id.Nombre, R.id.Numero});
setListAdapter(adapter);
startManagingCursor(names);
Log.i(DEBUG_TAG, "Mi numero: " + miNumeroTelefono());
}
public Cursor getNamesAndPictures(){
String[] projection = new String[] {
Phones.NUMBER,
Phones.PERSON_ID,
People.NAME,
People._ID
};
String selection = Phones.NAME + "!='null'";
String sortOrder = Phones.NAME + " COLLATE LOCALIZED ASC";
Cursor cursor = managedQuery(Phones.CONTENT_URI, projection, selection, null, sortOrder);
return cursor;
}
In a custom adapter:
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
...
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView imageView = (ImageView) view.findViewById(R.id.Foto);
int id = cursor.getColumnIndex(Phones.PERSON_ID);
Uri uri = ContentUris.withAppendedId(Phones.CONTENT_URI, cursor.getLong(id));
String uriPhoto = uri.toString();
String uriPeople = uriPhoto.replace("phones", "people");
Uri uriFinal = Uri.parse(uriPeople);
Bitmap bitmap = People.loadContactPhoto(context, uriFinal, R.drawable.avatar02, null);
imageView.setImageBitmap(bitmap);
super.bindView(view, context, cursor);
}
}
I know it is a very old question but so is the answer as few things in this solution have now been deprecated. As the question showed up in searches while I was looking for similar solution, I though I will add my two cents here...
I have created a simple contacts list with their names and photos from ContactsContract.
Please check my answer at... https://stackoverflow.com/a/37710199/1209544

Trying to list Android Bookmarks showing History as well

I'm trying to list the system default bookmarks but when I run the app, it list not only the bookmarks but also show History URLs and Most Visited URLs.
How can I avoid this and show only the bookmarks?
here is the method: (imported everything necessary + permissions valid)
public class CLASSNAME extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] projection = new String[] {Browser.BookmarkColumns._ID,
Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL};
String[] displayFields = new String[] {Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL};
int[] displayViews = new int[] { android.R.id.text1,
android.R.id.text2 };
Cursor cur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
setListAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, cur,
displayFields, displayViews));
}
}
Solution:
Replace the first "null" to "android.provider.Browser.BookmarkColumns.BOOKMARK"
Cursor cur = managedQuery(android.provider.Browser.BOOKMARKS_URI, projection, null->android.provider.Browser.BookmarkColumns.BOOKMARK, null, null);
Hope this helps anyone else :)

Categories

Resources