Android Subitems on a Listview - android

My question: Why am I getting an error of java.lang.NullPointerException for trying to set set an adapter to one of my listviews in subListView.setAdapter(adapter2);
I am trying to create an app for learning purposes that will display subjects in a listview and when one of the items/subjects on the listview is clicked a sub item list will appear.
Right now I am just trying to show a listview view with their subitems shown.
Here is my code:
activity_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="150dp"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/listView1"
android:layout_below="#+id/button1"
android:text="#string/hello_world" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textview1" >
</ListView>
</RelativeLayout>
group_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/groupItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#+id/sublistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/groupItem"
android:layout_marginLeft="26dp" >
</ListView>
</RelativeLayout>
db_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:maxHeight="60dp"
android:maxWidth="60dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/subSubjectTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageView1"
android:text="Jesus is God"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/subIdtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Small Text"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/subScriptTextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:text="John 1:1-12"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
protected void onCreate(Bundle savedInstanceState) {
//Creates DB and Tables if they do not exist... This part works
popList();
}
public void popList(){
ListView listView = (ListView) findViewById(R.id.listView1);
ListView subListView = (ListView) findViewById(R.id.sublistView);
TextView textv = (TextView)findViewById(R.id.textview1);
String topList[] = {"First", "Second", "Third"};
//Queries the DB and stores it in a Cursor... This part works
textv.append(" Cursor Count = " + c.getCount()); //this is for debugging purposes
int iId = c.getColumnIndex("id");
int iSummary = c.getColumnIndex("Summary");
int iScripts = c.getColumnIndex("Scripts");
int iDescription = c.getColumnIndex("Description");
int iSourceType = c.getColumnIndex("SourceType");
cursor.moveToFirst();
for (int j=0; j<c.getCount(); j++)
{
int image = 0;
if(c.getString(iSourceType).equals("Bible"))
{
image = R.drawable.bible;
}
if(c.getString(iSourceType).equals("Article"))
{
image = R.drawable.article;
}
if(c.getString(iSourceType).equals("Video"))
{
image = R.drawable.video;
}
myLVItems.add(new lvItem(c.getString(iId), c.getString(iSummary), c.getString(iScripts), c.getString(iDescription), image));
c.moveToNext();
}
ArrayAdapter<lvItem> adapter2 = new myListAdapter();
textv.append(" subListView Count = " + myLVItems.size()+ " adapter2 Count: " + adapter2.getCount()); //this is for debugging purposes
subListView.setAdapter(adapter2); //this is first error that the logcat points to
for (int i=0; i<topList.length; i++)
{
myGroupTopItems.add(new topgroupItem(topList[i], null));
}
ArrayAdapter<topgroupItem> adapter = new myTopListAdapter();
listView.setAdapter(adapter);
}
private class myListAdapter extends ArrayAdapter<lvItem>{
public myListAdapter(){
super(MainActivity.this, R.layout.db_items, myLVItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// make sure we have a view to work with (may have been given null
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.db_items, parent, false);
}
//find the item to work with
lvItem currentLVItem = myLVItems.get(position);
//fill the view
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView1);
imageView.setImageResource(currentLVItem.getIconId());
TextView hiddenView = (TextView) itemView.findViewById(R.id.subIdtextView);
hiddenView.setText(currentLVItem.getId());
TextView summaryView = (TextView) itemView.findViewById(R.id.subSubjectTextView);
summaryView.setText(currentLVItem.getSummary());
TextView descripView = (TextView) itemView.findViewById(R.id.subScriptTextView2);
descripView.setText(currentLVItem.getScripts());
return itemView;
}
}
private class myTopListAdapter extends ArrayAdapter<topgroupItem>{
public myTopListAdapter() {
super(MainActivity.this, R.layout.group_item, myGroupTopItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.group_item, parent, false);
}
topgroupItem currentTGItem = myGroupTopItems.get(position);
TextView textView = (TextView) itemView.findViewById(R.id.groupItem);
textView.setText(currentTGItem.getText());
return itemView;
}
}
}
This is what textv displays: Cursir Count = 3 subListView Count = 3 adapter2 Count: 3
I'm not sure why I am getting a Null for subListView. I'm not looking for an expanded listview with what I am doing
Sorry for all the code. Any help would be greatly appreciated

