notifyDataSetChanged Android ListView and VideoView - android

My app has a ListView and each row contains a TextView running a timer and a video player (ExoMediaPlayer) in each row
I refresh each row by listAdapter.notifyDataSetChanged() to update the timer TextView every second. It works fine as shown in the below code.
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
updateTextView();
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
private void updateTextView() {
if (listView != null) {
for (int i = 0; i <= listView.getListChildCount(); i++) {
View v = listView.getListChildAt(i);
if (v != null) {
for(int x=firstVisibleRow;i<=lastVisibleRow;i++)
{
HomeListItem data;
data = listMockData.get(i);
HListAdapter.notifyDataSetChanged();
TextView t = (TextView) v.findViewById(R.id.tvTimer);
t.setText(data.getElapsedTime());
}
}
}
}
}
Adapter
public HListAdapter(Context context, ArrayList<HomeListItem> listData) {
c = context;
layoutInflater = LayoutInflater.from(context);
this.listData = listData;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return listData.indexOf(getItem(position));
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.location_list_row, null);
holder.timer= (TextView) convertView.findViewById(R.id.timer);
holder.videoPlayer = (EMVideoView) convertView.findViewById(R.id.videoPlayer);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
newsItem = listData.get(position);
holder.timer.setText(newsItem.getElapsedTime());
String videolink = "http://www.someurl.com/";
holder.videoPlayer.setVideoURI(Uri.parse(videolink ));
holder.videoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
holder.videoPlayer.start();
}
});
return convertView;
}
static class ViewHolder {
TextView timer;
EMVideoView videoPlayer;
}
Problem
The above code works good and the timer TextView updates the time every second.
But the problem i am facing is the VideoPlayer is being reloaded every second, the video does not play due to HListAdapter.notifyDataSetChanged();
if i remove the notifyDataSetChanged() video plays on the listview but the timer TextView does not get updated.
Any possibility to refresh/update the TextView timer only every second.
Any logic or method to solve the problem and make the video play and also the timer to be updated every second?

I think your logic in updateTextView method is wrong. See my comments
private void updateTextView() {
if (listView != null) {
for (int i = 0; i <= listView.getListChildCount(); i++) {
View v = listView.getListChildAt(i);
if (v != null) {
for(int x=firstVisibleRow;i<=lastVisibleRow;i++) // what is x here ?!!
{
HomeListItem data;
data = listMockData.get(i);
HListAdapter.notifyDataSetChanged();
TextView t = (TextView) v.findViewById(R.id.tvTimer);
t.setText(data.getElapsedTime()); // here you are setting the same text over and over
}
}
}
}
}
Instead go with this
private void updateTextView() {
if (listView != null) {
for (int i = 0; i < listView.getListChildCount(); i++) {
View v = listView.getListChildAt(i);
HomeListItem data;
data = listMockData.get(firstVisibleRow + i);
TextView t = (TextView) v.findViewById(R.id.tvTimer);
t.setText(data.getElapsedTime());
}
}
}
no need of notifyDataSetChanged()

Related

Fail to AsyncTask update progressBar's progress when first enter the fragment ListView, then okay after scroll ListView

