Android Listview Overwrite data instead of append - android

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;
}

Related

Listview add item one at a time

I have a listview and a button in my main activity and three layout ressource files (right.xml, mid.xml and left.xml [They're relative layout]).
I want to make an arrayList (with strings and drawable (images)) and each time I push the button in main.xml the first content of the arrayList will appear at the bottom of the screen (either left, mid or right --> depend of the order of the arrayList) and when I click again the next item (string or drawable) will appear beneath it, pushing it in an upward motion.
UPDATE
I made a Model and an Adapter
Here is the model
public class ModelC1 {
public String C1Name;
public String C1Text;
public int id;
public boolean isSend;
public ModelC1(String C1Name, String C1Text, int id, boolean isSend){
this.id = id;
this.C1Name = C1Name;
this.C1Text = C1Text;
this.isSend = isSend;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getC1Name() {
return C1Name;
}
public void setC1Name(String C1Name){
this.C1Name = C1Name;
}
public String getC1Text() {
return C1Text;
}
public void setC1Text (String C1Text){
this.C1Text = C1Text ;
}
public boolean isSend() {
return isSend;
}
public void setIsSend(boolean send){
isSend = send;
}
Here is the Adapter
public class AdapterC1 extends BaseAdapter {
private List<ModelC1> listChat;
private LayoutInflater inflater;
private Context context;
public AdapterC1(List<ModelC1> listChat, Context context){
this.listChat = listChat;
this.context = context;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listChat.size();
}
#Override
public Object getItem(int i) {
return listChat.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View vi = convertView;
if(convertView == null ){
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}else{
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}
if(listChat.get(i).isSend() !=0 || listChat.get(i).isSend() !=1 || listChat.get(i).isSend() !=2 ){
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
if(bubbleTextView != null)
bubbleTextView.setText(listChat.get(i).C1Text);
TextView nameTextView = (TextView) vi.findViewById(R.id.nameChat);
if(nameTextView != null)
nameTextView.setText(listChat.get(i).C1Name);
}else{
vi=inflater.inflate(R.layout.list_mid,null);
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
bubbleTextView.setText("THE END");
}
return vi;
}
And here is the activity
public class Chat1 extends AppCompatActivity {
private static final String TAG = "Chat1";
private AdapterC1 adapter;
private List<ModelC1> listChat = new ArrayList<>();
private int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
RecyclerView chatContent1 = findViewById(R.id.chatContent1);
}
private ModelC1 setUpMessage(){
Log.d(TAG, "setUpMessage: Exec");
return();
}
///OnClick of the button in the activity_chat1.xml
public void nextClicked1(View view) {
Log.d(TAG, "nextClicked: Is Clicked");
///After the limit of the arraylist is reached
final int limit = 40;
if(count == limit){
Log.d(TAG, "nextClicked: Limit Reached");
Intent i = new Intent(Chat1.this, MainActivity.class);
startActivity(i);
}else{
///Call the list
loadList(null);
}
}
///Load the list of arrays?
public void loadList(View view){
ModelC1 chat = setUpMessage();
listChat.add(chat);
///The ID of the recycleview in the activity_chat1.xml
final RecyclerView recyclerview = findViewById(R.id.chatContent1);
///The adapter
final AdapterC1 adapter = new AdapterC1(listChat, this);
///Make the recyclerview always scroll
///the adapter
///recyclerview.setAdapter(adapter);
}
My questions are now how do I make the ArrayList (containing strings and drawables) and how to link the ArrayList to make it appear one by one when I click on the button ?
As for the ArrayList, will soemthing like that works ?
private List<List<String>> textChat1 = new ArrayList<List<String>>();
ArrayList<String> textChat1 = new ArrayList<String>();
textChat1.add("This is message 1");
textChat1.add("This is message 2");
textChat1.add("This is message 2");
addresses.add(textChat1);
How can I add images and how to say which strings inflate which layout (left, mid or right) ?
You can do your job like this: in your Adapter's getView method ,
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
if (position == 1) {
convertView = getLayoutInflater().inflate(R.layout.left, container, false);
} else if (position == 2) {
convertView = getLayoutInflater().inflate(R.layout.mid, container, false);
} else {
convertView = getLayoutInflater().inflate(R.layout.right, container, false);
}
}
//your code here
return convertView;
}
This will do your job, but, I suggest you to use Recyclerview because it's more efficient and better in terms of looks as well as memory management.

Android ListView glitching back to top for a few seconds before it works properly

I am trying to make an application with a ListView that include a Country Flag and name. This is so that the user can click on them and be shown images of the country that they wouldve taken before. However for about 3 seconds when the listview loads if i try to scroll it will sort of glitch and send me back to top. This is the code..
public class CountriesListAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater inflater;
private List<CountryModel> countryModels;
private WeakReference<TextView> selectedCountryIdtxt;
private boolean useFilter;
private WeakReference<ProgressBar> progressBarWeakReference;
public int getSelectedCountryId() {
return selectedCountryId;
}
public void setSelectedCountryId(int selectedCountryId) {
this.selectedCountryId = selectedCountryId;
}
private int selectedCountryId;
public CountriesListAdapter(#NonNull WeakReference<Context> context, int resourceId, WeakReference<TextView> textView, #NonNull List<CountryModel> countryModelList, boolean useFilter, WeakReference<ProgressBar> progressBarWeakReference){
super(context.get(), resourceId, countryModelList);
selectedCountryIdtxt = textView;
resource = resourceId; //the id of the template file
inflater = LayoutInflater.from(context.get());
this.countryModels = countryModelList;
selectedCountryId = -1;
this.useFilter = useFilter;
this.progressBarWeakReference = progressBarWeakReference;
}
public int getCount() {
if (countryModels != null)
return countryModels.size();
return 0;
}
public CountryModel getItem(int position) {
if (countryModels != null)
return countryModels.get(position);
return null;
}
public long getItemId(int position) {
if (countryModels != null)
return countryModels.get(position).hashCode();
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// this method is automatically called for every object in our list
//basically it's called for every single row before it is generated
// this method is called per row
convertView = (ConstraintLayout) inflater.inflate(resource, null);
//the variable countryModel is fiiled with current object that is being processed
final CountryModel countryModel = countryModels.get(position);
TextView countryName = convertView.findViewById(R.id.countryNamelbl);
final ImageView countryFlag = convertView.findViewById(R.id.countryFlagimg);
final ImageView checked = convertView.findViewById(R.id.countryCheckedimg);
//this is done for every object in the list
assert countryModel != null;
countryName.setText(countryModel.getName());
Picasso.get().load(countryModel.getImage()).fit().into(countryFlag);
if(!useFilter) {
if (selectedCountryId == countryModel.getId()) {
checked.setVisibility(View.VISIBLE);
} else {
checked.setVisibility(View.INVISIBLE);
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!useFilter) {
if (checked.getVisibility() == View.VISIBLE) {
checked.setVisibility(View.INVISIBLE);
selectedCountryId = -1;
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
} else {
if (selectedCountryId == -1) {
checked.setVisibility(View.VISIBLE);
selectedCountryId = countryModel.getId();
} else {
selectedCountryId = countryModel.getId();
notifyDataSetChanged();
}
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
}
} else {
Intent i = new Intent(getContext(), PicturesActivity.class);
i.putExtra("countryId",countryModel.getId());
i.putExtra("countryName", countryModel.getName());
getContext().startActivity(i);
}
}
});
progressBarWeakReference.get().setVisibility(View.INVISIBLE);
return convertView;
}
public List<CountryModel> getCountryModels() {
return countryModels;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.countryModels = countryModels;
}
}
The problem was actually in another class, i was calling the adapter for every list item instead of just once... oops.
Thanks for the replies though!