First: you call popList() in onCreate(). That is before the List gets populated with items and therefore there is no child view with the id sublistView.
Second: DO NOT ADD A LIST INTO A LIST ITEM! No ScrollViews inside another ScrollView! You might wanna check out ExpandableListView if you'd like to have sub lists.

Related

Choice Mode does not effect on Custom Adapter with Layout

Previously i worked with GridView and set ChoiceMode to single and everything was OK.
Now i create my Custom Adapter with it's Layout.
And then added items to the GridView.
And set ChoiceMode to Single, As below you will see.
But Choice mode does not work in appearance and view.
Here is Custom Adapter :
public class CarAdapter extends ArrayAdapter<Car>{
public CarAdapter(Context context, int resource, ArrayList<Car> carArrayList) {
super(context, resource, carArrayList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Car car = getItem(position);
if(convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_car,parent, false);
}
TextView carName = (TextView)convertView.findViewById(R.id.textView2);
TextView carSIM = (TextView)convertView.findViewById(R.id.textView);
carName.setText(car.getName());
carSIM.setText(car.getSIM());
return convertView;
}
}
And here is it's Layout XML :
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:layout_marginTop="30dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="#+id/textView2"
android:layout_x="12dp"
android:layout_y="2dp"
android:textColor="#000"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginLeft="20dp"
android:id="#+id/textView"
android:layout_x="157dp"
android:layout_y="0dp"
android:textColor="#000"/>
</AbsoluteLayout>
And here is Main Activity :
public class DisplayActivity extends Activity {
CarAdapter carAdapter;
Car car;
Car car2;
Car car3;
ArrayList<Car> carArrayList;
GridView gridView;
Button test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
carArrayList = new ArrayList<Car>();
gridView = (GridView) findViewById(R.id.gridView);
carAdapter = new CarAdapter(getApplicationContext(), android.R.layout.select_dialog_singlechoice, carArrayList);
test = (Button) findViewById(R.id.button);
car = new Car("Test", "aaa");
car2 = new Car("Test2", "aaa");
car3 = new Car("Test3", "aaa");
Car car4 = new Car("Test4", "aaa");
carArrayList.add(car);
carArrayList.add(car2);
carArrayList.add(car3);
carArrayList.add(car4);
gridView.setAdapter(carAdapter);
Toast.makeText(getApplicationContext(), "Choice mode is : " + gridView.getChoiceMode(), Toast.LENGTH_SHORT ).show();
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (gridView.isItemChecked(gridView.getCheckedItemPosition())) {
String name = (carAdapter.getItem(gridView.getCheckedItemPosition())).getName();
Toast.makeText(getApplicationContext(), "Here is " + name, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "This is not true", Toast.LENGTH_SHORT).show();
}
}
});
}
}
As you see i put a test Button and return the name of selected GridView Item.It returns the value,But with no checkable or selected View.
And Main Activity 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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".DisplayActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:weightSum="1"
android:layout_marginTop="30dp">
<GridView
android:layout_width="wrap_content"
android:layout_height="387dp"
android:id="#+id/gridView"
android:background="#abc"
android:layoutDirection="ltr"
android:choiceMode="singleChoice"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:id="#+id/button" />
</LinearLayout>
Should i set it by myself?
If yes, where?
Any solution will appreciate.
Thx
First create the array list. then create the adapter and then assign it as an adapter to grid view.
what you are doing is creating adapter first the creating array-list and the setting it to grid view.

ListView OnItemClickListener is not listening