The progressbar cannot show progress if without scroll down and back to same position visit again, detail please check this demo:
https://www.youtube.com/watch?v=wGu8MyUHidQ&feature=youtu.be
No exception or error, maybe ListView bug or logic error, anyone have any idea?
DownloadInfo class:
private final static String TAG = DownloadInfo.class.getSimpleName();
public enum DownloadState {
NOT_STARTED,
QUEUED,
DOWNLOADING,
COMPLETE
}
private volatile DownloadState mDownloadState = DownloadState.NOT_STARTED;
private final String mFilename;
private volatile Integer mProgress;
private final Integer mFileSize;
private volatile ProgressBar mProgressBar;
public DownloadInfo(String filename, Integer size) {
mFilename = filename;
mProgress = 0;
mFileSize = size;
mProgressBar = null;
}
//Follow by getters & setters
DownloadInfoArrayAdapter Class:
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
private static class ViewHolder {
TextView textView;
ProgressBar progressBar;
Button button;
DownloadInfo info;
}
public DownloadInfoArrayAdapter(Context context, List<DownloadInfo> objects) {
super(context, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final DownloadInfo info = getItem(position);
ViewHolder holder = null;
if (null == row) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_download_row, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
holder.button = (Button) row.findViewById(R.id.downloadButton);
holder.info = info;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
holder.info.setProgressBar(null);
holder.info = info;
holder.info.setProgressBar(holder.progressBar);
}
holder.textView.setText(info.getFilename());
holder.progressBar.setProgress(info.getProgress());
holder.progressBar.setMax(info.getFileSize());
info.setProgressBar(holder.progressBar);
holder.button.setEnabled(info.getDownloadState() == DownloadState.NOT_STARTED);
final Button button = holder.button;
holder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
info.setDownloadState(DownloadState.QUEUED);
button.setEnabled(false);
button.invalidate();
FileDownloadTask task = new FileDownloadTask(info);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
return row;
}
}
FileDownloadTask class:
#Override
protected void onProgressUpdate(Integer... values) {
mInfo.setProgress(values[0]);
ProgressBar bar = mInfo.getProgressBar();
if (bar != null) {
bar.setProgress(mInfo.getProgress());
bar.invalidate();
}
}
#Override
protected Void doInBackground(Void... params) {
Log.d(TAG, "Starting download for " + mInfo.getFilename());
mInfo.setDownloadState(DownloadState.DOWNLOADING);
for (int i = 0; i <= mInfo.getFileSize(); ++i) {
try {
Thread.sleep(16);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
mInfo.setDownloadState(DownloadState.COMPLETE);
return null;
}
#Override
protected void onPostExecute(Void result) {
mInfo.setDownloadState(DownloadState.COMPLETE);
}
#Override
protected void onPreExecute() {
mInfo.setDownloadState(DownloadState.DOWNLOADING);
}
In the fragment add click listener
lvStickerGroup = (ListView) activity.findViewById(R.id.lvStickerGroup);
List<DownloadInfo> downloadInfo = new ArrayList<DownloadInfo>();
for (int i = 0; i < 50; ++i) {
downloadInfo.add(new DownloadInfo("File " + i, 1000));
}
adapter = new DownloadInfoArrayAdapter(activity, downloadInfo);
lvStickerGroup.setAdapter(adapter);
lvStickerGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(activity, "bla" + i, Toast.LENGTH_SHORT).show();
}
});
//Testing all below, no luck
((BaseAdapter) adapter).notifyDataSetChanged();
lvStickerGroup.invalidate();
lvStickerGroup.invalidateViews();
lvStickerGroup.refreshDrawableState();
lvStickerGroup.post(new Runnable() {
public void run() {
for (int a = 0; a < lvStickerGroup.getCount(); a++) {
lvStickerGroup.setSelection(a);
}
for (int a = lvStickerGroup.getCount() - 1; a >= 0; a--) {
lvStickerGroup.setSelection(a);
}
}
});
I tried to programmatically scroll to bottom and back to top, same no luck, except programmatically scroll to the item position will not show in the first page when enter the fragment initially.
Besides, I tried to invalidate(), invalidateView() notifyDataSetChanged on the adapter, same problem occurs, is it possibly a ListView bug?
Nothing wrong with the code above, fully functional. I found the clue in Google ListView IO conference
https://www.youtube.com/watch?v=wDBM6wVEO70
ListView cannot wrap content, else will have bugs showing up. That why I experience such issue.

android - ArrayAdapter notifyDataSetChanged() called from Handler.post randomly does not call GetView

