I have a ListView that is being populated with collection of items using a custom adapter. One of the properties of the collection is a count, and I have two TextViews in my ListView layout, one for the text and one for the count. I'd like not to display the count TextView if the count is zero. The code I have works fine when the ListView is initially loaded, but when I scroll the ListView, the count will show on random rows and constantly change if scroll the ListView up and down. This is the code I have:
public class Main extends ListActivity
{
private static CustomAdapter adapter = null;
#Override
public void onCreate(Bundle icicle)
{
List<Item> items = new ArrayList<Item>();
items = GetItems();
adapter = new CustomAdapter();
for (Item item : items)
adapter.addItem(item);
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
/* ADAPTER */
private class CustomAdapter extends BaseAdapter
{
private final List<Item> mData = new ArrayList<Item>();
private final LayoutInflater mInflater;
public CustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Item item) {
mData.add(item);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
final Item item = (Item)this.getItem(position);
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.main, parent, false);
holder.text = (TextView)convertView.findViewById(R.id.text);
holder.count = (TextView)convertView.findViewById(R.id.count);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.text.setText(item.getTitle());
if (item.getCount() > 0)
holder.count.setText(item.getCount().ToString());
else
holder.count.setVisibility(View.INVISIBLE);
return(convertView);
}
}
static class ViewHolder {
TextView text, count
}
Layout:
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
EDIT:
I was able to get it working by doing a hacky workaround. It seems setting the TextView's visibility to Invisible or Gone was causing the issue, so I just changed the color of the items with a zero count to the background color:
if (item.getCount() > 0)
holder.count.setText(item.getCount().ToString());
else
holder.count.setTextColor(Color.WHITE);
If anyone has a real fix, please let me know.
You should just do this:
if (item.getCount() > 0) {
holder.count.setText(item.getCount().ToString());
holder.count.setVisibility(View.VISIBLE);
}
else
holder.count.setVisibility(View.INVISIBLE);
Because you use a ViewHolder, you need to consider the fact that you might get an old View that's not showing the count. This means we need to make sure that the visibility of count is set to VISIBLE. Equally we want to hide it if the count is zero - so we change the visibility even though we might get a View that is all ready invisible.
I think you wrong a part of your code, Amend test this code:
if (item.getCount() > 0)
holder.count.setText(item.getCount());
else
holder.count.setVisibility(View.INVISIBLE);
Please go through this code you may helpful for the same.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.select);
mListUsers = getUsers();
lvUsers = (ListView) findViewById(R.id.lv_user);
s = new ListAdapter(this, R.id.lv_user, mListUsers);
lvUsers.setAdapter(s);
lvUsers.setClickable(true);
// lvUsers.setTextFilterEnabled(true);
lvUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
Object o = lvUsers.getItemAtPosition(position);
UserBO obj = (UserBO) o;
Intent intent = new Intent(Select.this,Update.class);
intent.putExtra("pid", ""+obj.getId());
intent.putExtra("name", obj.getName());
//put data which you want to show and select.
startActivity(intent);
}
});
}
public ArrayList<UserBO> getUsers()
{
DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
//Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM profiledatabase";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
try {
user.pid = Integer.parseInt(list.get(0));
//write code to get data from table
} catch (Exception e) {
//Log.i("***" + Select.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
// ***ListAdapter***
private class ListAdapter extends ArrayAdapter<UserBO> {
// --CloneChangeRequired
private ArrayList<UserBO> mList;
// --CloneChangeRequired
public ListAdapter(Context context, int textViewResourceId,ArrayList<UserBO> list) {
// --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try
{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null);
// --CloneChangeRequired(list_item)
}
final UserBO listItem = mList.get(position);
// --CloneChangeRequired
if (listItem != null)
{
// setting list_item views
//( (TextView) view.findViewById(R.id.tv_pid) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.tv_name) ).setText( listItem.getName() );
( (TextView) view.findViewById(R.id.tv_email)).setText(listItem.getEmail());
( (TextView) view.findViewById(R.id.tv_contact) ).setText( listItem.getContact()+"" );
}}catch(Exception e)
{
//Log.i(Select.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
Related
I'm trying to create a listview with different items within it. I want to use a switch statement to do this but I'm struggling to produce this I have created this with one XML layout how can I use multiple XML Layouts. I've attached my code - thank you in advance!
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postlist);
this.generateDummyData();
ListView listView = (ListView) this.findViewById(R.id.postListView);
final PostItemAdapter itemAdapter = new PostItemAdapter(getApplicationContext(), this.generateDummyData());
listView.setAdapter(itemAdapter);
}
private ArrayList<PostData> generateDummyData() {
PostData data = null;
ArrayList<PostData> listData = new ArrayList<PostData>();
for (int i = 0; i < 20; i++) {
data = new PostData();
data.postTitle = "Person " + (i + 1)
+ " Name Surname";
data.postThumbUrl = null;
listData.add(data);
}
return listData;
}
// Get dummy data for Activity Feed
class PostDataTask extends AsyncTask<Integer, Void, Void> {
ArrayList<PostData> recentTracks;
#Override
protected Void doInBackground(Integer... page) {
try {
// Get a page of 15 tracks
// Simplified - getPage accepts 'page' and 'limit' parameters and returns a Collection<Track>
recentTracks = new ArrayList<PostData>();
Thread.sleep(3000);
PostData data = null;
for (int i = 0; i < 10; i++) {
data = new PostData();
data.postTitle = "Person " + (i + 1)
+ " Name is the Post Title from RSS Feed";
data.postThumbUrl = null;
recentTracks.add(data);
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView listView = (ListView) findViewById(R.id.postListView);
PostItemAdapter adapter = ((PostItemAdapter) ((HeaderViewListAdapter) listView.getAdapter()).getWrappedAdapter());
if (adapter == null) {
adapter = new PostItemAdapter(getApplicationContext(), recentTracks);
listView.setAdapter(adapter);
} else {
adapter.addAll(recentTracks);
adapter.notifyDataSetChanged();
}
}
}
public class PostItemAdapter extends ArrayAdapter<PostData> {
private final Context context;
private final ArrayList<PostData> items;
private int currentPage = 0;
public PostItemAdapter(Context context, ArrayList<PostData> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.items = recentTrackArrayList;
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.postitem,
parent, false);
}
final PostData item = items.get(position);
rowView = convertView;
ImageView thumbImageView = (ImageView) rowView
.findViewById(R.id.postThumb);
if (items.get(position).postThumbUrl == null) {
thumbImageView.setImageResource(R.drawable.postthumb_loading);
}
TextView postTitleView = (TextView) rowView
.findViewById(R.id.postTitleLabel);
postTitleView.setText(items.get(position).postTitle);
if (position == getCount() - 1) {
currentPage++;
new PostDataTask().execute(currentPage);
}
return convertView;
}
}
}
At first use ViewHolder pattern.
At second make interfase of Item which will include two methods:
getType() - which return the type of your item;
getView(LayoutInflater inflater, View convertView) - which return the view of row. Inside this method create ViewHolder instance, then inflate View parameter to VH and do some action with result view.
. Then create 2 (or how much u need) classes which would implement Item. Define methods. Then in ListAdapter in getView() call getView() of items and return it to list.
Using the view holder pattern won't work if your items are completely different.
For every item, you need to check what kind of item you want to display and inflate a different view depending on it (for example, using a switch as you said)
I have another blocker as I study Android Development.
This time my problem is when I wanted to "selectively" highlight a row in a ListView populated by data from an adapter.
This ListView is actually within a dialog, and purpose is to show a list of friends, where user can multi-select and highlight it as he selects.
The selected values by the way, is stored in an ArrayList "arr_FriendsShare" so that the next time he opens the listview, rows will be highlighted (via onScrollListener) for those previously selected.
What is currently happening, only the "recently" or "last" clicked row/item is highlighted; and seems to be clearing all the previously highlighted rows.
I cannot understand why it is behaving that way, as row's value is successfully stored to/removed from arr_FriendsShare ArrayList, as I click on it.
Below is my listener codes, and thanks in advance for the usual help:
//Item click listener for Select Friends ListView
listview_SelectFriends.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String friends_ListItemSelected = (String)adapter.getItemAtPosition(position);
if(!arr_FriendsShare.contains(friends_ListItemSelected)){
arr_FriendsShare.add(friends_ListItemSelected);
}
else{
removeItemFromArrayListString(Main.this, arr_FriendsShare, friends_ListItemSelected);
}
}
});
listview_SelectFriends.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
for (int i = firstVisibleItem; i < (visibleItemCount + firstVisibleItem); i++) {
String listViewItemText = view.getItemAtPosition(i).toString();
if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(getResources().getColor(R.color.red_light));
view.setSelector(cd);
}
else if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(Color.TRANSPARENT);
view.setSelector(cd);
}
}
}
});
Additional Code Block:
ArrayList<String> stringArray = new ArrayList<String>();
String jsonURL = <SOME URL HERE>;
stringArray = Global.getStringArrayFromJSON(Main.this, jsonURL, "friends", "FriendUsername");
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.friends_list_layout, null);
ListView listview_SelectFriends = (ListView) convertView.findViewById(R.id.layout_Friends);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
listview_SelectFriends.setAdapter(adapter);
Change
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
to
// Define this at class level as --> private FriendsAdapter adapter = null;
adapter = new FriendsAdapter(Main.this, stringArray);
add this method in your activity
private void setResetSelection(int index, boolean setSelection){
View v = listview_SelectFriends.getChildAt(index);
if(v != null){
TextView name = (TextView) v.findViewById(R.id.name);
if(setSelection)
name.setBackgroundResource(R.color.red);
else
name.setBackgroundResource(R.color.transparent);
}
}
and create a new class as
public class FriendsAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> mFriends;
private ArrayList<String> mSelectedFriends = new ArrayList<String>();
public GoodPeopleAdapter(Context context, ArrayList<String> friends) {
mInflater = LayoutInflater.from(context);
mFriends= friends;
}
public void setSelectedFriends(ArrayList<String> selectedFriends){
mSelectedFriends = selectedFriends;
}
#Override
public int getCount() {
return mFriends.size();
}
#Override
public Object getItem(int position) {
return mFriends.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if(convertView == null) {
view = mInflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.name);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
String name = mFriends.get(position);
holder.name.setText(name);
if(mSelectedFriends.contains(name))
holder.name.setBackgroundResource(R.color.red) // red is in color xml by default, change according to your choice
return view;
}
private class ViewHolder {
public TextView name;
}
}
Add following line at the end of method onItemClick
adapter.setSelectedFriends(arr_FriendsShare);
Add this in the if part of onItemClick
setResetSelection(position, true);
and this in else part
setResetSelection(position, false);
Also create a new xml layout with name row_layout with a textview with id name.
I have a custom listview and spinner.First of all i am filling the listview and then i am clicking dropdown spinner.I am choosing a item(city).I want to update listview with new result.But whatever i can custom adapter getview is not call. So listview is not update. This is my screen
How can i do it?
I am filling spinner here
private void getCityListWithSpinner() {
cityListRequest = new CityListRequest(new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
System.out.println("Objemizzz " + obj.toString());
cityArrayList = (ArrayList<CityList>) obj;
Spinner ss = (Spinner) findViewById(R.id.cityfilmspinner);
CinemaCitySelector2 citySelector = new CinemaCitySelector2();
cityList.add("Seçiniz");
for (int i = 0; i < cityArrayList.size(); i++) {
cityList.add(cityArrayList.get(i).getCinemaCity());
citySelector.CinemaCitySelector2(
CinemaCityMoviePickerActivity.this, ss, cityList,2);
}
}
CinemaCitySelector:
public class CinemaCitySelector2 implements OnItemSelectedListener {
Context context2;
Spinner spinner2;
CityListInCityRequest cityListInCityRequest2;
ArrayList<Cinema> cityListInCityArrayList2;
ListView list_cinema_movie_selectorr2;
CinemaListViewAdapter2 adapter2;
View row2;
int act2 = 0;
Spinner cityspinner;
public void CinemaCitySelector2(Context context, Spinner spinner,
ArrayList<String> cityList, int activityfrom) {
this.context2 = context;
this.spinner2 = spinner;
act2 = activityfrom;
// Declaring an Adapter and initializing it to the data pump
ArrayAdapter adapter = new ArrayAdapter(context,
android.R.layout.simple_list_item_1, cityList);
// Setting Adapter to the Spinner
spinner.setAdapter(adapter);
// Setting OnItemClickListener to the Spinner
spinner.setOnItemSelectedListener(CinemaCitySelector2.this);
}
// Defining the Callback methods here
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
String city = spinner2.getItemAtPosition(pos).toString();
LayoutInflater layoutInflater = LayoutInflater.from(context2);
row2 = layoutInflater.inflate(
R.layout.activity_cinemacitymoviepicker, null, false);
list_cinema_movie_selectorr2 = (ListView) row2
.findViewById(R.id.listfilmincinema);
if (!city.equals("Seçiniz")) {
cityListInCityRequest2 = new CityListInCityRequest(
new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
// adapter.clear();
// adapter.notifyDataSetChanged();
// list_cinema_movie_selector.setAdapter(adapter);
System.out.println("Objemizzz " + obj.toString());
cityListInCityArrayList2 = (ArrayList<Cinema>) obj;
// adapter.notifyDataSetChanged();
adapter2 = new CinemaListViewAdapter2(context2,
R.layout.cinema_list,
cityListInCityArrayList2);
list_cinema_movie_selectorr2
.setAdapter(adapter2);
}
#Override
public void asyncOperationFailed(Object obj, int queue) {
// TODO Auto-generated method stub
System.out.println("Objemizzz2 " + obj.toString());
}
}, city);
}
}
public void onNothingSelected(AdapterView arg0) {
// TODO Auto-generated method stub
}
}
CinemaListViewAdapter2:
public class CinemaListViewAdapter2 extends ArrayAdapter<Cinema> {
Context context;
int arraycount=0;
public CinemaListViewAdapter2(Context context, int resourceId,
ArrayList<Cinema> items) {
super(context, resourceId, items);
this.context = context;
arraycount=items.size();
}
/*private view holder class*/
private class ViewHolder {
BlackBrandTextview cinemaName;
RelativeLayout cinemalist;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Cinema rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.cinema_list, null);
holder = new ViewHolder();
holder.cinemaName = (BlackBrandTextview) convertView.findViewById(R.id.txt_cinema_name);
holder.cinemalist=(RelativeLayout)convertView.findViewById(R.id.cinemalist);
holder.cinemaName.setText(rowItem.getCinemaName());
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
convertView.setTag(holder);
} else{
holder = (ViewHolder) convertView.getTag();
holder.cinemaName.setText(rowItem.getCinemaName());
}
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
holder.cinemaName.setText(rowItem.getCinemaName());
return convertView;
}
I'd create a method to update the adapter once an item on your spinner is chosen:
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
city = (String) parent.getItemAtPosition(position);
resetCinema(city); //or onRestart();
}
public void onNothingSelected(AdapterView<?> parent){
}
});
And resetCinema(city) rechages the view depending on the city value. You can do this manually:
public void resetCinema(String city) {
//show list view elements depending on city
}
or just call a refresh of the whole Activity:
protected void onRestart() {
Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.
}
I suggest you to call
adapter2.notifyDataSetChange();
But anyway there is no need to initialize a new adapter every time.
you should create a method inside the adapter like this:
public void setMyArray(ArrayList<Cinema> items) {
myArray.clear();
myArray.addAll(items);
notifyDataSetChange();
}
I got a list, that i would like to show in a ListView, using my own custom adapter. So this list have some null values in it, and also some "important" not-null values.
It could be like this:
(N representing Null)
(D representint some valuable data)
myList:
[N,N,D,D,N,N,D,N,D,N,N] for example.
So i got my adapter, but i cannot handle the null values in the list.
This is my adapter:
public class ItemAdapter extends ArrayAdapter {
List<Item> itemList;
private Activity act;
boolean selling;
public ItemAdapter(Activity act, List<Item> itemList, boolean selling) {
super(act, R.layout.item_view_layout, itemList);
this.itemList = itemList;
this.act = act;
this.selling = selling;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final Item itemManipulated = itemList.get(position);
if (convertView == null) {
convertView = new ItemInShopView(act, itemManipulated);
holder = new ViewHolder();
holder.convertView = convertView;
holder.itemNameTextView = (TextView) ((ItemView) convertView).getItemNameTextView();
holder.iconImageView = (ImageView) ((ItemView) convertView).getItemIconImageView();
holder.coinView = (CoinView) ((ItemInShopView) convertView).getCoinView();
holder.coinView.init(act);
holder.itemRarityHidedTextView = (TextView) ((ItemView) convertView).getItemRarityHidedTextView();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemNameTextView.setText(itemManipulated.getName());
holder.iconImageView.setImageResource(itemManipulated.getIcon());
holder.itemRarityHidedTextView.setText(itemManipulated.getRarity());
Colorer.setTextViewColorByItemRarity(holder.itemNameTextView, holder.getRarity(), act);
if (selling) {
holder.coinView.setCoins(itemManipulated.getSellPrice());
} else {
holder.coinView.setCoins(itemManipulated.getPrice());
}
holder.convertView.setOnClickListener(new OnClickListenerWithPreventDoubleTapper(itemManipulated));
holder.convertView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
return convertView;
}
class OnClickListenerWithPreventDoubleTapper extends OnClickListenerWithPreventDoubleTap {
Item item;
public OnClickListenerWithPreventDoubleTapper(Item item) {
this.item = item;
}
#Override
protected void performAction() {
new ItemDialog(act, item).show();
}
}
static class ViewHolder {
TextView itemRarityHidedTextView;
TextView itemNameTextView;
ImageView iconImageView;
CoinView coinView;
View convertView;
public String getRarity() {
return itemRarityHidedTextView.getText().toString();
}
}
}
How could i implement some way to get the adapter handle null values and shows nothing there, or maybe show a dummy layout with nothing on it?
I couldnt make a new list without null values and pass these new list to the adapter, because the nulls have an important meaning in an other view.
I hope my problem is clear. Please help if you can.
Why not just?
if (itemManipulated != null){
holder.itemNameTextView.setText(itemManipulated.getName());
holder.iconImageView.setImageResource(itemManipulated.getIcon());
holder.itemRarityHidedTextView.setText(itemManipulated.getRarity());
Colorer.setTextViewColorByItemRarity(holder.itemNameTextView, holder.getRarity(),act);
if (selling) {
holder.coinView.setCoins(itemManipulated.getSellPrice());
} else {
holder.coinView.setCoins(itemManipulated.getPrice());
}
} else {
holder.itemNameTextView.setText("No Item");
... (whatever default values you like)
}
Edit:
If you don't want to display nulls at all you will need to do something more complex.
in getView: find the nth piece of actual data
in getCount: return the number of pieces of actual data
getView:
int posInArray = -1;
for (int i =0; i <= position; i++){
posInArray++;
while(itemList.get(posInArray) == null){
posInArray++;
}
}
itemManipulated = itemList.get(posInArray);
...
getCount:
int count = 0;
for(int i = 0; i < itemList.size(); i++){
if (itemList.get(i) != null){
count++;
}
}
return count;
I have a listview, and i start an intent to fill it. But the list shows up with a default image and no text. It is supposed to show up with different images and text.
I have two arrays, one is in string type and the other one is in drawable type... But my list doesn't show me none of these that i wanted...
My ListActivity:
public class fillLeftMenu extends ListActivity {
private View menu;
ImageView findLocation;
Spinner cityList;
ListView leftList;
String [] textIndex;
Drawable [] imageIndex;
ArrayList<LeftListItems> Left;
listAdapter lAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataTransfer dt = BonubonActivity.deneme;
menu = dt.getView();
findLocation = (ImageView) menu.findViewById(R.id.image_findLocation);
leftList = (ListView) menu.findViewById(R.id.list);
// add items to listView
Left = new ArrayList<LeftListItems>();
textIndex = new String[] {"Bugünün Fırsatları", "Son Dakika Bonusları", "Kadın", "Aile", "Çocuk", "Alışveriş", "Şehirden Kaçış", "Kışa Özel"};
imageIndex = new Drawable[] {leftList.getResources().getDrawable(R.drawable.kucukicon_01),leftList.getResources().getDrawable(R.drawable.kucukicon_02),leftList.getResources().getDrawable(R.drawable.kucukicon_03),leftList.getResources().getDrawable(R.drawable.kucukicon_04),leftList.getResources().getDrawable(R.drawable.kucukicon_05),leftList.getResources().getDrawable(R.drawable.kucukicon_06),leftList.getResources().getDrawable(R.drawable.kucukicon_07),leftList.getResources().getDrawable(R.drawable.kucukicon_08)};
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);
getIndex();
lAdapter.notifyDataSetChanged();
leftList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
finish();
}
private void getIndex() {
try{
LeftListItems item = new LeftListItems();
for(int i=0; i<textIndex.length; i++) {
item.setText(textIndex[i]);
item.setImage(imageIndex[i]);
Left.add(item);
lAdapter.add(Left.get(i));
}
}
catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
}
private class listAdapter extends ArrayAdapter<LeftListItems> {
private ArrayList<LeftListItems> items;
private Context ctx;
public listAdapter(Context ctx, int textViewResourceId, ArrayList<LeftListItems> items) {
super(ctx, textViewResourceId, items);
this.ctx = ctx;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
LeftListItems index = items.get(position);
if(index != null) {
TextView text = (TextView) v.findViewById(R.id.text);
ImageView img = (ImageView) v.findViewById(R.id.icon);
if(text != null)
text.setText(index.getText());
if(img != null)
img.setBackgroundDrawable(index.getImage());
}
return v;
}
}
}
Try calling getIndex() method before creating the adapter and setting it to the list. Like this:
getIndex();
//then create new adapter
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);