populating listview using arrayadapter - android

I want to display two strings one below other as if it is a list.
I tried using simple_list_item_1 to populate listview but nothing is visible on the screen.
((ListView)view).setAdapter(new ArrayAdapter<String>
(RealScreen.getAndroidBaseContext(),android.R.layout.simple_list_item_1, label));
where label is an array which contains two items to be displayed. All I can see is a white screen. Also I want this list to be unclickable.
I want the output to be like this:
String 1
String 2
I am not working with the Activity, instead with the View.
Here is the method which creates view
public void createView(JSONObject definition) {
// TODO Auto-generated method stub
super.createView(definition);
final JSONArray rowArray = definition.optJSONArray(KeyConstants.KEY_ROWS);
final JSONArray columnArray = definition.optJSONArray(KeyConstants.KEY_COLUMNS);
if (rowArray != null) {
label = new String[rowArray.length()];
for (int i = 0; i < rowArray.length(); i++) {
final JSONObject candidate = rowArray.optJSONObject(i);
if(candidate!=null){
label[i]=candidate.optString(KeyConstants.KEY_LABEL_TEXT, null);
}
}
}
((ListView)view).setAdapter(new ArrayAdapter<String>(RealScreen.getAndroidBaseContext(),android.R.layout.simple_list_item_1, label));
}
Thanks.

First create a custom Adapter Class as below
class MyAdapter extends ArrayAdapter
{
private Context context;
private ArrayList<String> list;
public MyAdapter(Context context,
ArrayList<String> list)
{
super(context, R.layout.layout_list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.layout_list,
null);
convertView.setTag(holder);
holder.string1 = (TextView) convertView
.findViewById(R.id.stringgID1);
holder.string2 = (TextView) convertView
.findViewById(R.id.stringID2);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.string1 .setText(list.get(postion));
holder.string2 .setText(list.get(position));
return convertView;
}
#Override
public int getCount() {
return list.size();
}
class ViewHolder {
TextView string1 = null;
TextView string2 = null;
}
}
And then let your activity extend Activity and not ListActivity
listView.setAdapter(new MyAdapter(youtactivityame.this,label);
Doing this the label with any number of list items can be displayed.

Related

ArrayIndexOutofBoundException with ArrayList in ListView in android?

I am using one ListView and set the one adapter with two Arraylist. List and List1 is two ArrayList which is different different GetAllItems from SqliteDatabase.
My Question is , List have Suppose 10 Items and List1 have 7 Items then when I Scrolling my Listview and Successfully display item upto 7 but whenever 8th item then Give the error ArrayOutOfBoundExcecption. Because Different size of both ArrayList. List is Always Larger then List1.
How to solve This error?
Plesae guide me.
My code is,
Adapter1 adapter = new Adapter1(this,
List, List1);
listView1.setAdapter(Adapter1);
dbAdapter.openForRead();
list = dbAdapter.getAllMyData();
dbAdapter.close();
dbAdapter.openForRead();
list1 = dbAdapter.getDisplayLike();
dbAdapter.close();
/** Adapter Class */
public class Adapter1 extends BaseAdapter {
Context context = null;
LayoutInflater layoutInflater = null;
List<List> list = new ArrayList<List>();
List<List1> list1 = new ArrayList<List1>();
public Adapter1(Context context, List<List> list ,
List<List1> list1 ) {
this.context = context;
this.list = list ;
this.list1 = list1;
layoutInflater = LayoutInflater.from(context);
viewHolder = new ViewHolder();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View vi = convertView;
if (vi == null) {
vi = layoutInflater.inflate(R.layout.list_item,
parent, false);
viewHolder = new ViewHolder();
/** Initialize Widgets */
/** Imageview */
viewHolder.imgUserIcon = (ImageView) vi
.findViewById(R.id.imgUserIcon);
viewHolder.imgImage = (ImageView) vi
.findViewById(R.id.imgImage);
viewHolder.imgUnlike = (ImageView) vi
.findViewById(R.id.imgUnlike);
viewHolder.imgUnlike.setTag(position);
viewHolder.imgLike = (ImageView) vi
.findViewById(R.id.imgLike);
viewHolder.imgLike.setTag(position);
/** TextView */
viewHolder.txtPostId = (TextView) vi
.findViewById(R.id.txtPostId);
viewHolder.txtUserName = (TextView) vi
.findViewById(R.id.txtUserName);
viewHolder.txtDateTime = (TextView) vi
.findViewById(R.id.txtDateTime);
viewHolder.txtLikeUnlike = (TextView) vi
.findViewById(R.id.txtLikeUnlike);
viewHolder.txtLikeUnlike.setTag(position);
vi.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) vi.getTag();
}
final List listBean= list .get(position);
final List1 list1Bean= list1.get(position);
viewHolder.txtPostId.setText(listBean.getiPostId()
+ "");
viewHolder.txtUserName.setText(listBean.getName());
viewHolder.txtDateTime.setText(listBean.getStrCreated());
viewHolder.txtLikeUnlike.setText(listBean.getiLike()
+ "");
int iDisplayLike = list1Bean.getiDisplayLike();
if (iDisplayLike == 1) {
viewHolder.imgUnlike.setVisibility(View.GONE);
viewHolder.imgLike.setVisibility(View.VISIBLE);
}
if (iDisplayLike == 0) {
viewHolder.imgLike.setVisibility(View.GONE);
viewHolder.imgUnlike.setVisibility(View.VISIBLE);
}
});
return vi;
}
class ViewHolder {
ImageView imgIcon = null, imgImage = null,
imgUnlike = null;
TextView txtPostId = null, txtUserName = null,
txtDateTime = null,
txtLikeUnlike = null;
}
if you are fetching data from two tables then first marge both ArrayList then pass single ArrayList in adapter to show data instead of two List.
In Adapter1 class constructor marge both ArrayList:
private ArrayList<DataType> finalList;
public Adapter1(Context mContext,ArrayList list1,ArrayList list2){
finalList = new ArrayList<DataType>(list1);
finalList.addAll(list2);
}
Now use finalList for in getView and getCount methods of Adapter where you are using List and List1