I have searched between many notifyDataSetChanged() issue questions without finding my specific case, so here it is:
Problem
I have a root thread (started by the UI thread) that listen for something.
Everytime it receives a message, it starts a new thread (let's call them children threads) that does some operations and, at the end of its life, notifies to the UI adapter that an object has been added.
This procedure works 99.99% of the time (I have stressed a lot the program) but in some cases that I cannot understand this notification does not work.
I am sure that the problem is the listview because the two above statements (setImageBitmap) work properly, changing the imageViews images.
Code
Handler initialization in the Activity and passed to the class that works with threads
//class scope variable
private final Handler mHandler = new Handler(new IncomingHandlerCallback(this));
//At the end of the activity class
/**
* ref. https://groups.google.com/forum/#!msg/android-developers/1aPZXZG6kWk/lIYDavGYn5UJ
*/
class IncomingHandlerCallback implements Handler.Callback {
Activity activity;
public IncomingHandlerCallback(Activity activity) {
this.activity = activity;
}
#SuppressWarnings("unchecked")
#Override
public boolean handleMessage(Message msg) {
DeviceUtils.hideKeyboard(activity);
switch (msg.what) {
case EXECUTE_CODE_UPDATE_TCP_COUNT:
updateDebugCounter(true);
break;
.
.
.
case EXECUTE_CODE_UPDATE_LIST_COUNT:
updateDebugCounter(false);
break;
}
return true;
}
}
Like the comment says that declaration is taken here
Custom Array Adapter
public class PlateInfoListAdapter extends ArrayAdapter<PlateInfo> {
private final Activity context;
CheckBox selectAll;
List<PlateInfo> plateList;
AnprInterface anprInterface;
private MobileANPRDetailPopup readingDetailPopup;
public PlateInfoListAdapter(Activity context, List<PlateInfo> plateList, CheckBox selectAll, AnprInterface anprInterface) {
super(context, R.layout.adapter_plate_list, 0,
plateList);
this.context = context;
this.selectAll = selectAll;
this.plateList = plateList;
this.anprInterface = anprInterface;
final LayoutInflater factory = context.getLayoutInflater();
readingDetailPopup = new MobileANPRDetailPopup(context, factory.inflate(R.layout.popup_mobile_anpr_reading_detail, null));
readingDetailPopup.setBackgroundDrawable(Reso.getDrawable(context, R.drawable.grey_border_white_bck));
readingDetailPopup.setOutsideTouchable(true);
readingDetailPopup.update();
}
static class ViewHolder {
protected LinearLayout layout;
protected CheckBox checkBox;
protected TextView date;
protected TextView plate;
protected TextView plateCountry;
protected ImageView blackList;
protected ImageView whiteList;
protected ImageButton readingDetail;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
PlateInfo plateInfo = plateList.get(position);
boolean hotlistDrawn = false;
if(plateList.size() == 1) {
selectAll.setVisibility(View.VISIBLE);
}
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.adapter_plate_list, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.layout = (LinearLayout) view.findViewById(R.id.ll_plate_layout);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.cb_plate);
viewHolder.plate = (TextView) view.findViewById(R.id.tv_plate_plate);
viewHolder.plateCountry = (TextView) view.findViewById(R.id.tv_plate_country);
viewHolder.date = (TextView) view.findViewById(R.id.tv_plate_data);
viewHolder.blackList = (ImageView) view.findViewById(R.id.iv_plate_blacklist);
viewHolder.whiteList = (ImageView) view.findViewById(R.id.iv_plate_whitelist);
viewHolder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Here we get the position that we have set for the checkbox using setTag.
int getPosition = (Integer) buttonView.getTag();
// Set the value of checkbox to maintain its state.
plateList.get(getPosition).setRowChecked(buttonView.isChecked());
}
});
viewHolder.readingDetail = (ImageButton) view.findViewById(R.id.ib_plate_detail);
viewHolder.readingDetail.setFocusable(false);
viewHolder.readingDetail.setFocusableInTouchMode(false);
viewHolder.readingDetail.setTag(plateInfo);
viewHolder.readingDetail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(anprInterface.isReading()) {
return;
}
PlateInfo selectedPlateInfo = (PlateInfo) viewHolder.readingDetail.getTag();
if(selectedPlateInfo != null) {
readingDetailPopup.showCentered(v, selectedPlateInfo);
}
}
});
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
// Restore the checked state properly
holder.checkBox.setTag(position);
holder.checkBox.setChecked(plateInfo.isRowChecked());
holder.plate.setText(plateInfo.getPlate());
holder.plateCountry.setText(plateInfo.getPlateCountry());
holder.date.setText(DateUtils.formatHelianDateToCustomHumanDate("HH:mm:ss dd-MM-yyyy", plateInfo.getDate()));
holder.readingDetail.setTag(plateInfo);
if(plateInfo.getBlackWhiteListNote() != null && !plateInfo.getBlackWhiteListNote().equals("")) {
if(plateInfo.getBlackWhiteListNote().contains("WHITELIST")) {
holder.layout.setBackgroundColor(Reso.getColor(context, R.color.red_light));
holder.whiteList.setVisibility(View.VISIBLE);
hotlistDrawn = true;
}
else {
holder.whiteList.setVisibility(View.INVISIBLE);
}
if(plateInfo.getBlackWhiteListNote().contains("BLACKLIST")) {
holder.layout.setBackgroundColor(Reso.getColor(context, R.color.red_light));
holder.blackList.setVisibility(View.VISIBLE);
hotlistDrawn = true;
}
else {
holder.blackList.setVisibility(View.INVISIBLE);
}
}
else {
holder.layout.setBackgroundColor(Reso.getColor(context, R.color.transparent));
holder.whiteList.setVisibility(View.INVISIBLE);
holder.blackList.setVisibility(View.INVISIBLE);
}
if(plateInfo.isRowSelected()) {
if(hotlistDrawn) {
holder.layout.setBackgroundDrawable(Reso.getDrawable(context, R.drawable.list_selector_red_bck_blue_border_normal));
}
else {
holder.layout.setBackgroundDrawable(Reso.getDrawable(context, R.drawable.list_selector_blue_border_normal));
}
}
else if(hotlistDrawn) {
holder.layout.setBackgroundColor(Reso.getColor(context, R.color.red_light));
}
else {
holder.layout.setBackgroundColor(Reso.getColor(context, R.color.transparent));
}
return view;
}
#Override
public int getCount() {
return plateList.size();
}
#Override
public PlateInfo getItem(int position) {
return plateList.get(position);
}
#Override
public boolean hasStableIds() {
return true;
}
}
The following code is called by the children threads.
Here it is the code that generates the issue:
mHandler.post(new Runnable() {
#Override
public void run() {
mLastPlateImage.setImageBitmap(plateImage);
mLastContextImage.setImageBitmap(contextImageResized);
mPlateInfoList.add(0, plateInfo);
// That is the problem
mPlateListAdapter.notifyDataSetChanged();
System.gc();
}
});

