adding values to listView - android

I am trying to populate a ListView....but I cant add 2 string values from database used in SimpleCursorAdapter....
Any one, help me
Code
ListView.java
public class ListView extends ListActivity {
SQLiteDatabase messagedb;
List<String> senderArray = new ArrayList<String>();
List<String> bodyArray = new ArrayList<String>();
String[] simpleSenderArray = new String[ senderArray.size() ];
String[] simpleBodyArray = new String[ bodyArray.size() ];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_list);
senderArray.toArray( simpleSenderArray );
bodyArray.toArray( simpleBodyArray );
messagedb=ListView.this.openOrCreateDatabase("message",0, null);
//This database created already and add sender and body values...here just open that database
Cursor cur=messagedb.rawQuery("select sender, body from tab2", null);
while(cur.moveToNext())
{
String sender = cur.getString(cur.getColumnIndex("sender"));
String body = cur.getString(cur.getColumnIndex("body"));
senderArray.add(sender);
bodyArray.add(body);
}
cur.close();
messagedb.close();
int[] to = new int[] { R.id.sender_entry, R.id.body_entry };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.my_list_entry, cur,simpleSenderArray, to);
this.setListAdapter(mAdapter);
}
}
my_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
my_list_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/sender_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dip" />
<TextView
android:id="#+id/body_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dip" />
</LinearLayout>
Can somebody help me to populate my ListView?

You have named your Activity ListView which is already a built-in class name, I highly recommend changing it to something unique to prevent any confusion or naming conflicts.
In your SQLite table, you ought to have an _id INTEGER column set as the PRIMARY KEY, Android requires this _id column to bind the data to any ListView, Spinner, etc. (Technically SQLite3 creates a column like this automatically, but I believe it is best to define it yourself.)
messagedb.execSQL(
"CREATE TABLE IF NOT EXISTS tab2(" +
" _id INTEGER PRIMARY KEY," +
" sender INT(13)," +
" body varchar)");
Your code should look more like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_list);
// Using a SQLiteOpenHelper might be best, but I'll assume that this command works
messagedb=ListView.this.openOrCreateDatabase("message",0, null);
Cursor cur = messagedb.rawQuery("select _id, sender, body from tab2", null);
String[] from = new String[] { "_id", "sender", "body" }
int[] to = new int[] { R.id.sender_entry, R.id.body_entry };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.my_list_entry, cur, from, to);
this.setListAdapter(mAdapter);
}
You might want to consider using the SQLiteDatabase.query() methods, I believe it is a touch faster:
Cursor cur = messagedb.query("tab2", new String[] {"_id", "sender", "body"}, null, null, null, null, null);
I also recommend defining static variables for all you column names for future ease-of-coding.
Lastly, this should work for a table without the _id column, but again I don't recommend it:
Cursor cur = messagedb.rawQuery("select rowid as _id, sender, body from tab2", null);

Related

Android ListView and SimpleCursosrAdapter: nothing is showed

