Reputation: 13
I am trying to create a list with a custom List item cell in a completely programatic way (without using any xml). I am running into below error. After several hours of searching on the web, I am writing this as my first question on Stack Overflow.
Appreciate your inputs on this & any suggestions on how to better handle Android programming without using the R.*.xml
On running this code, I get the below error:
(Suspended (exception Resources$NotFoundException))
ListView.layoutChildren() line: 1596
ListView(AbsListView).onLayout(boolean, int, int, int, int) line: 1112
ListView(View).layout(int, int, int, int) line: 6569
FrameLayout.onLayout(boolean, int, int, int, int) line: 333 ...
Code:
public class MyList extends ListActivity{
static final ArrayList<HashMap<String,String>> list =
new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//CUSTOM LIST
LinearLayout mainLayout=new LinearLayout(this);
ListView myListView=new ListView(this);
mainLayout.addView(myListView);
LinearLayout ListItemLayout=new LinearLayout(this);
TextView title = new TextView(this);
TextView author = new TextView(this);
TextView price = new TextView(this);
ListItemLayout.addView(title);
ListItemLayout.addView(author);
ListItemLayout.addView(price);
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
ListItemLayout.getId(),
new String[] {"title","author","price"},
new int[] {ListItemLayout.getChildAt(0).getId(),ListItemLayout.getChildAt(1).getId(),ListItemLayout.getChildAt(2).getId()}
);
populateList();
setListAdapter(adapter);
}
private void populateList() {
HashMap<String,String> map = new HashMap<String,String>();
map.put("title",
"Professional Android ");
map.put("author", "Meier");
map.put("price", "$54.99");
list.add(map);
map = new HashMap();
map.put("title","Android 2");
map.put("author",
"Sayed");
map.put("price", "$48.98");
list.add(map);
}
}
Upvotes: 1
Views: 1270
Reputation: 41972
You can't do that. SimpleAdapter
requires a resource id from a layout defined in xml. It also requires the resource ids of the TextView
s that it will be populating. This is because it uses LayoutInflater#inflate
to create the containing View
and then ViewGroup#findViewById
to get the reference to the TextView
s that will display the data.
If you want to do all your layout in code including that of the Adapter
you will have to create your own custom Adapter
class. You can do this by extending BaseAdapter
and overriding getView
at a minimum.
Upvotes: 1
Reputation: 11923
The constructor of your SimpleAdapter requires an id from your ListItemLayout but it doesn't have one (I guess the Android fall back is to check the R file), so assign it an id in your code.
Upvotes: 0