Android Listview Overwrite data instead of append

In my Android application, I am using webservices with index values (for eg.
https://mysampleurl.com/sampledata?username=""&&password=""&&startindex="1"&&endindex="10")
and pass the extracted data to a BaseAdapter via an arraylist and display the result in a listview.
When the listview reaches the bottom, Using asynctask I will increment the index values (for eg.
https://mysampleurl.com/sampledata?username=""&&password=""&&startindex="11"&&endindex="20").
I will receive the data and store it in arraylist and it goes on.
But when I pass array list values to adapter, it overwrites the existing data instead of appending with previous values.
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
System.out.println("position:"+position);
}
I have checked this above code in some other examples, at first it gives values like 1,2,.....10. and at second time it gives 1,2,3,.....20. But in my application it always return the values upto 1,2,3......10.
Could some one tell me what mistake I have done?
public ContentListAdapter (Context context, ArrayList<CommonData> contentList)
{
ctxt = context;
this.ContentList = contentList;
contentListRowInflater = LayoutInflater.from(context);
mSelectedItemsIds=new SparseBooleanArray();
checkBoxState=new boolean[contentList.size()];
}
#Override
public int getCount() {
return (filteredContentList == null)?0:filteredContentList.size();
}
#Override
public Object getItem(int position) {
return filteredContentList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
Here only i pass the values and check the position
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ContentListActivity.adapterFlag = false;
DocumentListViewHolder viewHolder = null;
if (convertView == null || convertView.getTag() == null) {
convertView = contentListRowInflater.inflate(
R.layout.content_list_row, null);
viewHolder = new DocumentListViewHolder();
viewHolder.ivDocumentdoctypeIcon = (ImageView) convertView.findViewById(R.id.ivDocumentTypeIcon);
viewHolder.tvDocumentTitle = (TextView) convertView.findViewById(R.id.tvDocumentTitle);
viewHolder.tvsubitemcount = (TextView) convertView.findViewById(R.id.tvsubitemcount);
viewHolder.ivarrowlauncher = (ImageView)convertView.findViewById(R.id.arrowlauncher);
viewHolder.checkboxselection=(CheckBox)convertView.findViewById(R.id.checkboxdeletion);
checkBoxSelection=viewHolder.checkboxselection;
viewHolder.checkboxselection.setChecked(checkBoxState[position]);
viewHolder.ivarrowlauncher = (ImageView)convertView.findViewById(R.id.arrowlauncher);
mainlayoutrl = (RelativeLayout)convertView.findViewById(R.id.clrrlmain);
sublayoutll = (LinearLayout)convertView.findViewById(R.id.clrowll);
arrowlayoutll = (LinearLayout)convertView.findViewById(R.id.clarrowll);
final Context context = ContentListActivity.contentListActivity;
if(viewHolder.checkboxselection.isChecked()) {
mainlayoutrl.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
sublayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
arrowlayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
} else {
mainlayoutrl.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
sublayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
arrowlayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
}
sublayoutll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Config.networkConnectionCheck(context)) {
if(filteredContentList.get(position).type.equalsIgnoreCase("FOLDER")) {
ContentListActivity.ListarrowClick(position+1,context);
} else if (refreshFlag == false) {
ContentListActivity.oldviewContent(position+1,context);
} else
} else {
ContentListActivity.oldofflineViewContent(position+1,context);
}
}
});
arrowlayoutll.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
ContentListActivity.ListarrowClick(position+1,context);
}
});
viewHolder.ivfilesDownload=(ImageView)convertView.findViewById(R.id.document_list_row_download_imageview);
//newly added by venkat
viewHolder.ivfilesdownloaded=(ImageView)convertView.findViewById(R.id.document_list_row_downloaded_imageview);
viewHolder.tvDocumentDescription=(TextView)convertView.findViewById(R.id.tvdocumentdescription);
} else {
viewHolder = (DocumentListViewHolder) convertView.getTag();
}
viewHolder.tvDocumentTitle.setText(filteredContentList.get(position).name);
String desc = filteredContentList.get(position).versiondescription;
if (desc != null) {
viewHolder.tvDocumentDescription.setText(filteredContentList
.get(position).versiondescription);
}
String doctype = filteredContentList.get(position).type;
String subitemcount = filteredContentList.get(position).subitemcount;
if (doctype.equalsIgnoreCase(ctxt.getResources()
.getString(R.string.pdf))) {
viewHolder.ivDocumentdoctypeIcon
.setImageResource(R.drawable.pdfbigicon);
} else if (doctype.equalsIgnoreCase(ctxt.getResources().getString(
R.string.swf))) {
viewHolder.ivDocumentdoctypeIcon
.setImageResource(R.drawable.flashbigicon);
} if(doctype.equalsIgnoreCase(ctxt.getResources().getString(
R.string.folder)))
{
viewHolder.ivarrowlauncher.setVisibility(View.INVISIBLE);
}
if (filteredContentList.get(position).isupdateavailable
.equalsIgnoreCase(ctxt.getResources().getString(
R.string.update_false_status))) {
} else if (filteredContentList.get(position).isupdateavailable
.equalsIgnoreCase(ctxt.getResources().getString(
R.string.update_true_status))) {
WebAPI webapi = new WebAPI(ctxt);
if (LoginHandler.arraylistdata.size() == 1) {
user_id = LoginHandler.arraylistdata.get(0)
.getUserid();
org_id = LoginHandler.arraylistdata.get(0)
.getOrgId();
} else {
user_id = LoginHandler.arraylistdata.get(
OrgListActivity.selected_org_pos)
.getUserid();
org_id = LoginHandler.arraylistdata.get(
OrgListActivity.selected_org_pos)
.getOrgId();
}
LoginDatabaseHandler loginDBHandler = new LoginDatabaseHandler(
ctxt);
loginDBHandler.open();
int toglState = loginDBHandler.checkOffToggleState(
user_id, org_id, filteredContentList
.get(position).dockey.toString());
}
} else
versionUpdate(position, ctxt);
}
});
}
/*ends*/
return convertView;
}