A read a lot of docs, but can't figure out what I am doing wrong. I'm just trying to load data with Cursor and show it in a ListView using SimpleCursorAdapter.Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_expense_category);
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String q = "SELECT rowid as _id, " + GLO.DBEntry_Categories.COLUMN_CATEGORY +
" FROM " + GLO.DBEntry_Categories.TABLE_NAME;
Cursor cursor = db.rawQuery(q, new String[]{});
cursor.moveToFirst();
Toast toast = Toast.makeText(this, "Read count: " + Integer.toString(cursor.getCount()) + " " + cursor.getString(0), Toast.LENGTH_LONG);
toast.show();
cursor.moveToFirst();
//TODO: use Loader
String[] fromCols = {GLO.DBEntry_Categories.COLUMN_CATEGORY};
int[] toViews = {R.id.MyTextView1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor,
fromCols, toViews, 0);
ListView listView = (ListView) findViewById(R.id.SelectExpenseCategory_list);
listView.setAdapter(adapter);
}
So toast message shows there are 3 items in cursor, and data is peresent (at least in first one, but I'm sure for others too). But nothing is showed in ListView.
Here is a part of my activity layout:
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/SelectExpenseCategory_search"
android:layout_centerHorizontal="true"
android:id="#+id/SelectExpenseCategory_list">
</ListView>
And here is complete file for item layout:
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MyTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="5dp"
android:textColor="#color/cm_dark_green"
android:textSize="24sp">
</TextView>
Any ideas what's wrong?..
You're using the internal layout for the list items: android.R.layout.simple_list_item_1.
The TextView id there is called text1, so instead use this:
int[] toViews = {android.R.id.text1};
If you want to use your own custom layout then change the layout used by your adapter to e.g. R.layout.list_item_layout.

Android SQLite Data using SimpleCursorAdapter not populating more than one row in the listview?

Basically I have code that initialises the database in a DatabaseHelper extended class (see below) and I'm currently getting only one of the results to display?
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS host ("
+ BaseColumns._ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, mac_address VARCHAR)");
ContentValues host_values = new ContentValues();
host_values.put("name", "test host");
host_values.put("mac_address", "ffffffffffff");
db.insert("host", null, host_values);
ContentValues host_values2 = new ContentValues();
host_values.put("name", "test me host");
host_values.put("mac_address", "eeeeeeeeeeee");
db.insert("host", null, host_values2);
}
This is the code, I'm using a ListFragment over a ListActivity is that makes any difference?
public class TargetListFragment extends ListFragment {
private SQLiteDatabase database;
private CursorAdapter dataSource;
private static final String fields[] = { "name", "mac_address",
BaseColumns._ID };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
DatabaseHelper helper = new DatabaseHelper(this.getActivity().getApplicationContext());
database = helper.getWritableDatabase();
Cursor data = database.query("host", fields,
null, null, null, null, null);
dataSource = new SimpleCursorAdapter(this.getActivity().getApplicationContext(),
R.layout.target_row, data, fields,
new int[] { R.id.target_name, R.id.mac_address });
setListAdapter(dataSource);
}
This is really bothering me as it seems almost like the cursor is only dealing with the first row and then being closed but I can't think of anything that would cause that?
Again in case it's useful here's the XML of the row view.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:id="#+id/target_row_layout"
android:orientation="vertical" android:layout_width="wrap_content">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/target_name"
style="#style/target_list.item_name" /> <!--style="#style/target_list.item_name"-->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/mac_address"
style="#style/target_list.mac_address" /> <!--style="#style/target_list.mac_address"-->
</LinearLayout>
You are using host_values where you meant to use host_values2... insert() won't add a second row because all of the values inside host_values2 are null:
ContentValues host_values2 = new ContentValues();
host_values2.put("name", "test me host"); // Change variable
host_values2.put("mac_address", "eeeeeeeeeeee"); // Change variable
db.insert("host", null, host_values2);
(Alternatively you can simply remove host_values2 and write over the previous data host_values.)

facing difficulties in getting contacts in listview

I am trying to get all the contacts of the phone in a listview with checkboxes in order to select multiple contacts at a time. I have written some code which is creating the same number of rows as the number of contacts in my emulator. But the problem is the name and number of the contacts are not appearing as you can see in the image attached. Moreover when i click Show contacts button to show the selected contacts in Toast that too is not happening.
custcontactview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="5.0px"
android:paddingLeft="5.0px"
android:paddingTop="5.0px" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/cConName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/checkBox1"
android:layout_marginLeft="15.0dip"
android:layout_toRightOf="#+id/checkBox1"
android:text="Small Text"
android:textAppearance="?android:textAppearanceSmall" />
<TextView
android:id="#+id/cConNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/cConName"
android:layout_marginLeft="15.0dip"
android:layout_toRightOf="#id/checkBox1"
android:text="Medium Text"
android:textAppearance="?android:textAppearanceMedium" />
</RelativeLayout>
activity_contacts_picker.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/btnShow" >
</ListView>
</RelativeLayout>
ContactsPicker.java
public class ContactsPicker extends ListActivity {
protected Object mActionMode;
public int selectedItem = -1;
private Button btnShowContacts;
private ListView myListView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_picker);
myListView = getListView();
btnShowContacts = (Button) findViewById(R.id.btnShow);
btnShowContacts.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
String name = null;
String number = null;
long [] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
while(contact.moveToNext()){
name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
number = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Toast.makeText(getApplicationContext(), "Name: " +name + "\n" + "Number: " + number , Toast.LENGTH_LONG).show();
}
}
});
ArrayList<Map<String, String>> list = buildData();
String[] from = { "name", "purpose" };
int[] to = { R.id.cConName, R.id.cConNum };
SimpleAdapter adapter = new SimpleAdapter(this, list,R.layout.custcontactview, from, to);
setListAdapter(adapter);
}
private ArrayList<Map<String, String>> buildData() {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.clear();
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null,null);
while (people.moveToNext()) {
String contactName = people.getString(people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactId = people.getString(people.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ((Integer.parseInt(hasPhone) > 0)) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Map<String, String> NamePhoneType = new HashMap<String, String>();
NamePhoneType.put("Name", contactName);
NamePhoneType.put("Phone", phoneNumber);
list.add(NamePhoneType);
}
phones.close();
}
}
people.close();
startManagingCursor(people);
return list;
}
}
But the problem is the name and number of the contacts are not
appearing as you can see in the image attached
First of all, I guess you checked and see that you have real values in the ArrayList list in the buildData method. Second you use the key names "Name" and "Phone" when you add the values to the HashMap, but in the from String array that you use in the SimpleAdapter you use the values "name" and "purpose". In the from String array you need to have the same keys as you have in the HashMap.
Moreover when i click Show contacts button to show the selected
contacts in Toast that too is not happening.
First, you can't use ListView's default mechanism for checked items when you have a custom row view. If you want to get the checked items you'll need to manage the state of the CheckBox from the row yourself. The getCheckedItemIds() method will not return something valid and the query will fail returning any valid results. Instead you should implement your own custom adapter and return the row's HashMap(which will contain the name and the phone) with SimpleAdapter.getItem method. This way you'll avoid the need to query the contacts again.
call notifyDataSetChanged(); You need to refresh the list..

