I'm newbie. For couple of days I'm trying to resolve this issue, but no luck. Any help ? Thanks in advance.
Below is the images,
I selected few items and then scrolled up
Once scrolled down selection disappears
Below the adapter class I implemented,
/**
* Created by abcd on 27/1/17.
*/
public class ListItemAdapterTaxCheckBox extends BaseAdapter {
//flag = 1 name/id
//flag =2 //ID/Name
public class HolderCheck
{
TextView tv;
CheckBox ck;
}
private static LayoutInflater inflater=null;
Tax[] result;
Context context;
Tax[] selections = null;
String [] IDs = null;
boolean bAllSel = false;
Resources res = null;
public ListItemAdapterTaxCheckBox(Activity mainActivity, Tax[] prgmNameList, Tax[] sel, Resources rs, String [] ids) {
result=prgmNameList;
context=mainActivity;
selections = sel;
if(selections==null)
{
selections = new Tax[1];
selections[0] = new Tax();
}
IDs = ids;
res = rs;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return result.length + 1;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final HolderCheck holderCk = new HolderCheck();;
View rowView = convertView;
final int pos = position;
rowView = inflater.inflate(R.layout.custom_list_check_box, null);
holderCk.tv = (TextView) rowView.findViewById(R.id.code);
holderCk.ck = (CheckBox) rowView.findViewById(R.id.checkBox1);
if(position==0) {
holderCk.tv.setText(context.getString(R.string.all_text));
}
else {
holderCk.tv.setText("" + result[position-1].m_TaxID + " - " + result[position-1].m_TaxName);
}
holderCk.tv.setTextSize(16);
holderCk.tv.setTextColor(Color.BLACK);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holderCk.ck.isChecked()) {
holderCk.tv.setBackgroundColor(Color.WHITE);
holderCk.ck.setChecked(false);
if(pos!=0)
{
if (IDs != null)
IDs[pos -1] = "0";
}
else
{
bAllSel = false;
}
} else {
holderCk.tv.setBackgroundColor(GetResourceColor.getColorWrapper(context, R.color.selHintColor));
holderCk.ck.setChecked(true);
if(pos!=0)
{
if (IDs != null)
IDs[pos -1] = "" + result[pos-1].m_TaxID;
}
else
{
bAllSel = true;
}
}
}
});
return rowView;
}
public String [] getIDs() {
if(bAllSel)
return null;
else {
ArrayList<String> arrayList = new ArrayList<String>();
for (int i = 0, j = 0; i < IDs.length; i++) {
if (IDs[i].trim() != "0") {
arrayList.add(j, IDs[i].trim());
j = j + 1;
if (arrayList.size() == MySQLHelper.MAXITEMSLISTDELETE)
break;
}
}
return arrayList.toArray(new String[arrayList.size()]);
}
}
}
Below the way I'm populating the ListView
//class member
Tax[] valuesTaxID = null;
//inside a method
//default
Tax[] tx = new Tax[1];
tx[0] = new Tax();
if (valuesTaxID != null) {
listV.setAdapter(null);
listV.setAdapter(new ListItemAdapterTaxCheckBox(ctx, valuesTaxID, tx, rs, Ids));
listV.setVisibility(View.VISIBLE);
ListView will create and destroy views when you scroll. Your code is changing a checkbox when a view is clicked, but you store that info nowhere else, you scroll, ListView destroys the view when you scroll, and there you lost the status of the view.
You want to store the "checked" state of the view somewhere. Could be an ArrayList with states, could be a tag attached to the ViewHolders, ... just store it somewhere.
Related
I fulfill the AlertDIalog and ListView with two values Name and id, and I cannot find conclusion оr the right way, when i checked some CheckBoxes, i need the value of the Checked/Selected rows of (id's text) to save.
#OnClick(R.id.group_delete)
void deleteGroup() {
AlertDialog.Builder dialog4 = new AlertDialog.Builder(PreviewActivity.this);
LayoutInflater inflater2 = getLayoutInflater();
View convertView2 = (View) inflater2.inflate(R.layout.alert_dialog_delete_group, null);
dialog4.setView(convertView2);
ListView listView2 = (ListView) convertView2.findViewById(R.id.listViewGroup);
final List<Item> groupList = this.getGroup();
CustomAdapter listAdapter2 = new CustomAdapter(getBaseContext(), groupList);
// listAdapter2.notifyDataSetChanged();
convertView2.setTag(dialog4);
// SparseBooleanArray sp = listView2.getCheckedItemPositions();
listView2.setOnItemClickListener((AdapterView<?> adapterView, View view, int position, long l) -> {
// Get user selected item.
Object itemObject = adapterView.getAdapter();
Item itemDto = (Item) itemObject;
CheckBox itemCheckbox = (CheckBox) convertView2.findViewById(R.id.checkMark5);
listAdapter2.setCheckedItem(position);
});
ImageView delete = (ImageView) convertView2.findViewById(R.id.del_group);
delete.setOnClickListener((View view) -> {
CheckBox itemCheckbox = (CheckBox) convertView2.findViewById(R.id.checkMark5);
Iterator<String> it = listAdapter2.getCheckedItems().values().iterator();
for (int i=0;i<listAdapter2.getCheckedItems().size();i++){
//Do whatever
// String result = "";
// ArrayList<String> resultList = new ArrayList<String>();
// for (int y = 0; y < resultList.size(); y++) {
// result += String.valueOf(resultList.get(i)) + "\n";
// }
// if (result.matches("")) {
////
// Toast.makeText(getApplicationContext(),"Please select some thing from list to show",Toast.LENGTH_LONG).show();
// }
// else {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// }
listAdapter2.getItem(Integer.parseInt(it.next()));
}
// List<Item> resultList = listAdapter2.getCheckedItems();
// for (int i = 0; i < resultList.size(); i++) {
// result += String.valueOf(resultList.get(i)) + "\n";
// }
// listAdapter2.getCheckedItemPositions().toString();
//
// if (result.matches("")) {
//
// Toast.makeText(getApplicationContext(),"Please select some thing from list to show",Toast.LENGTH_LONG).show();
// }
// else {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// }
// shared.setSharedPreferencesString(Constants.ID, size2);
listAdapter2.notifyDataSetChanged();
});
listView2.setAdapter(listAdapter2);
listView2.setTag(dialog4);
AlertDialog alert4 = dialog4.create();
alert4.show();
alert4.getWindow().
setBackgroundDrawable(new ColorDrawable(android.graphics.Color.argb(0, 100, 100, 100)));
}
public List<Company> getCompanies() {
return mCompanies;
}
private List<Item> getGroup() {
ArrayList<String> groups = new ArrayList<String>();
ArrayList<String> groups2 = new ArrayList<>();
for (Group group2 : mRepository.getCompanies().get(posit).getGroups()) {
groups2.add(group2.getId());
}
for (Group group1 : mRepository.getCompanies().get(posit).getGroups()) {
groups.add(group1.getName());
}
List<Item> ret = new ArrayList<Item>();
int length = groups.size();
for (int i = 0; i < length; i++) {
String itemText2 = groups.get(i);
String itemText3 = groups2.get(i);
Item dto = new Item();
dto.setChecked(false);
dto.setIdText(itemText3);
dto.setItemText(itemText2);
ret.add(dto);
}
return ret;
}
Item Class:
public class Item {
private boolean checked ;
private String itemText = "";
private String IdText = "";
private String IdText2 = "";
public String getIdText2() {
return IdText2;
}
public void setIdText2(String idText2) {
IdText2 = idText2;
}
public String getIdText() {
return IdText;
}
public void setIdText(String idText) {
IdText = idText;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getItemText() {
return itemText;
}
public void setItemText(String itemText) {
this.itemText = itemText;
}}
CustomAdapter :
public class CustomAdapter extends BaseAdapter {
private List<Item> ItemList ;
public HashMap<String, String> checked = new HashMap<String, String>();
private Context ctx;
public CustomAdapter(Context ctx, List<Item> ItemList) {
this.ctx = ctx;
this.ItemList = ItemList;
}
public void setCheckedItem(int item) {
if (checked.containsKey(String.valueOf(item))) {
checked.remove(String.valueOf(item));
} else {
checked.put(String.valueOf(item), String.valueOf(item));
}
}
public HashMap<String, String> getCheckedItems() {
return checked;
}
#Override
public int getCount() {
return ItemList.size();
}
#Override
public Object getItem(int position) {
return ItemList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ItemViewHolder viewHolder = null;
if (convertView != null) {
viewHolder = (ItemViewHolder) convertView.getTag();
} else {
convertView = View.inflate(ctx, R.layout.custom, null);
CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkMark5);
TextView listItemText = (TextView) convertView.findViewById(R.id.item_unit_id5);
TextView tetx = (TextView) convertView.findViewById(R.id.tekst5);
TextView textId = (TextView) convertView.findViewById(R.id.item_number5);
viewHolder = new ItemViewHolder(convertView);
viewHolder.setItemCheckbox(checkbox);
viewHolder.setItemTextView(listItemText);
viewHolder.setIdTextView(textId);
viewHolder.setIdTextView2(tetx);
convertView.setTag(viewHolder);
}
Item items = ItemList.get(position);
viewHolder.getItemCheckbox().setChecked(items.isChecked());
viewHolder.getItemTextView().setText(items.getItemText());
viewHolder.getIdTextView().setText(items.getIdText());
viewHolder.getIdTextView2().setText(items.getIdText2());
return convertView;
}}
ViewHolder :
public class ItemViewHolder extends RecyclerView.ViewHolder {
private CheckBox itemCheckbox;
private TextView IdTextView;
private TextView itemTextView;
private TextView IdTextView2;
public TextView getIdTextView2() {
return IdTextView2;
}
public void setIdTextView2(TextView idTextView2) {
IdTextView2 = idTextView2;
}
public ItemViewHolder(View itemView) {
super(itemView);
}
public TextView getIdTextView() {
return IdTextView;
}
public void setIdTextView(TextView idTextView) {
IdTextView = idTextView;
}
public CheckBox getItemCheckbox() {
return itemCheckbox;
}
public void setItemCheckbox(CheckBox itemCheckbox) {
this.itemCheckbox = itemCheckbox;
}
public TextView getItemTextView() {
return itemTextView;
}
public void setItemTextView(TextView itemTextView) {
this.itemTextView = itemTextView;
} }
Been stucked at here more than a week but still unable to solve! I have an expandable listView where the data were retrieved from SQLite and set to expListAdapter. Once the arrow clicked, it will display two child items.
AddMonthlyExpenses
public class AddMonthlyExpenses extends AppCompatActivity {
ArrayList<ListObj> groupList= new ArrayList<ListObj>();;
List<String> childList;
Map<ListObj, List<String>> laptopCollection;
ExpandableListView listview;
ExpandableListAdapter expListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_monthly_expenses);
laptopCollection = new LinkedHashMap<ListObj, List<String>>();
listview = (ExpandableListView) findViewById(R.id.exlistView);
expListAdapter = new ExpandableListAdapter(getApplication(), groupList, laptopCollection);
listview.setAdapter(expListAdapter);
retrieveList(name);
}
public void retrieveList(String name) {
database = mdb.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + MyDatabaseHelper.TABLE__TASK + " WHERE Name = ? ", new String[]{name}, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
groupList = new ArrayList<ListObj>();
int iD = cursor.getInt(cursor.getColumnIndex("ID"));
String month = cursor.getString(cursor.getColumnIndex("Month"));
double budget = cursor.getDouble(cursor.getColumnIndex("Budget"));
groupList.add(new ListObj(iD,month,budget));
if (expListAdapter != null) {
expListAdapter.add(iD, month, budget);
createCollection(); // for child items
listview.setAdapter(expListAdapter);
}
}
}
}
private void createCollection() {
String[] options = {"Edit","Delete"};
for (ListObj laptop : groupList) {
loadChild(options);
laptopCollection.put(laptop, childList);
}
}
private void loadChild(String[] laptopModels) {
childList = new ArrayList<String>();
for (String model : laptopModels)
childList.add(model);
}
}
ExpandableListAdapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
Map<ListObj, List<String>> laptopCollections;
private ArrayList<ListObj> laptops;
double used = 0;
private LayoutInflater mInflater;
public ExpandableListAdapter(Context context, ArrayList<ListObj> laptops, Map<ListObj, List<String>> laptopCollections) {
this.context = context;
this.laptopCollections = laptopCollections;
this.laptops = laptops;
mInflater = LayoutInflater.from(context);
}
public Object getChild(int groupPosition, int childPosition) { // error line
if (laptopCollections.get(laptops.get(groupPosition)).get(childPosition) != null && !laptopCollections.get(laptops.get(groupPosition)).get(childPosition).isEmpty()) {
return laptopCollections.get(laptops.get(groupPosition)).get(childPosition);
}
return 1;
}
public void add(int id, String month, double budget) {
String[] splited = month.split("\\s+");
ListObj obj = new ListObj(id, month, budget);
obj.setYear(splited[1]);
obj.setMonth(splited[0]);
obj.setBudget(budget);
obj.setID(id);
laptops.add(obj);
this.notifyDataSetChanged();
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getCount() {
return laptops.size();
}
public ListObj getItem(int position) {
return laptops.get(position);
}
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final String laptop = (String) getChild(groupPosition, childPosition); // here the error line
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_item, null);
}
TextView edit = (TextView) convertView.findViewById(R.id.textEdit);
edit.setText(laptop);
return convertView;
}
public int getChildrenCount(int groupPosition) {
if (laptopCollections.get(laptops.get(groupPosition)) != null && ! laptopCollections.get(laptops.get(groupPosition)).isEmpty()) {
return laptopCollections.get(laptops.get(groupPosition)).size();
}
return 1;
}
public Object getGroup(int groupPosition) {
return laptops.get(groupPosition);
}
public int getGroupCount() {
return this.laptops.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ExpensesAdapter.ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.expenses_adapter, null);
holder = new ExpensesAdapter.ViewHolder();
holder.month = (TextView) convertView.findViewById(R.id.textMonth);
holder.budget = (TextView) convertView.findViewById(R.id.textAmount);
holder.year = (TextView) convertView.findViewById(R.id.textYear);
convertView.setTag(holder);
} else {
holder = (ExpensesAdapter.ViewHolder) convertView.getTag();
}
holder.month.setText(laptops.get(groupPosition).getMonth());
holder.budget.setText(String.format("%.2f", laptops.get(groupPosition).getBudget()));
holder.year.setText(laptops.get(groupPosition).getYear());
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Error
10-26 00:03:57.114 23612-23612/com.example.tony.monthlyexpenses
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at
com.example.tony.monthlyexpenses.adapter.ExpandableListAdapter.getChild(ExpandableListAdapter.java:42)
at
com.example.tony.monthlyexpenses.adapter.ExpandableListAdapter.getChildView(ExpandableListAdapter.java:87)
at
android.widget.ExpandableListConnector.getView(ExpandableListConnector.java:451)
at android.widget.AbsListView.obtainView(AbsListView.java:2232)
at android.widget.ListView.makeAndAddView(ListView.java:1849)
at android.widget.ListView.fillDown(ListView.java:678)
at android.widget.ListView.fillSpecific(ListView.java:1339)
My apps screen shot
I tried debug but nothing is null !
You can clone my project from link below
https://github.com/wseng92/MonthlyExpenses
Add createCollection(); to button1 setonclick listner
createCollection();
groupList = new ArrayList(); is written inside for loop might be problem? It creates a new arraylist for each loop and as a result your arraysize is 1 always ( last iteration count )
while (cursor.moveToNext()) {
groupList = new ArrayList<ListObj>();
int iD = cursor.getInt(cursor.getColumnIndex("ID"));
String month = cursor.getString(cursor.getColumnIndex("Month"));
double budget = cursor.getDouble(cursor.getColumnIndex("Budget"));
groupList.add(new ListObj(iD,month,budget));
createCollection(); // for child items
if (expListAdapter != null) {
expListAdapter.add(iD, month, budget);
listview.setAdapter(expListAdapter);
}
}
change to
groupList = new ArrayList<ListObj>();
while (cursor.moveToNext()) {
int iD = cursor.getInt(cursor.getColumnIndex("ID"));
String month = cursor.getString(cursor.getColumnIndex("Month"));
double budget = cursor.getDouble(cursor.getColumnIndex("Budget"));
groupList.add(new ListObj(iD,month,budget));
createCollection(); // for child items
if (expListAdapter != null) {
expListAdapter.add(iD, month, budget);
listview.setAdapter(expListAdapter);
}
}
I ran in to a similar problem year or two ago. Can not remember anymore which version it was.
Starting from call
public Object getChild(int groupPosition, int childPosition) {
if (laptopCollections.get(laptops.get(groupPosition)).get(childPosition) ...
What is the value of laptops? It is initialized with constructor
public ExpandableListAdapter(Context context, ArrayList<ListObj> laptops ...
on second parameter, it is created on AddMonthlyExpenses.onCreate()
expListAdapter =
new ExpandableListAdapter(getApplication(), groupList, laptopCollection);
and initially initialized in declaration
ArrayList<ListObj> groupList= new ArrayList<ListObj>();;
For some reason unknown to me - Android peculiarity - in my case this groupList (or similar member field i had) was NULL even it was initialized on declaration.
But moving the initialization inside onCreate() fixed this problem.
Try that. Or at lease debug the row where laptops is referenced.
i think in your code dont work this
laptopCollections.get(laptops.get(groupPosition)).size();
because try find other object instance.
you have so many list in your fragment and adapter you really dont need this. Try keep OOP and refactor this and create better model for this.
or easier way dont use for map key object but id then.
change from
Map<ListObj, List<String>> laptopCollections
to
Map<String,List<String>> laptopCollections where first K is id.
Maybe it will be helpfull.
I have a ToDo project with listview that shows the data from SQLite with custom adapter. Also, I have a button to add the new task but, the items in list view will be repeated.
my custom adapter is
public class CustomAdapter extends BaseAdapter {
private final Activity activity;
private final ArrayList < LT_Model > data;
private static LayoutInflater inflater = null;
public CustomAdapter(Activity a, ArrayList < LT_Model > d) {
this.activity = a;
this.data = d;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
public TextView task;
public ImageView imgD;
public ImageView imgE;
public ImageView imgS;
}#
Override
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
#
Override
public Object getItem(int position) {
return position;
}
#
Override
public long getItemId(int position) {
return position;
}
#
Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_todo, null);
holder = new ViewHolder();
holder.task = (TextView) convertView.findViewById(R.id.task_title);
holder.imgD = (ImageView) convertView.findViewById(R.id.imgDelete);
holder.imgE = (ImageView) convertView.findViewById(R.id.imgEdit);
holder.imgS = (ImageView) convertView.findViewById(R.id.imgCheck);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
if (data.size() <= 0) {
holder.task.setText("No Data");
} else {
holder.task.setText(data.get(position).getTaskName());
holder.imgD.setImageResource(android.R.drawable.ic_delete);
holder.imgE.setImageResource(data.get(position).getImgComment());
holder.imgS.setImageResource(data.get(position).getImgStatus());
}
return convertView;
}
}
My LT_Model with getter and setter
public class LT_Model {
private String TaskName = "";
private int ImgComment;
private int ImgStatus;
public String getTaskName() {
return TaskName;
}
public void setTaskName(String taskName) {
TaskName = taskName;
}
public int getImgComment() {
return ImgComment;
}
public void setImgComment(int imgComment) {
ImgComment = imgComment;
}
public int getImgStatus() {
return ImgStatus;
}
public void setImgStatus(int imgStatus) {
ImgStatus = imgStatus;
}
}
My UpdateUI which return the data to Arraylist from SQLite in the activity.
My table has 3 columns and I passed them to ArrayList.
private void updateUI() {
ArrayList<LT_Model> taskList = new ArrayList<>();
LT_Model lt_model = new LT_Model();
SQLiteDatabase db = mdb.getReadableDatabase();
Cursor cursor = db.query(DB_Value.Constant.List_Table,
new String[]{DB_Value.Constant._ID, DB_Value.Constant.COL_Task, DB_Value.Constant.COL_Comment,
DB_Value.Constant.COL_Status}, null, null, null, null, null);
while (cursor.moveToNext()) {
//int idx = cursor.getColumnIndex(DB_Value.Constant.COL_Task);
lt_model.setTaskName(cursor.getString(1));
Toast.makeText(getApplicationContext(), lt_model.getTaskName(), Toast.LENGTH_SHORT).show();
if (cursor.getString(2) == null || cursor.getString(2).equals("")) {
lt_model.setImgComment(android.R.drawable.ic_menu_edit);
}else{
lt_model.setImgComment(android.R.drawable.ic_menu_agenda);
}
if (cursor.getInt(3)==1){
lt_model.setImgStatus(android.R.drawable.checkbox_on_background);
}else{
lt_model.setImgStatus(android.R.drawable.checkbox_off_background);
}
taskList.add(lt_model);
}
mTaskListView.setAdapter(new CustomAdapter(dailyNew, taskList));
cursor.close();
db.close();
}
and this is my problem.
When I add the second task the title of first task would change with that, and this is repeated for the others rows.
When you iterate through your cursor, you need to make a new Model for each row, so you're adding a distinct object each time.
while (cursor.moveToNext()) {
LT_Model lt_model = new LT_Model();
I am trying to create an android application using a database from Parse.com. I am using a custom adapter to create a listview. I don't find any errors with the code and yet the listeview is not showing up. Nothing there in the logcat as well. Just the listview does not show up.
lv = (ListView)findViewById(R.id.listView);
mProgress = (ProgressBar)findViewById(R.id.check_progress);
mProgress.setVisibility(View.VISIBLE);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Sellers");
query.orderByAscending("Name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
studentsList = new ArrayList<Sellers>();
for (ParseObject ob : parseObjects) {
s = new Sellers();
s.setName(ob.getString("Name").toString());
s.setAddress1(ob.getString("Address1").toString());
s.setAddress2(ob.getString("Address2").toString());
s.setShopName(ob.getString("ShopName").toString());
s.setEmail(ob.getString("Email").toString());
s.setPhone(ob.getString("Phone").toString());
s.setZipcode(ob.getString("Zipcode").toString());
studentsList.add(s);
}
adapter = new ListviewAdapter(CheckStatus.this, studentsList);
lv.setAdapter(adapter);
mProgress.setVisibility(View.GONE);
} else {
mProgress.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
This is the activity where I am invoking the listview.
public class ListviewAdapter extends BaseAdapter{
private final static String TAG = ListviewAdapter.class.getSimpleName();
private Context activity;
private LayoutInflater inflater = null;
private List<Sellers> sellers;
int layout;
public ListviewAdapter(Context activity, List<Sellers> sellers) {
this.activity = activity;
this.sellers = sellers;
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView name ;
TextView shop ;
TextView address1 ;
TextView address2;
TextView phone;
TextView email;
RelativeLayout rl;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v =view;
ViewHolder holder = new ViewHolder();
if (view == null) {
LayoutInflater li = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.list_item_layout,null);
holder.name = (TextView)v.findViewById(R.id.seller_name);
holder.shop = (TextView)v.findViewById(R.id.shop_name);
holder.address1 = (TextView)v.findViewById(R.id.address1);
holder.address2 = (TextView)v.findViewById(R.id.address2);
holder.phone = (TextView)v.findViewById(R.id.phone);
holder.email = (TextView)v.findViewById(R.id.emailID);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Sellers s = sellers.get(position);
// String a = s.Name;
// Log.d(TAG, a);
holder.name.setText(s.getName());
holder.shop.setText(s.getShopName());
holder.address1.setText(s.getAddress1());
holder.address2.setText(s.getAddress2());
holder.phone.setText(s.getPhone());
holder.email.setText(s.getEmail());
Log.d("CustomAdapter.class", "CustomAdapter");
// imageView.setImageDrawable(s.getPic());
return v;
}
}
And this is the custom adapter. There are no null pointer exceptions showing up in the logcat. I can't determine why the listview is not getting populated.
Try this;
#Override
public int getCount() {
return sellers.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position:
}
You have to implement your code on getCount() by return number of item listview will be created.
I know this question has been asked thousands of times but I couldn't find an answer for my case for some reason.
What I have is a thread that fetches data from a web services and populates a list with the info. Then I want to press a button and call the same thread to fetch some more data and add it to the list.
But when I call notifyDataSetChanged(), the list for some reason doesn't refresh. The data is in the adapter though...
Here's the code:
#Override
protected void onPostExecute(PropertyNotesParser result) {
this.progressDialog.dismiss();
ArrayList<PropertyNoteHistory> propertyNoteList = result.getAllTheNotes();
addNoteListItems(propertyNoteList);
Collections.sort(getNoteList());
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> subtitles = new ArrayList<String>();
DateHandler handleDate = new DateHandler();
DataResolve convert = new DataResolve();
for(Iterator<PropertyNoteHistory> i = getNoteList().iterator(); i.hasNext(); ) {
PropertyNoteHistory item = i.next();
PropertyNoteHistory.Note note = item.getNotes();
PropertyNoteHistory.Jobs jobs = item.getJobs();
// Default value is office in case the xml does not have the tag "job" associated with "note".
String service = "Office";
if(jobs != null){
service = convert.getServiceName(jobs.getServiceID());
}
titles.add(note.getTitle() + " (" + service + ")");
subtitles.add(handleDate.formatDate(note.getDate(), "dd MMM yyyy") + " Ref: " + note.getJobID());
}
if(getConnectionCount() == 0){
adapter = new SimpleListAdapter(getActivity(), titles, subtitles);
lv.setAdapter(adapter);
}
else {
adapter.addItem(titles, subtitles);
}
and my adapter:
public class SimpleListAdapter extends BaseAdapter {
private int count = 0;
private static LayoutInflater inflater = null;
private ArrayList<String> titles = new ArrayList<String>();
private ArrayList<String> subtitles = new ArrayList<String>();
private ArrayList<Integer> imageResource = new ArrayList<Integer>();
private boolean hasImage = false;
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles, ArrayList<Integer> imageResource) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.imageResource = imageResource;
this.hasImage = true;
}
/**Constructor that creates an adapter with only a title and subtitle.
* #param activity The context.
* #param titles ArrayList with the titles of each list option.
* #param subtitles ArrayList with the subtitles of each list option. */
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.hasImage = false;
}
public void addItem(ArrayList<String> title, ArrayList<String> subtitle){
this.titles.addAll(title);
this.subtitles.addAll(subtitle);
notifyDataSetChanged();
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null)
v = inflater.inflate(R.layout.layout_simple_list, null);
final ImageView icon = (ImageView) v.findViewById(R.id.icon);
final TextView title = (TextView) v.findViewById(R.id.title);
final TextView subtitle = (TextView) v.findViewById(R.id.subtitle);
title.setText(titles.get(position));
subtitle.setText(subtitles.get(position));
if (hasImage) {
icon.setImageResource(imageResource.get(position));
}
else {
icon.setVisibility(ImageView.GONE);
}
return v;
}
}
You will need to update your count variable too in addItem so that the all the rows are created when notifyDataSetChanged is called