Get the total count of number of rows in the Custom Listview Android

I am trying to getting the total Count of the getView custom listview. But want to display in the different layout. Here is my onCreatedView. I am not sure how to inflate the layout. Thanks for all your help.
private static ListView addDropListView = null;
private TransactionAddDropAdapter addDropAdapter = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentPendingTrades = inflater.inflate(R.layout.fragment_transactions_pending, container, false);
pendingTradesView = inflater;
return fragmentPendingTrades;
}
public void onViewCreated(final View view, final Bundle savedInstanceState) {
this.addDropListView = (ListView) view.findViewById(R.id.transactions_pending_transactionsListView);
this.addDropAdapter = new TransactionAddDropAdapter(pendingTradesView);
this.addDropListView.setAdapter(this.addDropAdapter);
this.emptyTransationsContainer = view.findViewById(R.id.transactions_pending_transactions_emptyContainer);
TextView getTotalCount = (TextView) view.findViewById(R.id.transactions_pending_TransactionsAddDropCount);
getTotalCount.setText(""+addDropListView.getCount());
}
Here is my Holderview that get the getView
public class TransactionAddDropAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private List<TransactionAddDrop> addDropList = new ArrayList<TransactionAddDrop>();
public TransactionAddDropAdapter(LayoutInflater inflater) {
this.inflater = inflater;
}
public void setAddDropList(List<TransactionAddDrop> addDropList) {
clearAddDropList();
for (TransactionAddDrop ad : addDropList) {
if (ad.isStateApprove()) {
this.addDropApprovalsList.add(ad);
} else {
this.addDropList.add(ad);
}
}
}
public void clearAddDropList() {
this.addDropList.clear();
this.addDropApprovalsList.clear();
}
#Override
public int getCount() {
int size = this.addDropList.size();
if (this.addDropApprovalsList.size() > 0) {
size += 1;
}
return size;
}
#Override
public Object getItem(int position) {
try {
if (this.addDropList == null) {
return null;
} else if (position < addDropList.size()) {
return this.addDropList.get(position);
} else {
return this.addDropApprovalsList;
}
} catch (Exception e) {
return null;
}
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final TransactionAddDrop addDropData = this.addDropList.get(position);
TransactionAddDropViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.fragment_pending_transaction_list_item, null);
holder = new TransactionAddDropViewHolder();
holder.withdrawButton = convertView.findViewById(R.id.pendingTransactionItem_withdrawButton);
holder.addContainer = (LinearLayout) convertView.findViewById(R.id.pendingTransactionItem_addContainer);
holder.dropContainer = (LinearLayout) convertView.findViewById(R.id.pendingTransactionItem_dropContainer);
holder.rootView = convertView.findViewById(R.id.swipeRight);
holder.swipeButtons();
convertView.setTag(holder);
} else {
holder = (TransactionAddDropViewHolder) convertView.getTag();
holder.swipeButtons();
}
}
Ok, I "think" I know what's going on here. You setup your ListView and add its TransactionAddDropAdapter, and then set the total amount of items.
this.addDropListView = (ListView) view.findViewById(R.id.transactions_pending_transactionsListView);
this.addDropAdapter = new TransactionAddDropAdapter(pendingTradesView);
this.addDropListView.setAdapter(this.addDropAdapter);
TextView getTotalCount = (TextView) view.findViewById(R.id.transactions_pending_TransactionsAddDropCount);
getTotalCount.setText(""+addDropListView.getCount());
However, at this point, you haven't called setAddDropList(List<TransactionAddDrop> addDropList) on addDropAdapter, so addDropList in getCount() is still an empty array, so getCount() == 0, which is why you are seeing 0 being displayed.
So, you need to find where you call addDropAdapter.setAddDropList() and then call getTotalCount.setText(""+addDropListView.getCount()); right after in order to update the total number of rows.