ListView has correct number of rows, but shows no text

I have created a ListActivity inside a tabhost, and this tab is supposed to show all records from a sql table. When I click the tab however, it shows the right amount of rows (separation lines) but there's no data/text anything else to be seen. So basically I get an empty list, and I've checked the database file, the data is there!
My table only has the columns _id and name.
This is the code I'm using:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor c;
ShowAdapter sa = new ShowAdapter(this);
sa.open();
c = sa.getSubscribedShows();
String[] from = new String[] { "name" };
int to[] = new int[] { R.id.text1 };
SimpleCursorAdapter shows = new SimpleCursorAdapter(this, R.layout.show_list, c, from, to);
setListAdapter(shows);
sa.close();
}
And my other method simply returns the cursor:
public Cursor getSubscribedShows(){
Cursor c = db.query(true, "shows", null, null, null, null, null, "name", null);
c.moveToFirst();
return c;
}
And my XML is:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:id="#+id/text1" >
</TextView>
Any ideas what I'm doing wrong?
Change the layout_height propery to:
android:layout_height="wrap_content"
and see if that fixes it

Begginner working with ListAdapters / SQLite Database

My programming knowledge is slim, i discovered Java and the Android SDK some days ago.
I have a SQLiteDatabase, a SQLiteOpenHelper, and a Cursor working properly
( means i think i understood how to create/open a DB using a SQLiteOpenHelper, make queries on my DB and get a cursor )
currently, i'm wrapping i + labName + labCity into a single results String, and display into a single TextView R.id.label
Is it possible to bind labName to R.id.label, and bind labCity to another TextView R.id.label2 ?
Here is the code of my ListActivity i need help with :
public class MainLabList extends ListActivity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_lab_list);
// DB
GestionDB gdb = new GestionDB(this, GestionDB.DATABASE_NAME, null, GestionDB.DATABASE_VERSION);
SQLiteDatabase theDB = gdb.getWritableDatabase();
// Cursor
String[] columns = {GestionDB.LAB_NAME, GestionDB.LAB_ADDRESS_CITY};
Cursor c =
theDB.query(GestionDB.TABLE_NAME, columns, null, null, null, null, null);
////////
this.setTitle(" " + c.getCount() + " Labs in Local Database");
ArrayList<String> results = new ArrayList<String>();
int i = 0;
c.moveToFirst();
/* Loop through all Results */
do {
i++;
String labName = c.getString(c.getColumnIndex(GestionDB.LAB_NAME));
String labCity = c.getString(c.getColumnIndex(GestionDB.LAB_ADDRESS_CITY));
/* Add current Entry to results. */
results.add("" + i + ": " + labName
+ " (" + labCity + ")");
} while (c.moveToNext());
//need rework
ListView lvLabListing = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> labListAdapter = new ArrayAdapter<String>(this,
R.layout.listing, R.id.label, results );
lvLabListing.setAdapter(labListAdapter);
lvLabListing.setOnItemClickListener(this);
//
// don't forget to close the database
gdb.close();
And the listing.xml i would like to modify :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:layout_width="fill_parent">
<ImageView android:id="#+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="#drawable/icon"></ImageView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/label"></TextView>
</LinearLayout>
My GestionDB class is simple, just define some columns if the database doesn't exist, along with some variables.
You should use a CursorAdapter, perhaps a SimpleCursorAdapter, for this. Here is an example.

Categories

Resources