Android ListView not refreshing after notifyDataSetChanged with data as Map

I used list adapter with map values as data. When I use adapter.notifyDataSetChanged(); the data in the list not updating. But if I replace the Map with ArrayList everything working fine. Following is my adapter code.
public class CategoryAdapter extends BaseAdapter {
ArrayList<Category> list = new ArrayList<Category>();
Context context;
public CategoryAdapter(Context context, Map<String, Category> categories) {
this.context = context;
list.clear();
list.addAll(categories.values());
}
#Override
public int getCount() {
return list.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHandler handler;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.category_list_item, null);
handler = new ViewHandler();
handler.name = (TextView) convertView.findViewById(R.id.name);
handler.count = (TextView) convertView.findViewById(R.id.count);
convertView.setTag(handler);
} else {
handler = (ViewHandler) convertView.getTag();
}
Category category = list.get(position);
handler.name.setText(category.getMenuName());
handler.count.setText(category.getCount() + "");
if (category.getCount() <= 0) {
handler.count.setVisibility(View.INVISIBLE);
} else {
handler.count.setVisibility(View.VISIBLE);
}
return convertView;
}
}
and my activity code is
private void loadCategories() {
sampleDB = openOrCreateDatabase(AppConstants.DB_NAME, MODE_PRIVATE,
null);
Cursor menuCursor = sampleDB.rawQuery("select * from menu", null);
categories.clear();
while (menuCursor.moveToNext()) {
String menu = menuCursor.getString(menuCursor
.getColumnIndex("name"));
String id = menuCursor.getString(menuCursor.getColumnIndex("id"));
Category category = new Category(menu, id);
categories.put(id, category);
}
menuCursor.close();
categoryAdapter.notifyDataSetChanged();
}
in oncreate() method I have declared adapter as follows
categoryAdapter = new CategoryAdapter(context, categories);
categoryList.setAdapter(categoryAdapter);
loadCategories();
Every time I click on refresh button it calls loadCategories(); method.
In the same code if I replace Map with ArrayList everything working fine.
Now My question is why List is not refreshing with Map values. Please give me clarification regarding this.
Thanks in advance.
You must add a method to your CategoryAdapter to change the instance's list, like so
public class CategoryAdapter extends BaseAdapter {
ArrayList<Category> list = new ArrayList<Category>();
Context context;
public CategoryAdapter(Context context, Map<String, Category> categories) {
this.context = context;
list.clear();
list.addAll(categories.values());
}
#Override
public int getCount() {
return list.size();
}
//ADD THIS METHOD TO CHANGE YOUR LIST
public void addItems(Map<String, Category> categories){
list.clear();
list.addAll(categories.values());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHandler handler;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.category_list_item, null);
handler = new ViewHandler();
handler.name = (TextView) convertView.findViewById(R.id.name);
handler.count = (TextView) convertView.findViewById(R.id.count);
convertView.setTag(handler);
} else {
handler = (ViewHandler) convertView.getTag();
}
Category category = list.get(position);
handler.name.setText(category.getMenuName());
handler.count.setText(category.getCount() + "");
if (category.getCount() <= 0) {
handler.count.setVisibility(View.INVISIBLE);
} else {
handler.count.setVisibility(View.VISIBLE);
}
return convertView;
}
}
and change your loadCategories like so (note that I call the addItems() before notifyDataSetChanged()
private void loadCategories() {
sampleDB = openOrCreateDatabase(AppConstants.DB_NAME, MODE_PRIVATE,
null);
Cursor menuCursor = sampleDB.rawQuery("select * from menu", null);
categories.clear();
while (menuCursor.moveToNext()) {
String menu = menuCursor.getString(menuCursor
.getColumnIndex("name"));
String id = menuCursor.getString(menuCursor.getColumnIndex("id"));
Category category = new Category(menu, id);
categories.put(id, category);
}
menuCursor.close();
//ADD CALL TO addItems TO UPDATE THE LIST OF THE categoryAdapter instance
categoryAdapter.addItems(categories);
categoryAdapter.notifyDataSetChanged();
}
have you tried saying:
categoryList.setAdapter(null);
categoryList.setAdapter(categoryAdapter);

Custom adapter list view is not getting refreshed

Here is my adapter class.
public class CustomListViewAdapterRetailList extends ArrayAdapter<RowItem> {
Context context;
public ImageLoader imageLoader;
public CustomListViewAdapterRetailList(Context context,
int textViewResourceId, List<RowItem> objects) {
super(context, textViewResourceId, objects);
this.context = context;
imageLoader = new ImageLoader(context);
}
/* private view holder class */
private class ViewHolder {
ImageView retailerImage;
TextView retailerName;
TextView retailerSlogan;
TextView msgDesc;
ImageView typeImage;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.retailer_list_list_item,
null);
holder = new ViewHolder();
holder.retailerImage = (ImageView) convertView
.findViewById(R.id.retailer_list_item_iv_icon);
holder.retailerName = (TextView) convertView
.findViewById(R.id.retailer_list_item_tv_title);
holder.retailerSlogan = (TextView) convertView
.findViewById(R.id.retailer_list_item_tv_slogan);
holder.msgDesc = (TextView) convertView
.findViewById(R.id.retailer_list_item_tv_msg);
holder.typeImage = (ImageView) convertView
.findViewById(R.id.retailer_list_item_iv_type);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
//downloading image
imageLoader.DisplayImage(Perma.uImageRetailer[position],
holder.retailerImage);
holder.retailerName.setText(rowItem.getuNameRetailer());
holder.retailerSlogan.setText(rowItem.getuSloganRetailer());
holder.msgDesc.setText(rowItem.getuDescRetailer());
holder.typeImage.setImageResource(rowItem.getUtypeMsg());
return convertView;
}
}
Here is my main activity.
ListView retailListView;
List<RowItem> retailRowItems;
CustomListViewAdapterRetailList adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.retailer_list);
lSearch = (RelativeLayout) findViewById(R.id.rlist_ll_top);
searchBox = (EditText)findViewById(R.id.rlist_et_search);
startSearch = (Button)findViewById(R.id.rlist_bt_search_initiate);
retailRowItems = new ArrayList<RowItem>();
Log.i("in retailer list",""+Perma.retailerArrayLength);
for (int i = 0; i < Perma.retailerArrayLength; i++) {
Log.i("in retailer list","infor");
RowItem item = new RowItem(Perma.uNameRetailer[i],
Perma.uSloganRetailer[i], Perma.uImageRetailer[i],
Perma.uDescRetailer[i], Perma.typeRetailer[i]);
Log.i("retailer list",""+Perma.uNameRetailer[i]+""+Perma.uImageRetailer[i]);
retailRowItems.add(item);
}
retailListView = (ListView) findViewById(R.id.rlist_lv);
// i tried to clear data but it clears whole list and does not populate with new data.
/* if(adapter!=null){
adapter.clear();}
*/
adapter = new CustomListViewAdapterRetailList(this,
R.layout.retailer_list_list_item, retailRowItems);
retailListView.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
retailListView.invalidateViews();
adapter.notifyDataSetChanged();
}
Now the thing is
user clicks a button , a dialog appears , user select checkboxes and hit Ok.
then new data is loaded.
I have tried clear(), invalidate() and notifyDataSetChanged()
but they are not working.
Please help me out here, and please give answers in context of my code because I'm still a newbie.
Thanks in advance !!
Here is the answer.
protected void onResume() {
super.onResume();
/// here i used it in resume because my data was changing because of user interaction with dialog. so its should be in in resume.
if(!retailRowItems.isEmpty()){
///now if row is populated clear its data
retailRowItems.clear();
///populate again
for (int i = 0; i < Perma.retailerArrayLength; i++) {
RowItem item = new RowItem(Perma.uNameRetailer[i],
Perma.uSloganRetailer[i], Perma.uImageRetailer[i],
Perma.uDescRetailer[i], Perma.typeRetailer[i]);
retailRowItems.add(item);
}
}
///notify adapter
adapter.notifyDataSetChanged();
}
You can also override your adapter's notifyDataSetChanged() method:
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
//refresh your List<RowItem> objects here
}