I checked all the previous questions regarding this issue , but none of them are helpfull to me .
My listview is not responding , i tried changing this
list.setOnItemClickListener(new ContactsListItemClickListener(this));
to
list.setOnItemClickListener(this);
by making my PrioritiseContacts activity just imeplement OnItemClickListener , but then too its not working .
The activity is successfully running , but i am unable to listen for listclick events.
How to correct this?
Here is my class :
public class PrioritiseContacts extends Activity implements OnClickListener {
private ListView list;
// list of contacts with name
private List<Contacts> contactsList;
private Controller controll;
private ContactListAdapters adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_contacts);
controll = new Controller();
contactsList = controll.fetchContacts(this);
// call the adapter to set the list view layout
adapter = new ContactListAdapters(contactsList, this);
list = (ListView) findViewById(R.id.lv_contacts);
// set the adapter to list
list.setAdapter(adapter);
list.setOnItemClickListener(new ContactsListItemClickListener(this));
// inflate the list of contact
}
#Override
public void onClick(View arg0) {
Toast.makeText(this, "clicked", 1000).show();
}
class ContactsListItemClickListener implements OnItemClickListener {
private Context c;
public ContactsListItemClickListener(
PrioritiseContacts prioritiseContacts) {
this.c = prioritiseContacts;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(c, "Clicked", 1500).show();
System.out.print("clicked");
}
}
}
My select_contacts xml :
<LinearLayout 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"
android:background="#000000"
android:orientation="vertical">
<TextView
android:id="#+id/tv_select_contacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Choose Contacts"
android:textColor="#fdfdfd"
android:textSize="30dip"
android:gravity="center" >
</TextView>
<ListView
android:id="#+id/lv_contacts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:cacheColorHint="#00000000"
android:clickable="true"
android:focusable="true"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:scrollbars="none" >
</ListView>
</LinearLayout>
And this is my adapter's getview() :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// layout infklater to inflate the post list view
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = inflater.inflate(R.layout.contacts_list_view, null);
}
Contacts c = contactList.get(position);
// set text views in contact lists
// Typeface custom_font =
// Typeface.createFromAsset(context.getAssets(),"fonts/calibril.ttf");
TextView name = (TextView) view.findViewById(R.id.tv_contact_name);
// date.setTypeface(custom_font);
name.setText(c.getName());
TextView number = (TextView) view.findViewById(R.id.tv_number);
// title.setTypeface(custom_font);
number.setText(c.getPhone());
ImageView contact_image = (ImageView) view.findViewById(R.id.iv_single_contact);
// hut.setTypeface(custom_font);
if(c.getContactImage() != null)
contact_image.setImageBitmap(c.getContactImage());
else
contact_image.setImageDrawable(view.getResources().getDrawable(R.drawable.ic_contact_picture_2));
return view;
}
My contacts_list_view xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl_post_list"
android:layout_width="match_parent"
android:layout_height="50dip"
android:background="#000000"
android:gravity="left"
android:orientation="horizontal"
android:paddingBottom="2dp"
android:paddingTop="2dp" >
<ImageView
android:id="#+id/iv_single_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.87"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:gravity="left"
android:paddingLeft="2dp"
android:text="Contact Name"
android:textColor="#fdfbfb"
android:textStyle="bold" />
<View style="#style/Divider" />
<TextView
android:id="#+id/tv_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-thin"
android:gravity="left"
android:text="this is number"
android:textColor="#fdfbfb"
android:textSize="10dp"
android:textStyle="bold" />
</LinearLayout>
<CheckBox
android:id="#+id/cb_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
</LinearLayout>
If any row item of list contains focusable or clickable view then OnItemClickListener won't work such as for checkbox or button etc in the row item.There are two solution:
1. row item must be having param like android:descendantFocusability="blocksDescendants"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>
2. Set given two attributes to false
like
android:focusable="false"
android:focusableInTouchMode="false"
For example if there is any checkbox or button or image in the row item then
<CheckBox
android:id="#+id/fav_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />

ListView Item not clickable when I display ad's with PublisherAdView inside the Item [duplicate]

