I am using on scroll to load more data and show them in list view but my ListView first shows already loaded data then adds the newly added data to ListView
I have used for reference this and many others but unable to solve the issue
Here is my activity class
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
ButterKnife.bind(this);
Users = Users.getCurrentUser(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
UIUtility.setStatusColor(this);
Intent intent = getIntent();
try {
entityData = new JSONArray(intent.getStringExtra(EXTRA_DATA));
} catch (JSONException e) {
e.printStackTrace();
}
viewAllCategory = intent.getIntExtra(EXTRA_CATEGORY, 0);
viewAllEntityType = intent.getIntExtra(EXTRA_TYPE, 0);
latitude = intent.getDoubleExtra(EXTRA_LATITUDE, 0);
longitude = intent.getDoubleExtra(EXTRA_LONGITUDE, 0);
setTitle(TITLES[viewAllCategory]);
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser = new ViewAllUserAdapter(this, users);
lvEntity.setAdapter(adapterUser);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook = new ViewAllBookAdapter(this, books);
lvEntity.setAdapter(adapterBook);
}
lvEntity.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!stopLoadingMore) {
if (totalItemCount == firstVisibleItem + visibleItemCount && !isLoading) {
isLoading = true;
showLoading();
loadMoreData();
}
}
}
});
}
private void loadMoreData() {
String loadMoreUrl = buildLoadMoreUrl();
ShareMyBookHttpClient client = new ShareMyBookHttpClient();
client.get(loadMoreUrl, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
hideLoading();
if (responseBody != null) {
start = start+20;
try {
JSONObject jo = new JSONObject(new String(responseBody));
if (!jo.getBoolean(Constants.JsonKeys.ERROR)) {
JSONArray data = jo.getJSONArray(Constants.JsonKeys.DATA);
if (data.length() == 0) {
stopLoadingMore = true;
return;
}
if (data.length() < 20) {
stopLoadingMore = true;
}
for (int i = 0; i < data.length(); i++) {
entityData.put(data.getJSONObject(i));
}
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser.mergeArray(users);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook.mergeArray(books);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
hideLoading();
}
});
}
private String buildLoadMoreUrl() {
switch (viewAllCategory) {
default:
case ViewAllCategory.CATEGORY_USER:
return Constants.createUrlToGetViewAllUsers(Users.getId(), latitude, longitude, Users.getAuthToken(), start, LIMIT);
case ViewAllCategory.CATEGORY_MY_BOOKS:
return Constants.createUrlToGetViewAllMyBooks(Users.getId(), Users.getAuthToken(), start, LIMIT);
}
}
private void showLoading() {
sbLoading = Snackbar.make(coolMain, R.string.view_all_loading, Snackbar.LENGTH_INDEFINITE);
sbLoading.show();
}
private void hideLoading() {
isLoading = false;
if (sbLoading != null) {
sbLoading.dismiss();
}
}
and following is my AdapterClasss
public class ViewAllUserAdapter extends BaseAdapter {
private List<Users> users;
private Context context;
public ViewAllUserAdapter(Context context, List<Users> usersData) {
this.context = context;
users = usersData;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
}
return row;
}
#Override
public int getCount() {
return users == null ? 0 : users.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
public class UserVH extends View {
#Bind(R.id.item_vau_iv_user_image)
ImageView ivUserImage;
#Bind(R.id.item_vau_tv_name)
TextView tvName;
#Bind(R.id.item_vau_tv_distance)
TextView tvDistance;
private int position;
public UserVH(View view, final int position) {
super(context);
this.position = position;
ButterKnife.bind(this, view);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
UIUtility.openUserDetailActivity(context, users.get(position));
}
});
}
}
}
As you already referred this link, Exactly the same issue is happening with you, You should have correct implementation for holder class in getView method.
Update your getView() method as per below :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();
}
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
return row;
}
And update your getItemId and getItem methods as per below :
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
EDIT : clear the list additional users before adding the new objects
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
// Following line to be added
additonalusers.clear();
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
Your implementation of following methods is incorrect.
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
Change them as below
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
Related
There is adapter set to Station(Name/Code) AutocompleteTextView. First time whole list is setting. After that If I filter for ch, It will display all filtered Items.
And Now If i remove ch, It will display whole list. Here there is no problem.
But Now If click back button or navigate tot other screen and coming to this screen again, there is only filtered Items are displaying(which are starts with ch).
Why only filtered Items are showing?
Please help me.
This is very important for my project.
I tried many solutions on google. But not got the output.
Any help would be appreciated.
This is my custom Adapter:
public class CustomAdapter extends ArrayAdapter {
private final Context mContext;
private ArrayList<TextItem> textObjects;
private ArrayList<TextItem> textObjects_All;
private final int mLayoutResourceId;
View rowView;
private LayoutInflater inflater;
public CustomAdapter(Context mContext, int resource, ArrayList<TextItem> AObjects) {
super(mContext, resource, AObjects);
this.mContext = mContext;
mLayoutResourceId = resource;
setTextObjects(AObjects);
}
public void setTextObjects(ArrayList<TextItem> AObjects) {
try {
textObjects = AObjects;
textObjects_All = new ArrayList<>();
synchronized (this) {
textObjects_All.addAll(AObjects);
}
}catch (Exception e){
Log.d("eEmp/setTextObj", "Expt due to " + e.toString());
}
}
public int getCount() {
return textObjects.size();
}
public TextItem getItem(int position) {
return textObjects.get(position);
//return (textObjects != null ? textObjects.get(position) : "");
}
public long getItemId(int position) {
return position;
}
public void addTextObject(TextItem newItem) {
try {
if ((textObjects_All != null) && (!textObjects_All.contains(newItem))) {
textObjects_All.add(newItem);
}
} catch (Exception expt) {
Log.d("eEmp/setTextObj", "Expt due to " + expt.toString());
}
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
try {
rowView = convertView;
if (rowView == null){
inflater = LayoutInflater.from(mContext);
rowView = inflater.inflate(mLayoutResourceId, parent, false);
}
TextItem selectedItem = (TextItem) getItem(position);
TextView txtHeaderObject = (TextView) rowView.findViewById(R.id.tvHeaderItem);
txtHeaderObject.setText(selectedItem.headItemName);
TextView txtSubItem1Object = (TextView) rowView.findViewById(R.id.tvSub1Item);
if (txtSubItem1Object != null) {
txtSubItem1Object.setText(selectedItem.subItem1Name);
}
TextView txtSubItem2Object = (TextView) rowView.findViewById(R.id.tvSub2Item);
if (txtSubItem2Object != null) {
txtSubItem2Object.setText(selectedItem.subItem2Name);
}
ViewGroup.LayoutParams params = rowView.getLayoutParams();
return rowView;
} catch (Exception e) {
Log.e("/eEmp","/Convert View Exception"+e.toString());
e.printStackTrace();
}
return rowView;
}
private static class ViewHolder{
TextView Header;
TextView SubItem1;
TextView SubItem2;
}
#NonNull
#Override
public Filter getFilter() {
return new Filter() {
#Override
public CharSequence convertResultToString(Object resultValue) {
return ((TextItem) resultValue).headItemName;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {FilterResults filterResults = new FilterResults();
try {
if ((constraint == null) || (constraint.length() == 0)) {
synchronized (this) {
filterResults.values = textObjects_All;
filterResults.count = textObjects_All.size();
}
} else {
ArrayList<TextItem> textObjectsFiltered = new ArrayList<TextItem>();
for (TextItem obj : textObjects_All) {
TextItem itemObj = obj;
if (itemObj != null) {
if ((itemObj.headItemName != null) && (itemObj.headItemName.length() != 0)
&& (itemObj.headItemName.toLowerCase().startsWith(constraint.toString().toLowerCase()))) {
textObjectsFiltered.add(obj);
}
}
}
filterResults.values = textObjectsFiltered;
filterResults.count = textObjectsFiltered.size();
}
} catch (Exception expt) {
Log.d("eEmp/FilterResults", "Exception Occurred due to " + expt.toString());
}
return filterResults;
}
#SuppressWarnings("SingleStatementInBlock")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
try{
textObjects.clear();
if (results != null && results.count > 0) {
ArrayList<?> result = (ArrayList<?>) results.values;
for (Object object : result) {
if (object instanceof TextItem) {
textObjects.add((TextItem) object);
}
}
}
notifyDataSetChanged();
}catch (Exception expt) {
Log.d("eEmp/publishResults", "Exception Occurred due to " + expt.toString());
}
}
};
}
}
AutoCompleteTextWatcher.java
public class AutoCompleteTextWatcher implements TextWatcher {
private CustomAutoCompleteTextView currATV;
public AutoCompleteTextWatcher(CustomAutoCompleteTextView tv)
{
currATV = tv;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(currATV != null)
{
currATV.setTextItemTag(null);
}
}
}
atcvDivName is my AutoCompleteTextView
Activity
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.entry_fab_activity, container, false);
try {
Inst_Act_List_works_entry = new ArrayList<>();//added by pavani
status_pojo = new Status_POJO();
edtFromDate = (EditText) rootView.findViewById(R.id.edtFromDate);
edtFromDate.setText(getTodayDates()); // Added in V 1.3 by Shamili
// Get Available WorkTypes
WorkTypes = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.WorkTypes)));
actvDivName.addTextChangedListener(textWatcher());
//set event for clear button
btnClear_stn.setOnClickListener(onClickListener());
actvEntryCategory.addTextChangedListener(textWatcher_Entry());
btn_clear_EntryType.setOnClickListener(onClickListener());
btn_clear_Product.setOnClickListener(onClickListener());
actvPType.addTextChangedListener(textWatcher_Product());
cd_leaves.setVisibility(View.GONE);
if (stn_fal_falg == 1) {
btnClear_stn.setVisibility(View.GONE);
btn_clear_EntryType.setVisibility(View.GONE);
btn_clear_Product.setVisibility(View.GONE);
} else {
btnClear_stn.setVisibility(View.VISIBLE);
btn_clear_EntryType.setVisibility(View.VISIBLE);
btn_clear_Product.setVisibility(View.VISIBLE);
}
try {
WorksList = dbHandler.getWorkTypes();
for (String newWorkType : WorksList) {
if (!WorkTypes.contains(newWorkType)) {
WorkTypes.add(newWorkType);
}
}
} catch (Exception getWorkExp) {
}
EntryTypeAdapter = new CustomArrayAdapter(getActivity(), R.layout.autocomplete_text_layout, WorkTypes);
actvEntryCategory.setAdapter(EntryTypeAdapter);
actvEntryCategory.setThreshold(0);
Rlys = new ArrayList<Rly>();
try {
DivStnList = mContext.StnsPlacesList;
for (int i = 0; i < DivStnList.size(); i++) {
QRDivTextItemList = mContext.StnsPlacesList;
DivIDsList.add(DivStnList.get(i).did);
StnIDsList.add(DivStnList.get(i).id);
DivList.add(DivStnList.get(i).subItem2Name);
StnsList.add(DivStnList.get(i).headItemName);
}
} catch (Exception getDivExp) {
}
actvDivName.setThreshold(0);
actvDivName.addTextChangedListener(new AutoCompleteTextWatcher(actvDivName));
actvDivName.setOnItemClickListener(new AutoCompleteItemClickListener<TextItem>(QRDivTextItemList, actvDivName));
QRDivArrayAdapter = new CustomAdapter(mContext, R.layout.autocomplete_text_view, QRDivTextItemList);
actvDivName.setAdapter(QRDivArrayAdapter);
actvDivName.setCustomAutoCompleteTextViewListener(new CustomAutoCompleteTextView.CustomAutoCompleteTextViewListener() {
#Override
public void onItemSelected() {
try {
TextItem selectedItem = (TextItem) actvDivName.getTag();
InstRecyclerclear();
FailureRecyclerclear();
GeneralRecyclerclear();
actvPType.setText("");
ProdsItemList.clear();
actvDivName.setVisibility(View.VISIBLE);
actvPType.setVisibility(View.INVISIBLE);
cdAmc_entry.setVisibility(View.GONE);
trAMC.setVisibility(View.GONE);
if (selectedItem != null) {
instProd = (List<InstProd>) selectedItem.childObject;
for (int i = 0; i < instProd.size(); i++) {
TextItem item = new TextItem();
stn_pla_id = selectedItem.id;
item.headItemName = instProd.get(i).IName;
item.subItem1Name = instProd.get(i).MName;//String.valueOf(instProd.get(i).PID);
item.subItem2Name = instProd.get(i).NAME;//String.valueOf(instProd.get(i).IID);
item.id = instProd.get(i).PID;
item.did = instProd.get(i).IID;
prod_ID = instProd.get(i).PID;
ProdsItemList.add(item);
actvPType.setVisibility(View.VISIBLE);
actvPType.setEnabled(true);
}
}
QRProdArrayAdapter.setTextObjects(ProdsItemList);
} catch (Exception e) {
}
}
});
QRProdArrayAdapter = new CustomAdapter(mContext, R.layout.autocomplete_text_view, ProdsItemList);//added by pavani
actvPType.setAdapter(QRProdArrayAdapter);//added by pavani
actvPType.setThreshold(0);
actvPType.addTextChangedListener(new AutoCompleteTextWatcher(actvPType));
actvPType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
InstRecyclerclear();
FailureRecyclerclear();
GeneralRecyclerclear();
cdAmc_entry.setVisibility(View.GONE);
trAMC.setVisibility(View.GONE);
val = position;
iid = ProdsItemList.get(position).did;//Integer.parseInt(ProdsItemList.get(position).subItem2Name);
pid = ProdsItemList.get(position).id;//Integer.parseInt(ProdsItemList.get(position).subItem1Name);
station = ProdsItemList.get(position).headItemName;
product = ProdsItemList.get(position).subItem1Name;
} catch (Exception e) {
Log.d("eEmp/OnProdClick", "Exception Occurred due to " + e.toString());
}
}
});
actvDivName.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
entryFragment = (Entry_Fragment)
getFragmentManager().findFragmentByTag(EmpConstants.Entry_Info_Tag);
//set Station Name
if (StnIDFromAdapter != null) {
try {
long id = Long.parseLong(StnIDFromAdapter);
stn_pla_id = id;
for (int i = 0; i < DivStnList.size(); i++) {
if (id == DivStnList.get(i).id) {
actvDivName.setText(DivStnList.get(i).headItemName);
actvDivName.setEnabled(false);
}
}
} catch (Exception expt) {
}
}
//setting Product Name
if (ProdFromAdapter != null) {
try {
pid = ProdIdFromAdapter;
iid = ProdSno;
actvPType.setVisibility(View.VISIBLE);
actvPType.setText(ProdFromAdapter);
actvPType.setEnabled(false);
} catch (Exception expt) {
}
}
} catch (Exception expt) {
Log.d("eEmp/EntryCreate", "Exception Occurred due to " + expt.toString());
}
return rootView;
}
private TextWatcher textWatcher() {
return new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
if (!actvDivName.getText().toString().equals("")) {
btnClear_stn.setVisibility(View.VISIBLE);
} else {
}
} catch (Exception e) {
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
};
}
}
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();
}
});
I am having trouble when I open activity from one activity, and when I press back button of the phone the app crashes. Here I have described all details of activity and fragment.
FeedFragment.java
public class FeedFragment extends BaseFragment {
ListView lvFeeds;
TextView tvNoRecord;
public static Handler[] handler;
public static Runnable[] animateViewPager;
static Handler bannerHandler;
static Runnable bannerRunnable;
boolean stopSliding = false;
boolean isLastItemLoaded = false;
FeedAdapter feedAdapter;
ArrayList<FeedBean> feedList = new ArrayList<>();
int[] bannerImages = new int[]{
R.drawable.ic_feed_one,
R.drawable.ic_feed_two,
R.drawable.ic_feed_three,
R.drawable.ic_feed_four,
R.drawable.ic_feed_five
};
String articleId;
static int position = 0;
#SuppressLint("NewApi")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
lvFeeds = (ListView) view.findViewById(R.id.lvFeeds);
tvNoRecord = (TextView) view.findViewById(R.id.tvNoRecord);
LayoutInflater mInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View headerView = mInflater.inflate(R.layout.feed_banner_view, null);
CirclePageIndicator cpiBanner = (CirclePageIndicator) headerView.findViewById(R.id.indicators);
final JazzyViewPager vpFeedBanner = (JazzyViewPager) headerView.findViewById(R.id.vpFeeds);
vpFeedBanner.setTransitionEffect(JazzyViewPager.TransitionEffect.Accordion);
BannerAdapter pagerAdapter = new BannerAdapter(vpFeedBanner);
vpFeedBanner.setAdapter(pagerAdapter);
cpiBanner.setViewPager(vpFeedBanner);
cpiBanner.setCurrentItem(vpFeedBanner.getCurrentItem());
lvFeeds.addHeaderView(headerView);
listFeed();
bannerHandler = new Handler();
bannerRunnable = new Runnable() {
public void run() {
try {
if (position >= bannerImages.length - 1) {
vpFeedBanner.setCurrentItem(0);
} else {
vpFeedBanner.setCurrentItem(
vpFeedBanner.getCurrentItem() + 1, true);
}
bannerHandler.postDelayed(bannerRunnable, Constant.VP_ANIMATION_TIME);
} catch (Exception e) {
e.printStackTrace();
}
}
};
return view;
}
#Override
public void onResume() {
super.onResume();
try {
if (!feedList.isEmpty())
setAllSlidingAnimation(feedList.size());
bannerHandler.postDelayed(bannerRunnable, Constant.VP_ANIMATION_TIME);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
try {
if (bannerHandler != null) {
bannerHandler.removeCallbacks(bannerRunnable);
}
if (!feedList.isEmpty())
removeAllSlidingAnimation(feedList.size());
} catch (Exception e) {
e.printStackTrace();
}
}
class BannerAdapter extends PagerAdapter {
JazzyViewPager vpFloor;
LayoutInflater mInflater;
public BannerAdapter(JazzyViewPager viewPager) {
this.vpFloor = viewPager;
mInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
class ViewHolder {
RoundedImageView ivFeed;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(vpFloor.findViewFromObject(position));
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ViewHolder viewHolder = new ViewHolder();
View layout = mInflater.inflate(R.layout.row_feed_view_pager_banner, null);
viewHolder.ivFeed = (RoundedImageView) layout.findViewById(R.id.ivFeed);
try {
BaseActivity.setImageToBanner(getActivity(), bannerImages[position], viewHolder.ivFeed);
viewHolder.ivFeed.setImageDrawable(getResources().getDrawable(bannerImages[position]));
vpFloor.setObjectForPosition(layout, position);
container.addView(layout);
} catch (Exception e) {
e.printStackTrace();
}
return layout;
}
#Override
public int getCount() {
return bannerImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
if (view instanceof OutlineContainer) {
return ((OutlineContainer) view).getChildAt(0) == object;
} else {
return view == object;
}
}
}
void listFeed() {
BaseActivity.showLoader(getActivity());
JSONObject feedObj = null;
RequestQueue queue = Volley.newRequestQueue(getActivity());
final String serverRequest = Constant.WEB_SERVICE_LIST_FEED;
Log.e("", "ListFeed URL : " + serverRequest);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
com.android.volley.Request.Method.POST, serverRequest,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("",
"ListFeed Response : " + response.toString());
JSONObject serverResponse = response
.getJSONObject(Constant.LIST_FEED_ACTION);
String Ws_Status = serverResponse.getString(Constant.TAG_STATUS);
String Ws_Message = serverResponse.getString(Constant.TAG_MESSAGE);
BaseActivity.hideLoader();
if (serverResponse.getString(Constant.TAG_STATUS)
.equalsIgnoreCase(Constant.TAG_STATUS_FAILURE)) {
} else {
feedList.clear();
JSONArray categoriesArray = serverResponse.getJSONArray(Constant.TAG_CATEGORIES);
int categoryLength = categoriesArray.length();
handler = new Handler[categoryLength + 1];
animateViewPager = new Runnable[categoryLength + 1];
for (int i = 0; i < categoriesArray.length(); i++) {
JSONObject categoriesObject = categoriesArray.getJSONObject(i);
FeedBean feedBean = new FeedBean();
feedBean.setId(categoriesObject.getString(Constant.TAG_ID));
feedBean.setName(categoriesObject.getString(Constant.TAG_NAME));
JSONArray articles = categoriesObject.getJSONArray(Constant.TAG_ARTICLES);
ArrayList<ArticleBean> articleList = new ArrayList<>();
for (int j = 0; j < articles.length(); j++) {
JSONObject articlesObject = articles.getJSONObject(j);
ArticleBean articleBean = new ArticleBean();
articleBean.setId(articlesObject.getString(Constant.TAG_ID));
articleBean.setTitle(articlesObject.getString(Constant.TAG_TITLE));
articleBean.setTimeLapsed(articlesObject.getString(Constant.TAG_TIME_LAPSED));
articleBean.setBody(articlesObject.getString(Constant.TAG_BODY));
articleBean.setArticleUrl(articlesObject.getString(Constant.TAG_ARTICLE_URL));
articleBean.setTags(articlesObject.getString(Constant.TAG_TAGS));
articleBean.setUserId(articlesObject.getString(Constant.TAG_USER_ID));
articleBean.setFeaturedImage(articlesObject.getString(Constant.TAG_FEATURED_IMAGE));
articleBean.setLikeCounter(articlesObject.getString(Constant.TAG_LIKE_COUNTER));
articleBean.setLocation(articlesObject.getString(Constant.TAG_LOCATION));
articleList.add(articleBean);
}
feedBean.articleBeanList = articleList;
int articleLength = articles.length();
feedBean.setArticleLength(articleLength);
feedList.add(feedBean);
}
feedAdapter = new FeedAdapter();
lvFeeds.setAdapter(feedAdapter);
removeAllSlidingAnimation(feedList.size());
setAllSlidingAnimation(feedList.size());
}
} catch (Exception e) {
BaseActivity.hideLoader();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
BaseActivity.hideLoader();
e.printStackTrace();
}
});
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(Constant.WEB_SERVICE_TIME_OUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsObjRequest);
}
void removeAllSlidingAnimation(int length) {
try {
for (int i = 0; i < length; i++) {
if (handler[i] != null) {
handler[i].removeCallbacks(animateViewPager[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
void setAllSlidingAnimation(int length) {
try {
for (int i = 0; i < length; i++) {
if (handler[i] != null) {
handler[i].postDelayed(animateViewPager[i], Constant.VP_ANIMATION_TIME);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void runnable(final int size, final JazzyViewPager mViewPager, final int position) {
try {
handler[position] = new Handler();
animateViewPager[position] = new Runnable() {
public void run() {
if (!stopSliding) {
if (mViewPager.getCurrentItem() == size - 1) {
mViewPager.setCurrentItem(0);
} else {
mViewPager.setCurrentItem(
mViewPager.getCurrentItem() + 1, true);
}
try {
handler[position].postDelayed(animateViewPager[position], Constant.VP_ANIMATION_TIME);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
};
} catch (Exception e) {
e.printStackTrace();
}
}
class FeedAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
public FeedAdapter() {
inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return feedList.size();
}
#Override
public Object getItem(int position) {
return feedList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View itemView = convertView;
ViewHolder viewHolder = null;
if (convertView == null) {
itemView = inflater.inflate(R.layout.row_feed, null);
viewHolder = new ViewHolder();
viewHolder.llFeed = (LinearLayout) itemView.findViewById(R.id.llFeed);
viewHolder.vpFeeds = (JazzyViewPager) itemView.findViewById(R.id.vpFeeds);
viewHolder.indicators = (CirclePageIndicator) itemView.findViewById(R.id.indicators);
viewHolder.tvFeedTitle = (TextView) itemView.findViewById(R.id.tvFeedTitle);
viewHolder.tvFeedSubTitle = (TextView) itemView.findViewById(R.id.tvFeedSubTitle);
viewHolder.tvFeedTime = (TextView) itemView.findViewById(R.id.tvFeedTime);
viewHolder.tvCategoryName = (TextView) itemView.findViewById(R.id.tvCategoryName);
viewHolder.vpFeeds.setTransitionEffect(JazzyViewPager.TransitionEffect.Accordion);
itemView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) itemView.getTag();
}
try {
FeedBean bean = feedList.get(i);
FeedPagerAdapter pagerAdapter = new FeedPagerAdapter(viewHolder.vpFeeds, viewHolder.tvFeedTitle, viewHolder.tvFeedSubTitle, viewHolder.tvFeedTime, bean, viewHolder.llFeed, viewHolder.indicators);
viewHolder.vpFeeds.setAdapter(pagerAdapter);
viewHolder.indicators.setViewPager(viewHolder.vpFeeds);
viewHolder.indicators.setCurrentItem(viewHolder.vpFeeds.getCurrentItem());
viewHolder.tvCategoryName.setText(bean.getName().toUpperCase().trim());
if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_FEATURED)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_yellow));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_ORIGINAL)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_purple));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_MUSIC)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_pink));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_GIVE)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightGreen));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_LIFESTYLE)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_parrot));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_INSPIRATION)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightRed));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_TECH)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_lightBlack));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_FASHION)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightBlue));
} else {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_pink));
}
runnable(bean.getArticleLength(), viewHolder.vpFeeds, i);
if (i != 0)
if ((i + 1) % 2 == 0) {
if (!isLastItemLoaded) {
removeAllSlidingAnimation(i);
setAllSlidingAnimation(i);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return itemView;
}
class ViewHolder {
JazzyViewPager vpFeeds;
TextView tvFeedTitle, tvFeedSubTitle, tvFeedTime, tvCategoryName;
CirclePageIndicator indicators;
LinearLayout llFeed;
}
}
class FeedPagerAdapter extends PagerAdapter {
JazzyViewPager vpFloor;
private LayoutInflater mInflater;
TextView tvFeedTitle, tvFeedSubTitle, tvFeedTime;
FeedBean bean;
LinearLayout llFeed;
CirclePageIndicator indicators;
public FeedPagerAdapter(JazzyViewPager vpFloor, TextView tvFeedTitle, TextView tvFeedSubTitle, TextView tvFeedTime, FeedBean bean, LinearLayout llFeed, CirclePageIndicator indicators) {
this.vpFloor = vpFloor;
mInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.tvFeedTitle = tvFeedTitle;
this.tvFeedTime = tvFeedTime;
this.tvFeedSubTitle = tvFeedSubTitle;
this.bean = bean;
this.llFeed = llFeed;
this.indicators = indicators;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(vpFloor.findViewFromObject(position));
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ViewHolder viewHolder = new ViewHolder();
View layout = mInflater.inflate(R.layout.row_feed_view_pager, null);
viewHolder.ivFeed = (RoundedImageView) layout.findViewById(R.id.ivFeed);
try {
BaseActivity.setImageToView(getActivity(), bean.articleBeanList.get(position).getFeaturedImage(), viewHolder.ivFeed);
} catch (Exception e) {
e.printStackTrace();
}
llFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (bean.articleBeanList.size() == 1) {
openDetailActivity(bean.articleBeanList.get(position).getId());
} else {
openDetailActivity(bean.articleBeanList.get(position).getId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
vpFloor.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
try {
tvFeedTitle.setText(bean.articleBeanList.get(position).getTitle().toUpperCase());
tvFeedSubTitle.setText(bean.articleBeanList.get(position).getBody().toUpperCase());
tvFeedTime.setText(bean.articleBeanList.get(position).getTimeLapsed().toUpperCase());
articleId = bean.articleBeanList.get(position).getId();
indicators.setCurrentItem(position);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (bean.articleBeanList.size() == 1) {
openDetailActivity(bean.articleBeanList.get(position).getId());
} else {
openDetailActivity(bean.articleBeanList.get(position).getId());
}
} catch (Exception e) {
}
}
});
try {
vpFloor.setObjectForPosition(layout, position);
tvFeedTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTitle().toUpperCase());
tvFeedTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTitle().toUpperCase());
tvFeedSubTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getBody().toUpperCase());
tvFeedTime.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTimeLapsed().toUpperCase());
articleId = bean.articleBeanList.get(vpFloor.getCurrentItem()).getId();
} catch (Exception e) {
e.printStackTrace();
}
container.addView(layout);
return layout;
}
class ViewHolder {
RoundedImageView ivFeed;
}
#Override
public int getCount() {
return bean.getArticleLength();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
if (view instanceof OutlineContainer) {
return ((OutlineContainer) view).getChildAt(0) == obj;
} else {
return view == obj;
}
}
}
void openDetailActivity(String articleId) {
startActivity(new Intent(DashboardActivity.context, StoriesDetailsActivity.class).putExtra(Constant.TAG_ID, articleId));
}
}
Logcat
FATAL EXCEPTION: main
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: Process: com.cultureapp, PID: 19925
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:308)
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: at android.widget.HeaderViewListAdapter.isEnabled(HeaderViewListAdapter.java:164)
In your code, your are calling something like list.get(1) but list size is 1. So, you can only call list.get(0). You are trying to reach to the non-existence objects.
The java.lang.IndexOutOfBoundsException means:
You have an ArrayList which has 1 element so you can only get the element at position 0.
But here, you're trying to access to the element at position 1 which is impossible because it does not exists.
The problem is probably here:
#Override
public void onResume() {
super.onResume();
try {
if (!feedList.isEmpty())
setAllSlidingAnimation(feedList.size());
...
}
If the size of feedList is 1, you will try to access to the SECOND element (first is at position 0, second is at position 1 == feedList.size()).
Hi,
I try to refresh my data with a tweet app which I am making. When I delete a following person by cliking on the button "following_del", I want that my list view being refreshed without the user I just deleted. Do you have any idea do to this? I am in a baseAdaptor class. Thanks
public class UsersAdapter extends BaseAdapter implements DialogInterface.OnShowListener {
private List<User> mUsers;
Integer BUTTON_ACTIVATE = 0;
public List<User> getUsers() {
return mUsers;
}
public Context context;
public void setUsers(List<User> users) {
mUsers = users;
}
public UsersAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return mUsers != null ? mUsers.size() : 0;
}
#Override
public User getItem(int position) {
return mUsers.get(position);
}
#Override
public long getItemId(int position) {
// if (getItem(position).getId() == null) {
return 0;
// } else {
// return getItem(position).getId().hashCode();
// }
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.follower_item, parent, false);
BUTTON_ACTIVATE = 0;
}
final User user = getItem(position);
TextView handleView = (TextView) convertView.findViewById(R.id.handle);
handleView.setText(user.getHandle());
TextView statusView = (TextView) convertView.findViewById(R.id.status);
Log.i(context.getClass().getName(), "Je suis dans ce context2");
ImageButton button_del = (ImageButton) convertView.findViewById(R.id.add_following);
button_del.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (AccountManager.isConnected(context)) {
new AsyncTask<String, Void, Integer>() {
#Override
protected Integer doInBackground(String... arg) {
try {
String handle = AccountManager.getUserHandle(context);
String token = AccountManager.getUserToken(context);
String content = user.getHandle();
if (handle.compareTo(content) != 0) {
new ApiClient().postdelFollowing(handle, token, content);
return 1;
}
} catch (IOException e) {
return 0;
}
}
#Override
protected void onPostExecute(Integer success) {
if (success == 1) {
Toast.makeText(context, "Vous ne suivez plus " + user.getHandle(), Toast.LENGTH_SHORT).show();
if (context.getClass().getName().compareTo(FollowingActivity.class.getName()) == 0) {
Intent intent = new Intent(context, FollowingActivity.class);
intent.putExtras(FollowingFragment.newArgument(UsersFragment.user));
context.startActivity(intent);
}
} else {
Toast.makeText(context, "Une erreur s'est produite", Toast.LENGTH_SHORT).show();
}
}
}.execute();
} else {
new AlertDialog.Builder(context)
.setMessage("Veuillez vous connecter")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
});
return convertView;
}
}
I use component android-section-list (http://code.google.com/p/android-section-list/) to create sections in my listView. How can I hide sections after push some button?
I try to do like
public void onClick(View v) {
switch(v.getId()) {
case R.id.sortTitle:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.market_list_separator, null, false);
TextView separatorLayout = (TextView) convertView.findViewById(R.id.section_view);
separatorLayout.setVisibility(View.GONE);
sectionAdapter.notifyDataSetChanged();
setButtonState(sortByTitle);
adapter.sort((Comparator<SectionListItem>) sortByTitle());
break;
}
}
But this way don't work.
My adapter put data in list rows and SectionListAdapter draw sections.
public class SectionListAdapter extends BaseAdapter implements ListAdapter,
OnItemClickListener {
private final DataSetObserver dataSetObserver = new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
updateSessionCache();
}
#Override
public void onInvalidated() {
super.onInvalidated();
updateSessionCache();
};
};
private final ListAdapter linkedAdapter;
private final Map<Integer, String> sectionPositions = new LinkedHashMap<Integer, String>();
private final Map<Integer, Integer> itemPositions = new LinkedHashMap<Integer, Integer>();
private final Map<View, String> currentViewSections = new HashMap<View, String>();
private int viewTypeCount;
protected final LayoutInflater inflater;
private View transparentSectionView;
private OnItemClickListener linkedListener;
public SectionListAdapter(final LayoutInflater inflater,
final ListAdapter linkedAdapter) {
this.linkedAdapter = linkedAdapter;
this.inflater = inflater;
linkedAdapter.registerDataSetObserver(dataSetObserver);
updateSessionCache();
}
private boolean isTheSame(final String previousSection,
final String newSection) {
if (previousSection == null) {
return newSection == null;
} else {
return previousSection.equals(newSection);
}
}
private synchronized void updateSessionCache() {
int currentPosition = 0;
sectionPositions.clear();
itemPositions.clear();
viewTypeCount = linkedAdapter.getViewTypeCount() + 1;
String currentSection = null;
final int count = linkedAdapter.getCount();
for (int i = 0; i < count; i++) {
final SectionListItem item = (SectionListItem) linkedAdapter
.getItem(i);
if (!isTheSame(currentSection, item.section)) {
sectionPositions.put(currentPosition, item.section);
currentSection = item.section;
currentPosition++;
}
itemPositions.put(currentPosition, i);
currentPosition++;
}
}
public synchronized int getCount() {
return sectionPositions.size() + itemPositions.size();
}
public synchronized Object getItem(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
final int linkedItemPosition = getLinkedPosition(position);
return linkedAdapter.getItem(linkedItemPosition);
}
}
public synchronized boolean isSection(final int position) {
return sectionPositions.containsKey(position);
}
public synchronized String getSectionName(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
return null;
}
}
public long getItemId(final int position) {
if (isSection(position)) {
return sectionPositions.get(position).hashCode();
} else {
return linkedAdapter.getItemId(getLinkedPosition(position));
}
}
protected Integer getLinkedPosition(final int position) {
return itemPositions.get(position);
}
#Override
public int getItemViewType(final int position) {
if (isSection(position)) {
return viewTypeCount - 1;
}
return linkedAdapter.getItemViewType(getLinkedPosition(position));
}
private View getSectionView(final View convertView, final String section) {
View theView = convertView;
if (theView == null) {
theView = createNewSectionView();
}
setSectionText(section, theView);
replaceSectionViewsInMaps(section, theView);
return theView;
}
protected void setSectionText(final String section, final View sectionView) {
final TextView textView = (TextView) sectionView.findViewById(R.id.listTextView);
textView.setText(section);
}
protected synchronized void replaceSectionViewsInMaps(final String section,
final View theView) {
if (currentViewSections.containsKey(theView)) {
currentViewSections.remove(theView);
}
currentViewSections.put(theView, section);
}
protected View createNewSectionView() {
return inflater.inflate(R.layout.section_view, null);
}
public View getView(final int position, final View convertView,
final ViewGroup parent) {
if (isSection(position)) {
return getSectionView(convertView, sectionPositions.get(position));
}
return linkedAdapter.getView(getLinkedPosition(position), convertView,
parent);
}
#Override
public int getViewTypeCount() {
return viewTypeCount;
}
#Override
public boolean hasStableIds() {
return linkedAdapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return linkedAdapter.isEmpty();
}
#Override
public void registerDataSetObserver(final DataSetObserver observer) {
linkedAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
linkedAdapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return linkedAdapter.areAllItemsEnabled();
}
#Override
public boolean isEnabled(final int position) {
if (isSection(position)) {
return true;
}
return linkedAdapter.isEnabled(getLinkedPosition(position));
}
public void makeSectionInvisibleIfFirstInList(final int firstVisibleItem) {
final String section = getSectionName(firstVisibleItem);
// only make invisible the first section with that name in case there
// are more with the same name
boolean alreadySetFirstSectionIvisible = false;
for (final Entry<View, String> itemView : currentViewSections
.entrySet()) {
if (itemView.getValue().equals(section)
&& !alreadySetFirstSectionIvisible) {
itemView.getKey().setVisibility(View.INVISIBLE);
alreadySetFirstSectionIvisible = true;
} else {
itemView.getKey().setVisibility(View.VISIBLE);
}
}
for (final Entry<Integer, String> entry : sectionPositions.entrySet()) {
if (entry.getKey() > firstVisibleItem + 1) {
break;
}
setSectionText(entry.getValue(), getTransparentSectionView());
}
}
public synchronized View getTransparentSectionView() {
if (transparentSectionView == null) {
transparentSectionView = createNewSectionView();
}
return transparentSectionView;
}
protected void sectionClicked(final String section) {
//
}
public void onItemClick(final AdapterView< ? > parent, final View view,
final int position, final long id) {
if (isSection(position)) {
sectionClicked(getSectionName(position));
} else if (linkedListener != null) {
linkedListener.onItemClick(parent, view,
getLinkedPosition(position), id);
}
}
public void setOnItemClickListener(final OnItemClickListener linkedListener) {
this.linkedListener = linkedListener;
}
}
Where can I put check for visibility in this Adapter?
This works but will be overwritten by the getView() method in the adapter . You must handle this in the adapter bcoz each time view becomes visible on the screen the View is updated so becomes visible in your case.
For the Data you are storing add a Visibility field ( by default keep it visible ) and change the Visibility to GONE in the onClick() method.
if you dont understand , post me your code and will let you know what changes to make.