How to disable previous items in a ListView

I am trying to develop an activity where there is a custom listView made out of CustomAdapter.
The list consists of a TextView and an EditText. The EditText when clicked, it auto fetches the system time.
What I want is when a particular EditText is filled, I want all the previous(above) list items in the sequence to be disabled.
So far, I have tried using isEnabled() and areAllItemsEnabled() functions returning respective boolean values using position, but however didn’t work.
Please help me achieve the above.
Thanks.
This is my CustomAdapter Class
public class SelectStnListByRoute extends BaseAdapter implements View.OnClickListener {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if(position==position){
return false;
}
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position)); //Here I am getting the position of the row item clicked, where should I put the Onclick false for disabling all of the above fields using the position?
}
});
viewHolder.txtStnDep.setOnClickListener(this);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
int ref;
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case txtArrivalTime:
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
textViewArrVal.setClickable(false);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
break;
case txtDepTime:
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
break;
default:
break;
}
}
public String getCurrentTime(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
You can do this as below mentioned -:
You need to store the position of clicked button was. So initialize a variable in your class
int mButtonSelected = -1;
EDIT 1.
Then make a change to your isEnabled method
#Override
public boolean isEnabled(int position) {
if(position<mButtonSelected){
return false;
}
return true;
}
That will work it if any other button was clicked. but you have to do that in your onClick
mButtonSelected = position;
notifyDataSetChanged();
Let me it worked or not
EDIT
see below changes in your code-:
public class SelectStnListByRoute extends BaseAdapter {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
private SQLiteDB sqLiteDB;
int mArrivalSelected = -1;
int mDepartSelected = -1;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
sqLiteDB = new SQLiteDB(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if (position <= mArrivalSelected) {
return false;
}
return true;
}
public boolean isEnabledd(int position) {
if (position <= mDepartSelected) {
return false;
}
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
if (!isEnabled(position)) {
if (position <= mArrivalSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
if (position < mArrivalSelected) {
viewHolder.txtStnDep.setEnabled(false);
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
}
}
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mArrivalSelected = position;
arrivalClick(view);
notifyDataSetChanged();
}
});
if (!isEnabledd(position)) {
if (position <= mDepartSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
viewHolder.txtStnDep.setEnabled(false);
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
}
viewHolder.txtStnDep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mDepartSelected = position;
departureClick(view);
notifyDataSetChanged();
}
});
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
StnNames pos;
int ref;
}
public void arrivalClick(View view) {
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
int stnId = listItemsArrr.getStnId();
String arrClick = "arrival";
String upSideKm = listItemsArrr.getStnUpsideKm();
String downsideKm = listItemsArrr.getStnDownSideKm();
String arrTime = getCurrentTime();
/* sqLiteDB.open();
*//* long abc = sqLiteDB.insertJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick);*//*
*//* long abcd = sqLiteDB.updateJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick,downsideKm,upSideKm);
Log.e("arrclick",String.valueOf(abcd));*//*
sqLiteDB.close();*/
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
}
public void departureClick(View view) {
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
String depTime = getCurrentTime();
int stnId = listItemsDepp.getStnId();
String depClick = "departure";
String upSideKm = listItemsDepp.getStnUpsideKm();
String downsideKm = listItemsDepp.getStnDownSideKm();
sqLiteDB.open();
/*long abc = sqLiteDB.insertJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick);*/
/*long abcd = sqLiteDB.updateJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick,downsideKm,upSideKm);
Log.e("depclick",String.valueOf(abcd));*/
sqLiteDB.close();
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
}
public String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
Get the position of the row which is clicked and then set onclick false for positions less than clicked position
as follows:
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position));
for (int i = 0; i < position; i++) {
viewHolder.txtStnArr.setEnable(false);
}
notifyDataSetChanged();
}
});