Update TextView within custom ListView

I'm trying to update the TextView within a custom ListView at a set time interval, for example the TextView will update every 200ms however I can't figure out how to do this. The object updates with a number internally and I would like to show that in the mTitleText Textview however as the code below shows at the moment I can only achieve it when the user presses a button.
public class ListAdapter extends BaseAdapter {
private ArrayList< Object > mObjects;
private int mNumObjs = 0;
private LayoutInflater mLayoutInflater;
private Context mContext;
public ListAdapter ( Context context, ArrayList< Object > objects ) {
mObjects;= objects;
mLayoutInflater = LayoutInflater.from(context);
mContext = context;
}
public int getCount() {
return mObjects;.size();
}
public Object getItem( int position ) {
return mObjects;.get(position);
}
public long getItemId( int position ) {
return position;
}
public void addObject( Object obj) {
obj.setId(mNumObjs);
mObjects.add( obj );
(mNumObjs);++;
notifyDataSetChanged();
}
public void deleteObject( int pos ) {
mObjects;.remove( pos );
notifyDataSetChanged();
}
public View getView( final int position, View convertView, ViewGroup parent ) {
final TimerView holder;
if( convertView == null ) {
convertView = mLayoutInflater.inflate( R.layout.customlistview, null );
holder = new HolderView();
holder.mListPosition = position;
holder.mDeleteButton = (Button)convertView.findViewById(R.id.Delete);
holder.mDeleteButton.setText( "Button No: " + position );
holder.mDeleteButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteObject(holder.mListPosition);
}
});
holder.mButton = (Button)convertView.findViewById(R.id.Button);
holder.mButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Object obj = mObjects.get(holder.mListPosition);
mTitleText.setText(obj.getNum());
}
});
convertView.setTag(holder);
}
else {
holder = (TimerView) convertView.getTag();
}
holder.mListPosition = position;
holder.mDeleteButton.setText( "Button No: " + position );
return convertView;
}
class HolderView{
int mListPosition;
Button mDeleteButton;
Button mButton;
TextView mTitleText;
}
}
Okay I managed to figure this out myself, if your updates don't need to be very frequent ( >1 sec ) you can use notifyDataSetChanged() however if like me you need to constantly update the listview every 200ms or so you need to iterate through the visible objects on the list view and update it.
private Runnable showUpdate = new Runnable(){
public void run(){
mAdapter.updateList();
//mAdapter.notifyDataSetChanged();
int count = mListView.getCount();
for( int i = 0; i < count; i ++ )
{
View convertView = mListView.getChildAt( i );
if( convertView != null )
{
HolderView holder = (HolderView) convertView.getTag();
Object obj = (Object)mAdapter.getItem( holder.mListPosition );
holder.mTitleText.setText( obj.getText() );
}
}
}
};
Thread mThread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(100);
mHandler.post(showUpdate);
//mHandler.sendEmptyMessage(MSG_UPDATE);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Update the text in your list mObjects and call notifyDataSetChanged() on your adapter.

Categories

Resources