I checked all the previous questions regarding this issue , but none of them are helpfull to me .
My listview is not responding , i tried changing this
list.setOnItemClickListener(new ContactsListItemClickListener(this));
to
list.setOnItemClickListener(this);
by making my PrioritiseContacts activity just imeplement OnItemClickListener , but then too its not working .
The activity is successfully running , but i am unable to listen for listclick events.
How to correct this?
Here is my class :
public class PrioritiseContacts extends Activity implements OnClickListener {
private ListView list;
// list of contacts with name
private List<Contacts> contactsList;
private Controller controll;
private ContactListAdapters adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_contacts);
controll = new Controller();
contactsList = controll.fetchContacts(this);
// call the adapter to set the list view layout
adapter = new ContactListAdapters(contactsList, this);
list = (ListView) findViewById(R.id.lv_contacts);
// set the adapter to list
list.setAdapter(adapter);
list.setOnItemClickListener(new ContactsListItemClickListener(this));
// inflate the list of contact
}
#Override
public void onClick(View arg0) {
Toast.makeText(this, "clicked", 1000).show();
}
class ContactsListItemClickListener implements OnItemClickListener {
private Context c;
public ContactsListItemClickListener(
PrioritiseContacts prioritiseContacts) {
this.c = prioritiseContacts;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(c, "Clicked", 1500).show();
System.out.print("clicked");
}
}
}
My select_contacts xml :
<LinearLayout 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"
android:background="#000000"
android:orientation="vertical">
<TextView
android:id="#+id/tv_select_contacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Choose Contacts"
android:textColor="#fdfdfd"
android:textSize="30dip"
android:gravity="center" >
</TextView>
<ListView
android:id="#+id/lv_contacts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:cacheColorHint="#00000000"
android:clickable="true"
android:focusable="true"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:scrollbars="none" >
</ListView>
</LinearLayout>
And this is my adapter's getview() :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// layout infklater to inflate the post list view
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = inflater.inflate(R.layout.contacts_list_view, null);
}
Contacts c = contactList.get(position);
// set text views in contact lists
// Typeface custom_font =
// Typeface.createFromAsset(context.getAssets(),"fonts/calibril.ttf");
TextView name = (TextView) view.findViewById(R.id.tv_contact_name);
// date.setTypeface(custom_font);
name.setText(c.getName());
TextView number = (TextView) view.findViewById(R.id.tv_number);
// title.setTypeface(custom_font);
number.setText(c.getPhone());
ImageView contact_image = (ImageView) view.findViewById(R.id.iv_single_contact);
// hut.setTypeface(custom_font);
if(c.getContactImage() != null)
contact_image.setImageBitmap(c.getContactImage());
else
contact_image.setImageDrawable(view.getResources().getDrawable(R.drawable.ic_contact_picture_2));
return view;
}
My contacts_list_view xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl_post_list"
android:layout_width="match_parent"
android:layout_height="50dip"
android:background="#000000"
android:gravity="left"
android:orientation="horizontal"
android:paddingBottom="2dp"
android:paddingTop="2dp" >
<ImageView
android:id="#+id/iv_single_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.87"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:gravity="left"
android:paddingLeft="2dp"
android:text="Contact Name"
android:textColor="#fdfbfb"
android:textStyle="bold" />
<View style="#style/Divider" />
<TextView
android:id="#+id/tv_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-thin"
android:gravity="left"
android:text="this is number"
android:textColor="#fdfbfb"
android:textSize="10dp"
android:textStyle="bold" />
</LinearLayout>
<CheckBox
android:id="#+id/cb_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
</LinearLayout>
If any row item of list contains focusable or clickable view then OnItemClickListener won't work such as for checkbox or button etc in the row item.There are two solution:
1. row item must be having param like android:descendantFocusability="blocksDescendants"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>
2. Set given two attributes to false
like
android:focusable="false"
android:focusableInTouchMode="false"
For example if there is any checkbox or button or image in the row item then
<CheckBox
android:id="#+id/fav_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />

Populating Listview with Dictionary and ListFragment