Show Image in listview, if file specific file is downloaded internal storage

I am working on a project. In my project when user clicks on a list item, it downloads a file from some source and saves it into internal storage.
I want to show an image in list items of listview if file is already download.
The code below is working fine but it is also showing image for the list items whose file is yet not downloaded.
Here is my adapter class code.
package life.quran.com.quranlife;
public class SurahBaseSearchAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflator;
private List<Surah> surahList = null;
private ArrayList<Surah> arrayList;
Surah surah;
ArrayList<String> imgfileLocation = null;
String searchhighlightString = "";
public SurahBaseSearchAdapter(Context context, List<Surah> list) {
mContext = context;
surahList = list;
mInflator = LayoutInflater.from(context);
arrayList = new ArrayList<Surah>();
arrayList.addAll(surahList);
}
public class ViewHolder {
TextView sname;
TextView sno;
ImageView dlimg;
}
#Override
public int getCount() {
return surahList.size();
}
#Override
public Object getItem(int position) {
return surahList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
imgfileLocation = new ArrayList<>();
surah = surahList.get(position);
File f = mContext.getFilesDir();
String filepath = f.getAbsolutePath();
File _file = new File(filepath+"/surah_"+surah.getSurah_id()+".json");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflator.inflate(R.layout.item_template,null);
holder.sname = (TextView) convertView.findViewById(R.id.txt_surahName);
holder.sno = (TextView) convertView.findViewById(R.id.txtsuraNo);
holder.dlimg = convertView.findViewById(R.id.dlimg);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.sname.setText(surah.getSurah_name());
holder.sno.setText(surah.getSurah_no());
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
}
String hSurahName = surah.getSurah_name().toLowerCase(Locale.getDefault());
if(hSurahName.contains(searchhighlightString)) {
int startpos = hSurahName.indexOf(searchhighlightString);
int endpos = startpos + searchhighlightString.length();
Spannable spanText = Spannable.Factory.getInstance().newSpannable(holder.sname.getText());
spanText.setSpan(new ForegroundColorSpan(Color.BLUE),startpos,endpos,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.sname.setText(spanText,TextView.BufferType.SPANNABLE);
}
return convertView;
}
public void filter(String charText) {
searchhighlightString = charText;
charText = charText.toLowerCase(Locale.getDefault());
surahList.clear();
if(charText.length() == 0) {
surahList.addAll(arrayList);
} else {
for(Surah surah : arrayList) {
if(surah.getSurah_name().toLowerCase(Locale.getDefault()).contains(charText)) {
surahList.add(surah);
}
}
}
notifyDataSetChanged();
}
}
Let me know if anything is unclear
You require to set default drawable if file not exist condition. Add else part to this if condition like
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
}else{
holder.dlimg.setImageResource(R.drawable.<default_image>);
}
You should clear image in ViewHolder after previous usage. Just change your code to something like this:
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
} else {
//clear image from previous usage
//do not sure is it legal to set null. You need to check it.
holder.dlimg.setImageResource(null)
}

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.

Categories

Resources