How to get the values from string to textview? in Android

In my application I want to display some items in a list, I kept all items in String array and brought by using code
String[] activities = getResources().getStringArray(R.array.Contents);
Now my task is assign these string array values to my TextView.
Any suggestions?
In MainActivity.class
String[] activities = getResources().getStringArray(R.array.Contents);
List<RowItem> rowItems;
In onCreate(){
super.onCreate(savedInstanceState);
setContentView(layoutname);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(activities[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(id of ListView);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
}
In RowItem class
public class RowItem {
private String activities;
public RowItem(String activities {
this.activities = activities;
}
public String getActivities() {
return activities;
}
public void setactivities(String activities) {
this.activities = activities;
}
#Override
public String toString() {
return activities;
}
}
In CustomBaseAdapter class
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
private class ViewHolder {
TextView txtActivities;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.activities);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtActivites.setText(rowItem.getActivity());
return convertView;
}
}
try this
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_list_item_1, activities);
mylistView.setAdapter(aa);

Android ArrayAdapters convertviews tag null after update

I'm trying to update my custom ArrayAdapter, but after calling updateListArray getView is called and the convertview is not null but the tag is null, giving me errors. If I make an extra null check and set a new viewholder it simply shows the wrong content.
I simply can't figure out why this gives me problems, I have following in code:
public class CustomAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> mListItems;
public CustomAdapter (Context context, int rowResourceId, ArrayList<Item> items) {
super(context, rowResourceId, items);
mListItems = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
// setup holder
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_row, null);
holder.mEventStart = (TextView) convertView.findViewById(R.id.row_date);
holder.mTitle = (TextView) convertView.findViewById(R.id.row_artist);
holder.mSubTitle = (TextView) convertView.findViewById(R.id.row_description);
holder.mImage = (ImageView) convertView.findViewById(R.id.row_artist_image);
holder.mScene = (ImageView) convertView.findViewById(R.id.row_scene_image);
holder.mStatus = (ImageView) convertView.findViewById(R.id.row_new);
holder.mRowParent = (View) convertView.findViewById(R.id.row_parent);
} else {
// get existing row view
holder = (ViewHolder) convertView.getTag();
}
//setup row view content
if(!mListItems.isEmpty()) {
//set content
}
return convertView;
}
public void updateListArray(ArrayList<Item> list) {
this.clear();
for(Item item : list) {
this.add(item);
}
mListItems = list;
notifyDataSetChanged();
}
getTag() will be null unless you have used setTag(). It will probably work as you want if you remove the call to getTag()

Categories

Resources