How can I populate a listview using a Dictionary from a fragment for each row and use a custom layout ? In layout of row, contains two textview and one Imageview.
My Layout with listview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:background="#ff04aefa" />
</LinearLayout>
Layout Row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:src="#android:drawable/ic_menu_gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imageView1" />
<LinearLayout
android:id="#+id/singleMessageContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:paddingLeft="10dip"
android:text="Texview 1"
android:textColor="#android:color/background_light" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:paddingLeft="10dip"
android:textColor="#android:color/background_light" />
</LinearLayout>
</LinearLayout>
My ListFragment.cs:
Dictionary <string,string> _Dic = new Dictionary<string,string>();
string[] _ValuesOfDic = { };
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
_Dic = MyProject.UtilDic.ReturnDic ();
_ValuesOfDic = new string[_Dic.Count];
int cont = 0;
foreach (var item in _Dic) {
_ValuesOfDic[cont] = item.Value;
cont++;
}
View view = inflater.Inflate(Resource.Layout.LayoutListOfValues, null); //Layout with listView
ListView listview = (ListView)view.FindViewById (Android.Resource.Id.List);
listview.Adapter = new ArrayAdapter <string> (this.Activity,
Android.Resource.Layout.SimpleListItem1,
_ValuesOfDic); //Here I want to use the layout for the rows of listview
return view;
}
public override void OnListItemClick (ListView l, View v, int position, long id)
{
string value = l.Adapter.GetItem (position).ToString ();
string key = _Dic.FirstOrDefault (x => x.Value.Contains (value)).Key;
Console.WriteLine ("Value: " + value);
Console.WriteLine ("Key: " + key);
}
Create a Custom Adapter, which inherits from BaseAdapter and can take your Dictionary and present accordingly. ArrayAdapter only takes lists or arrays.
So something like:
public class MyDictionaryAdapter : BaseAdapter
{
private Dictionary<TX,TY> _dict;
public MyDictionaryAdapter(Dictionary<TX, TY> dict)
{
_dict = dict;
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
// populate your listview items here
}
}
You can read more about ListView and Adapters here: http://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/

Android EditText: How to process data

I have created an application which is a simple form. Users will enter username data and password into each editText pair provided.
My problem comes with extracting this data. Normally, I would extract by the "#id/" value assigned to each editText, but as I am using an adapter and a separate xml file for the row this is not possible, as each editText has the same id.
Does anyone have an idea how I might go about doing this?
Main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button
android:id="#+id/cancelbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:paddingLeft="50dp"
android:paddingRight="50dp"/>
<Button
android:id="#+id/submitbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:paddingLeft="50dp"
android:paddingRight="50dp"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list"
android:layout_alignParentTop="true"
android:layout_above="#id/cancelbutton" />
list.xml : used for individual row
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/logo"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:src="#drawable/g" >
</ImageView>
<EditText
android:id="#+id/firstLine"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="email"
>
</EditText>
<EditText
android:id="#+id/secondLine"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_alignRight="#id/logo"
android:layout_alignParentRight="true"
android:layout_below="#id/firstLine"
android:text="password"
>
</EditText>
public class ColorAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public SocialSiteAdapter(Context context, String[] values) {
super(context, R.layout.list, values);
this.context = context;
this.values = values;
}
// GetView does what exactly..?
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
// Change icon based on name
String s = values[position];
System.out.println(s);
if (s.equals("Blue")) {
imageView.setImageResource(R.drawable.b);
} else if (s.equals("Green")) {
imageView.setImageResource(R.drawable.g);
} else if (s.equals("Red")) {
imageView.setImageResource(R.drawable.r);
} else if (s.equals("Yellow")) {
imageView.setImageResource(R.drawable.y);
} else {
imageView.setImageResource(R.drawable.ic_launcher);
}
return rowView;
}
}
You need to first select the row and then inside the row select the EditTexts by their known #id
To list the entries you could go like:
ListView listView = getListView();
for (int i = 0; i < listView.getCount(); i++) {
Layout row = (Layout) listView.getItemAtPosition(i); /// XXX
EditText t = (EditText) row.findViewById(R.id.firstLine);
// ...
}
You need to check by yourself in the line with XXX what the getItem.. call returns and change accordingly.

Categories

Resources