I have a listview, a row, two text, and one delete button. I can delete item, but sometimes it's deleting a different item, not clicked.
I checked IDs getting correct to the list. I used Retrofit, and I just respond when I clicked the delete button, and I used notifyDataSetChanged(); for list(setFavoriteMerchant())
public class FavoriteMerchantActivity extends AppCompatActivity implements IButtonCliclListener {
FavoriteMerchantAdapter favoriteMerchantAdapter;
#InjectView(R.id.ListFavoriteMerchant)
ListView ListFavoriteMerchant;
AlertDialogHelper alertDialogHelper;
List<ItemsFavoriteMerchant> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_merchant);
ButterKnife.inject(this);
alertDialogHelper = new AlertDialogHelper(this);
getFavoriteMerchant();
}
#Override
public void onClick(View v) {
int itemIndex = (int) v.getTag();
setFavoriteMerchant(itemIndex);
alertDialogHelper.showAlertSuccess("Removed from your favorites!");
}
void getFavoriteMerchant() {
Call<FavoriteMerchant> call = ToolApi.getApi().getFavoriteMerchant(BaseService.TOKEN);
call.enqueue(new Callback<FavoriteMerchant>() {
#Override
public void onResponse(Response<FavoriteMerchant> response, Retrofit retrofit) {
if (response.body() != null) {
FavoriteMerchant favoriteMerchant = response.body();
Integer errorCode = favoriteMerchant.getStatus().getErrorCode();
if (errorCode == 0) {
list = favoriteMerchant.getItems();
favoriteMerchantAdapter = new FavoriteMerchantAdapter(FavoriteMerchantActivity.this, alertDialogHelper, favoriteMerchant, list, getApplicationContext());
ListFavoriteMerchant.setAdapter(favoriteMerchantAdapter);
}
}
else {
startActivity(getIntent());
alertDialogHelper.showAlertError("Connection error...");
}
}
#Override
public void onFailure(Throwable t) {
startActivity(getIntent());
alertDialogHelper.showAlertError("Connection error...");
}
});
}
void setFavoriteMerchant(final int index) {
Call<SetFavoriteMerchant> call = ToolApi.getApi().setFavoriteMerchant(BaseService.TOKEN, index, true);
call.enqueue(new Callback<SetFavoriteMerchant>() {
#Override
public void onResponse(Response<SetFavoriteMerchant> response, Retrofit retrofit) {
for (ItemsFavoriteMerchant item : list) {
if (item.getID() == index) {
list.remove(item);
favoriteMerchantAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onFailure(Throwable t) {
alertDialogHelper.showAlertError("connection error...");
}
});
}
public class FavoriteMerchantAdapter extends BaseAdapter implements View.OnClickListener {
List<ItemsFavoriteMerchant> itemsFavoriteMerchant;
FavoriteMerchant favoriteMerchant;
Context context;
AlertDialogHelper alertDialogHelper;
private IButtonCliclListener iButtonCliclListener;
public FavoriteMerchantAdapter(IButtonCliclListener iButtonCliclListener, AlertDialogHelper alertDialogHelper, FavoriteMerchant favoriteMerchant, List<ItemsFavoriteMerchant> itemsFavoriteMerchant, Context context) {
this.favoriteMerchant = favoriteMerchant;
this.context = context;
this.itemsFavoriteMerchant = itemsFavoriteMerchant;
this.alertDialogHelper = alertDialogHelper;
this.iButtonCliclListener = iButtonCliclListener;
}
#Override
public int getCount() {
return itemsFavoriteMerchant.size();
}
#Override
public Object getItem(int position) {
return itemsFavoriteMerchant.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FavoriteMerchantAdapter.ViewHolder viewHolder;
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchant.get(position);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
viewHolder = new FavoriteMerchantAdapter.ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_favorite_merchant, null);
viewHolder.FavoriteMerchantPlaceDesc = (TextViewGothamBook) convertView.findViewById(R.id.FavoriteMerchantPlaceDesc);
viewHolder.FavoriteMerchantLocationDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantLocationDesc);
viewHolder.FavoriteMerchantCashDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantCashDesc);
viewHolder.FavoriteMerchantDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantDesc);
viewHolder.FavoriteMerchantLogo = (ImageView) convertView.findViewById(R.id.FavoriteMerchantLogo);
viewHolder.FavoriteMerchantDeleteButton = (ImageButton) convertView.findViewById(R.id.im_btn_deletemerchant);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID());
viewHolder.FavoriteMerchantDeleteButton.setOnClickListener(this);
convertView.setTag(item.getID());
//convertView.setTag(viewHolder);
}
else {
viewHolder = (FavoriteMerchantAdapter.ViewHolder) convertView.getTag();
}
/*
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchants.get(position);
*/
String ImageUrl = item.getCoverPageImageURL();
if (ImageUrl != null && !ImageUrl.isEmpty())
Picasso.with(context)
.load(CDnPath + ImageUrl)
.transform(new CircleTransform())
.into(viewHolder.FavoriteMerchantLogo);
String MerchantPlaceDesc = item.getName();
if (MerchantPlaceDesc != null && !MerchantPlaceDesc.isEmpty())
viewHolder.FavoriteMerchantPlaceDesc.setText(MerchantPlaceDesc);
String MerchantocationDesc = (String) item.getDistrict();
if (MerchantocationDesc != null && !MerchantocationDesc.isEmpty())
viewHolder.FavoriteMerchantLocationDesc.setText(MerchantocationDesc);
String MerchantCashDesc = "";
if (MerchantCashDesc != null && !MerchantCashDesc.isEmpty())
viewHolder.FavoriteMerchantCashDesc.setText(MerchantCashDesc);
return convertView;
}
#Override
public void onClick(View v) {
this.iButtonCliclListener.onClick(v);
}
public static class ViewHolder {
ImageView FavoriteMerchantLogo;
TextViewGothamBook FavoriteMerchantPlaceDesc;
TextViewGothamMedium FavoriteMerchantLocationDesc;
TextViewGothamMedium FavoriteMerchantCashDesc;
TextViewGothamMedium FavoriteMerchantDesc;
ImageButton FavoriteMerchantDeleteButton;
}
}
Use:
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
viewHolder = new FavoriteMerchantAdapter.ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_favorite_merchant, null);
viewHolder.FavoriteMerchantPlaceDesc = (TextViewGothamBook) convertView.findViewById(R.id.FavoriteMerchantPlaceDesc);
viewHolder.FavoriteMerchantLocationDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantLocationDesc);
viewHolder.FavoriteMerchantCashDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantCashDesc);
viewHolder.FavoriteMerchantDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantDesc);
viewHolder.FavoriteMerchantLogo = (ImageView) convertView.findViewById(R.id.FavoriteMerchantLogo);
viewHolder.FavoriteMerchantDeleteButton = (ImageButton) convertView.findViewById(R.id.im_btn_deletemerchant);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID());
viewHolder.FavoriteMerchantDeleteButton.setOnClickListener(this);
convertView.setTag(item.getID());
//convertView.setTag(viewHolder);
}
your setting tags only when convert view is null.
convertView.setTag(item.getID()); // This call should be made to all getview calls.
Solution (check comments):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FavoriteMerchantAdapter.ViewHolder viewHolder;
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchant.get(position);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
viewHolder = new FavoriteMerchantAdapter.ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_favorite_merchant, null);
viewHolder.FavoriteMerchantPlaceDesc = (TextViewGothamBook) convertView.findViewById(R.id.FavoriteMerchantPlaceDesc);
viewHolder.FavoriteMerchantLocationDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantLocationDesc);
viewHolder.FavoriteMerchantCashDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantCashDesc);
viewHolder.FavoriteMerchantDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantDesc);
viewHolder.FavoriteMerchantLogo = (ImageView) convertView.findViewById(R.id.FavoriteMerchantLogo);
viewHolder.FavoriteMerchantDeleteButton = (ImageButton) convertView.findViewById(R.id.im_btn_deletemerchant);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID());
viewHolder.FavoriteMerchantDeleteButton.setOnClickListener(this);
//convertView.setTag(item.getID()); // Update
convertView.setTag(viewHolder);
}
else {
viewHolder = (FavoriteMerchantAdapter.ViewHolder) convertView.getTag();
}
/*
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchants.get(position);
*/
String ImageUrl = item.getCoverPageImageURL();
if (ImageUrl != null && !ImageUrl.isEmpty())
Picasso.with(context)
.load(CDnPath + ImageUrl)
.transform(new CircleTransform())
.into(viewHolder.FavoriteMerchantLogo);
String MerchantPlaceDesc = item.getName();
if (MerchantPlaceDesc != null && !MerchantPlaceDesc.isEmpty())
viewHolder.FavoriteMerchantPlaceDesc.setText(MerchantPlaceDesc);
String MerchantocationDesc = (String) item.getDistrict();
if (MerchantocationDesc != null && !MerchantocationDesc.isEmpty())
viewHolder.FavoriteMerchantLocationDesc.setText(MerchantocationDesc);
String MerchantCashDesc = "";
if (MerchantCashDesc != null && !MerchantCashDesc.isEmpty())
viewHolder.FavoriteMerchantCashDesc.setText(MerchantCashDesc);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID()); // check update
return convertView;
}
Related
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 using listview in my application, in that if I will scroll the listview morethan twice app is restarting. How to fix the same.
this is my adapter code :
public class ExpertQAListAdapter extends BaseAdapter {
static class ViewHolder {
public TextView mQuestionTextView;
public TextView mUserNameTextView;
public TextView mQuestionDateTime;
public TextView mAnswerTextView;
public TextView mExpertNameTextView;
public TextView mAnswerDateTime;
public ImageView mExpertImageView;
public ImageView mQuestionaireImageView;
public ImageView mHelpfulImageView;
public ImageView mNonHelpfulImageView;
public TextView mHelpfulTextView;
public RelativeLayout mRelativelayoutForImageDateAndTime;
public String mImageUrl;
}
private LayoutInflater mInflater;
private IWDObjectList mQAItemList;
private ExpertQAListController mExpertQAListController;
private Context mContext;
public ExpertQAListAdapter(Context context, LayoutInflater inflater,
ExpertQAListController expertQAListController) {
mInflater = inflater;
mExpertQAListController = expertQAListController;
mContext = context;
}
public void updateDataSet(IWDObjectList itemList) {
mQAItemList = itemList;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mQAItemList != null ? mQAItemList.Count() : 0;
}
#Override
public AskAnExpertDTO getItem(int position) {
return (AskAnExpertDTO) mQAItemList.GetItem(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.askanexpert_listitem_view_v25, null);
View userBoxView = convertView.findViewById(R.id.askanexpert_relativelayout_for_userbox);
viewHolder.mQuestionTextView = (TextView) userBoxView.findViewById(
R.id.askanexpert_textview_for_content);
viewHolder.mUserNameTextView = (TextView) userBoxView.findViewById(
R.id.askanexpert_textview_for_username);
viewHolder.mQuestionDateTime = (TextView) userBoxView.findViewById(
R.id.askanexpert_textview_for_date);
viewHolder.mQuestionaireImageView = (ImageView) userBoxView.findViewById(
R.id.askanexpert_imageview_for_userpic);
View expertBoxView = convertView.findViewById(
R.id.askanexpert_relativelayout_for_expertbox);
viewHolder.mRelativelayoutForImageDateAndTime=(RelativeLayout)expertBoxView.findViewById(R.id.askanexpert_relativelayout_for_image_date_and_time);
viewHolder.mAnswerTextView = (TextView) expertBoxView.findViewById(
R.id.askanexpert_textview_for_content);
// To make hyper links clickable
viewHolder.mAnswerTextView.setMovementMethod(LinkMovementMethod.getInstance());
viewHolder.mExpertNameTextView = (TextView) expertBoxView.findViewById(
R.id.askanexpert_textview_for_username);
viewHolder.mAnswerDateTime = (TextView) expertBoxView.findViewById(
R.id.askanexpert_textview_for_date);
viewHolder.mExpertImageView = (ImageView) expertBoxView.findViewById(
R.id.askanexpert_imageview_for_userpic);
viewHolder.mHelpfulImageView = (ImageView) expertBoxView.findViewById(
R.id.askanexpert_imageview_for_helpful);
viewHolder.mNonHelpfulImageView = (ImageView) expertBoxView.findViewById(
R.id.askanexpert_imageview_for_nothelpful);
viewHolder.mHelpfulTextView = (TextView) expertBoxView.findViewById(R.id.askanexpert_textview_for_helpful);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.mHelpfulImageView.setSelected(false);
viewHolder.mNonHelpfulImageView.setSelected(false);
viewHolder.mHelpfulImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mExpertQAListController.OnHelpfulIconClick(position);
}
});
viewHolder.mNonHelpfulImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mExpertQAListController.OnNonHelpfulIconClick(position);
}
});
loadQuestionAndAnswer(viewHolder, getItem(position));
if (position == mQAItemList.Count() - 3) {
mExpertQAListController.OnListItemScrollEnd();
}
return convertView;
}
private void loadQuestionAndAnswer(final ViewHolder vh, final AskAnExpertDTO dto) {
IDateTime answerDateTime = null;
IMobilePlatformFactory mpf = MobilePlatformFactoryLocator.GetMobilePlatformFactory();
IFormatDataType formatDataType = MobilePlatformFactoryLocator.GetMobilePlatformFactory()
.CreateFormatDataType();
IDateTime questionDateTime = mpf.CreateDateTime(dto.QuestionDateTimeInMillis);
String questionTime = formatDataType.FormatDateTime(questionDateTime,
StringResource.DATE_MMM_DD_YYYY, null, 0);
vh.mQuestionTextView.setText(dto.Question);
vh.mUserNameTextView.setText(dto.QuestionerName);
vh.mQuestionDateTime.setText(questionTime);
if (dto.Status == QAStatusRequestDTO.STATUS_QA_USEFUL) {
vh.mHelpfulImageView.setSelected(true);
}
if (dto.Status == QAStatusRequestDTO.STATUS_QA_UNUSEFUL) {
vh.mNonHelpfulImageView.setSelected(true);
}
if (dto.Status == QAStatusRequestDTO.STATUS_QA_DEFAULT) {
vh.mNonHelpfulImageView.setSelected(false);
vh.mHelpfulImageView.setSelected(false);
}
String mobileSKey = DataAccessObjectFactoryLocator.getDataAccessObjectFactory()
.getSecurityInformationLookUpDAO().GetMobileSKey();
PatientLookUpDAO patientDao = DataAccessObjectFactoryLocator.getDataAccessObjectFactory()
.getPatientLookUpDAO();
PatientLookUpDTO patientDto = patientDao.Read(mobileSKey, true);
if (dto.QuestionerId == patientDto.PatientId && patientDto.Base64EncodedProfilePicture!=null) {
byte[] profilePicData = formatDataType.DecodeBase64EncodedString(patientDto.Base64EncodedProfilePicture);
Bitmap bitmap = BitmapFactory.decodeByteArray(profilePicData, 0, profilePicData.length);
vh.mQuestionaireImageView.setAdjustViewBounds(true);
vh.mQuestionaireImageView.setImageBitmap(bitmap);
vh.mQuestionaireImageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
else {
vh.mQuestionaireImageView.setImageDrawable(mContext.getResources().getDrawable(
R.drawable.ask_an_expert_profile_pic_male_icon_v25));
}
if (dto.AnswerDateTimeInMillis != 0) {
answerDateTime = mpf.CreateDateTime(dto.AnswerDateTimeInMillis);
}
if (answerDateTime != null) {
if (dto.ExpertId != 0) {
String imageUrl = MobilePlatformFactoryLocator.GetMobilePlatformFactory().GetPortalURL() + "/Service/api/AskAnExpert/GetExpertImage/" + dto.ExpertId;
ImageLoader.loadWithAuth(mContext, vh.mExpertImageView, imageUrl, null);
}
String answerTime = formatDataType.FormatDateTime(answerDateTime, StringResource.DATE_MMM_DD_YYYY, null, 0);
vh.mExpertNameTextView.setText(dto.ExpertName);
vh.mAnswerDateTime.setText(answerTime);
}
else {
vh.mExpertNameTextView.setVisibility(View.GONE);
vh.mAnswerDateTime.setVisibility(View.GONE);
vh.mExpertImageView.setVisibility(View.GONE);
}
if (dto.Answer.equalsIgnoreCase(mContext.getResources().getString(R.string.ExpertQAList_yet_to_be_answered_LBL))){
vh.mNonHelpfulImageView.setVisibility(View.GONE);
vh.mHelpfulImageView.setVisibility(View.GONE);
vh.mHelpfulTextView.setVisibility(View.GONE);
}else {
vh.mNonHelpfulImageView.setVisibility(View.VISIBLE);
vh.mHelpfulImageView.setVisibility(View.VISIBLE);
vh.mHelpfulTextView.setVisibility(View.VISIBLE);
}
vh.mAnswerTextView.setText(Html.fromHtml(dto.Answer));
vh.mRelativelayoutForImageDateAndTime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(mContext,ExpertDescriptionActivity.class);
i.putExtra("ask an expert object",dto);
mContext.startActivity(i);
}
});
}
}
This is my imageLoader class:
public final class ImageLoader {
public static void load(Context context, ImageView view, String url) {
load(context, view, url, null);
}
public static void load(Context context, ImageView view, String url, Callback callback) {
if (TextUtils.isEmpty(url)) {
return;
}
Picasso.with(context)
.load(url)
.fit()
.skipMemoryCache()
.into(view, callback);
}
public static void loadWithAuth(Context context, ImageView view, String url, Callback callback) {
if (TextUtils.isEmpty(url)) {
return;
}
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
SecurityInformationLookUpDAO securityInformationLookUpDAO = CommonDataAccessObjectFactoryLocator
.getCommonDataAccessObjectFactory().getSecurityInformationLookUpDAO();
Request newRequest = chain.request().newBuilder()
.addHeader(HttpHeaderDTO.CUSTOM_HEADER_ACCESS_TOKEN, securityInformationLookUpDAO.ReadAccessToken())
.addHeader(HttpHeaderDTO.CUSTOM_HEADER_CSRF_TOKEN, securityInformationLookUpDAO.ReadCSRFToken())
.build();
return chain.proceed(newRequest);
}
})
.build();
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttp3Downloader(client))
.build();
picasso.load(url).into(view, callback);
}
}
I am getting outofmemory error. please help me to resolve the same.
For example, I need to judge the contents of the item in the Item can be clicked.
enter image description here
As shown in the picture, I need to get the gray Item cannot be clicked.
Here is my adapter
public class RoomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context mContext;
private List<Room> mDatas;
public RoomAdapter(Context context, List<Room> mDatas) {
mInflater = LayoutInflater.from(context);
this.mContext = context;
this.mDatas = mDatas;
}
#Override
public int getCount() {
return mDatas.size();
}
#Override
public Object getItem(int position) {
return mDatas.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Room room = mDatas.get(position);
ViewHolder viewHolder = null;
View view;
if (convertView == null) {
viewHolder = new ViewHolder();
view = mInflater.inflate(R.layout.roomstate_item, null);
viewHolder.tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
viewHolder.tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
viewHolder.tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
viewHolder.tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
view.setTag(viewHolder);
}else{
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
// String nu = room.getRoom_number();
viewHolder.tv_roomstate.setText(room.getRoom_status());
viewHolder.tv_roomnumber.setText(room.getRoom_number());
viewHolder.tv_roomtype.setText(room.getRoomType().getRoom_type_name());
viewHolder.tv_roomprice.setText(room.getRoomType().getRoom_type_price());
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setClickable(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setClickable(false);
view.setBackgroundResource(R.drawable.doubleg);
}
return view;
}
private class ViewHolder {
TextView tv_roomnumber;
TextView tv_roomstate;
TextView tv_roomtype;
TextView tv_roomprice;
}
}
Here is my Activity
public class RoomList extends Activity {
private ImageView iv_back;
private TextView tv_hotelname;
private GridView griv_hotel;
private RoomAdapter adapter;
private String hotelname;
private String url
= "http://jm/user/room/selectRoomByHotelName?hotel_name=";
private List<Room> mRoom;
private RoomType mRoomType;
private boolean isfinish = false;//判断请求是否完成
private String hotel_address;
private String hotel_id;
private Bundle mBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_room_list);
init();
sendRequestWithOkHttp();
boolean is = true;
while (is) {
if (isfinish) {
adapter = new RoomAdapter(this, mRoom);
griv_hotel.setAdapter(adapter);
griv_hotel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
TextView tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
TextView tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
TextView tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
String roomnumber = tv_roomnumber.getText().toString();
String roomstate = tv_roomstate.getText().toString();
String roomtype = tv_roomtype.getText().toString();
String roomprice = tv_roomprice.getText().toString();
Log.e("房间类型",roomtype);
// if (roomstate.equals("0") && roomtype.equals("0")) {
// view.setClickable(false);
// } else if (roomstate.equals("1") && roomtype.equals("0")) {
// view.setClickable(true);
// } else if (roomstate.equals("1") && roomtype.equals("1")) {
// view.setClickable(true);
// } else {
// view.setClickable(false);
// }
mBundle.putString("roomnumber", roomnumber);
mBundle.putString("roomstate", roomstate);
mBundle.putString("roomtype", roomtype);
mBundle.putString("roomprice", roomprice);
mBundle.putString("hoteladdress", hotel_address);
mBundle.putString("hotelid", hotel_id);
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}
});
is = false;
}
}
}
private void init() {
initView();
initEvents();
}
private void initEvents() {
iv_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void initView() {
iv_back = (ImageView) findViewById(R.id.iv_back);
tv_hotelname = (TextView) findViewById(R.id.tv_hotelname);
mBundle = getIntent().getExtras();
hotelname = mBundle.getString("hotelname");
tv_hotelname.setText(hotelname);
griv_hotel = (GridView) findViewById(R.id.griv_hotel);
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
#Override
public void run() {
MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
try {
OkHttpClient client = new OkHttpClient();
String postBody = hotelname;
Request request = new Request.Builder()
.url(url + hotelname)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
try {
parseJSON(responseData);
isfinish = true;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSON(String responseData) throws JSONException {
JSONArray JSONArray = new JSONArray(responseData);
mRoom = new ArrayList<Room>();
for (int i = 0; i < JSONArray.length(); i++) {
try {
JSONObject JSON = JSONArray.getJSONObject(i);
String room_number = JSON.getString("room_number");
String room_status = JSON.getString("room_status");
JSONObject jsonObject = JSON.getJSONObject("roomType");
String room_type_name = jsonObject.getString("room_type_name");
String room_type_price = jsonObject.getString("room_type_price");
JSONObject jsonObj = JSON.getJSONObject("hotel");
hotel_id = String.valueOf(jsonObj.getInt("hotel_id"));
hotel_address = jsonObj.getString("hotel_location");
mRoomType = new RoomType(null, room_type_name, room_type_price, null, null);
mRoom.add(new Room(null, room_number, room_status, null, null, mRoomType));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I set view.setClickable (false)in my Adapter, but it does not work.
item.setEnabled(false);
when u need to make it clickable call
item.setEnabled(true);
Here item is your edittext or button or anything else
Try this:
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setEnabled(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setEnabled(false);
view.setBackgroundResource(R.drawable.doubleg);
}
else
view.setEnabled(true);
The right way is to write a Boolean value, and let it based on a Boolean value to determine whether to jump.
private boolean checkedIntent = false;
if (roomstate.equals("0") && roomtype.equals("0")) {
checkedIntent = false;
} else if (roomstate.equals("1") && roomtype.equals("0")) {
checkedIntent = true;
} else if (roomstate.equals("1") && roomtype.equals("1")) {
checkedIntent = true;
} else if (roomstate.equals("0") && roomtype.equals("1")) {
checkedIntent = false;
}
if (checkedIntent == true) {
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}
Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});
I am setting the adapter of gridview on a fragment. this fragment is attached on the layout of view pager and viewpager is attached in an activity.
I have checked my arraylist data is refreshed but view is not refreshing.
My code is:
Setting the adapter in the onCreate of Activity::
for(ArrayList<Item> newLst : updateList){
newPropertySubList.add(newLst);
}
Log.e("newPropertySubList","newPropertySubList"+newPropertySubList.size());
adapter = new PropertyPagerAdapetr(getSupportFragmentManager());
//propertyViewPager.setAdapter(adapter);
adapter.notifyChangeInPosition(1);
propertyViewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
mIndicator.setViewPager(propertyViewPager);
PropertyPagerAdapetr is: in this code section GridviewFragment new instance is created when adapter is setting.
public class PropertyPagerAdapetr extends FragmentPagerAdapter {
private long baseId = 0;
public PropertyPagerAdapetr(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
return GridViewFragment.newInstance(newPropertySubList.get(arg0));
}
#Override
public long getItemId(int position) {
return baseId + position;
}
public void destroyAllItem(){
getSupportFragmentManager().getFragments().clear();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if (newPropertySubList != null && newPropertySubList.size() > 0)
return newPropertySubList.size();
else
return 0;
}
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
GridViewFragment: Gridview adapter is setting in this fragment
public class GridViewFragment extends Fragment {
public static final String PROPERTY_TYPE = "property_type";
private GridView mImageGrid;
private View view;
ArrayList<Item> itemList;
String forRentOrSale;
double belowheight;
private GridLayout gLayout;
//int count;
//static Context mContext;
public static GridViewFragment newInstance(ArrayList<Item> propertyList) {
GridViewFragment frag = new GridViewFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("Property_item", propertyList);
frag.setArguments(bundle);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.grid_view_fragmnet, container, false);
mImageGrid = (GridView) rootView.findViewById(R.id.gridview);
itemList = (ArrayList<Item>) getArguments().getSerializable(
"Property_item");
LoadPropertyAdapter adapter = new LoadPropertyAdapter(getActivity());
mImageGrid.setAdapter(adapter);
//mImageGrid.setAdapter(new MyAdapter());
return rootView;
//return (view = inflater.inflate(R.layout.grid_view_fragmnet, null));
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
belowheight = (((SearchForm) getActivity()).belowHeight / 2);
initView();
initData();
setListener();
}
private void setListener() {
mImageGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Toast.makeText(getActivity(),
// ""+itemList.get(position).getPID()+" "+itemList.get(position).getA2(),
// Toast.LENGTH_LONG).show();
if (Constants.g_Setttings.getApp_google_analytics() != null
&& !Constants.g_Setttings.getApp_google_analytics().equals("")) {
TVApplication dApp = (TVApplication) getActivity().getApplication();
Tracker tracker = dApp.getTracker(TrackerName.APP_TRACKER,
Constants.g_Setttings.getApp_google_analytics());
tracker.setScreenName("/Search Form");
tracker.set(Fields.SCREEN_NAME, "Search Form");
tracker.send(new HitBuilders.AppViewBuilder().build());
}
Intent intent = new Intent(getActivity(),
PropertyDetailActivity.class);
Item item = itemList.get(position);
intent.putExtra(Constants.ACCESS_DETAIL_PAGE_KEY,
item);
if (((SearchForm) getActivity()).boolSale) {
intent.putExtra(PROPERTY_TYPE, "for sale");
} else if (((SearchForm) getActivity()).boolRent) {
intent.putExtra(PROPERTY_TYPE, "to rent");
} else if (((SearchForm) getActivity()).boolStudentRent) {
intent.putExtra(PROPERTY_TYPE, "to rent");
}
startActivity(intent);
}
});
}
private void initView() {
//mImageGrid = (GridView) view.findViewById(R.id.gridview);
// gLayout=(GridLayout) view.findViewById(R.id.gridlayout);
/*itemList = (ArrayList<Item>) getArguments().getSerializable(
"Property_item");
LoadPropertyAdapter adapter = new LoadPropertyAdapter();
mImageGrid.setAdapter(adapter);*/
}
private void initData() {
if (itemList == null || itemList.size() == 0)
return;
// setUpGridLayout();
/*
* ViewGroup.LayoutParams layoutParams = mImageGrid.getLayoutParams();
* layoutParams.height = (int)
* (((SearchForm)getActivity()).belowHeight/2); //this is in pixels
* mImageGrid.setLayoutParams(layoutParams);
*/
}
}
public class LoadPropertyAdapter extends BaseAdapter {
private Item propertyItem;
Context mContext;
Holder holder = null;
DisplayImageOptions options;
ImageLoader imageLoader;
ImageLoaderConfiguration config;
public LoadPropertyAdapter(FragmentActivity activity) {
mContext = activity;
imageLoader = ImageLoader.getInstance();
config = new ImageLoaderConfiguration.Builder(mContext)
.memoryCache(new WeakMemoryCache())
.denyCacheImageMultipleSizesInMemory()
.threadPoolSize(1)
.build();
options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.resetViewBeforeLoading()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
imageLoader.init(config);
}
#Override
public int getCount() {
if (itemList != null && itemList.size() > 0)
return itemList.size();
else
return 0;
}
#Override
public Object getItem(int arg0) {
return itemList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
public String imageUrl() {
String imageUrl = "";
/*
* if (nm_item.m_bIsAdvert) { imageUrl =
* Constants.advertContainer.getImages_url() + "&file=" +
* Constants.advertContainer.getGen_advert()
* .get(nm_item.m_nIndex).getsca_image(); } else {
*/
imageUrl = Constants.getRequestUrl(propertyItem.getPID(), 1,
Constants.FLOORPLANS_IMAGE_BIG_URL, "");
// }
return imageUrl;
}
public class Holder
{
TextView priceText,content, feesApply, cornerLabel;
ImageView imageview;
RelativeLayout propertyStatusBG, propertyInfoView, layout;
ProgressBar progressbar ;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = null;
propertyItem = itemList.get(position);
if (rowView == null) {
// If convertView is null then inflate the appropriate layout file
rowView = LayoutInflater.from(mContext).inflate( R.layout.grid_view_imageviewitem , null);
holder = new Holder();
rowView.setTag(holder);
}else{
holder = (Holder) rowView.getTag();
}
//rowView = new View(getActivity());
holder.imageview = (ImageView) rowView
.findViewById(R.id.img_property);
holder.priceText = (TextView) rowView
.findViewById(R.id.pricetext);
holder.content = (TextView) rowView
.findViewById(R.id.contenttext);
holder.feesApply = (TextView) rowView
.findViewById(R.id.txt_fees_rent);
holder.propertyStatusBG = (RelativeLayout) rowView
.findViewById(R.id.rel_status_bg);
holder.cornerLabel = (TextView) rowView
.findViewById(R.id.txt_property_offer);
holder.progressbar = (ProgressBar) rowView
.findViewById(R.id.progressbar);
holder.propertyInfoView = (RelativeLayout) rowView
.findViewById(R.id.property_info_view);
//holder.imageview.setTag(imageUrl());
if (Constants.filter_Parameter != null
&& (Constants.filter_Parameter.getGoal().equals("2")
|| Constants.filter_Parameter.getGoal().equals(
"3") || Constants.filter_Parameter
.getGoal().equals("5"))) {
if (Constants.g_Setttings != null
&& Constants.g_Setttings.getIncl_tenantfeesinfo() != null
&& Constants.g_Setttings.getIncl_tenantfeesinfo()
.equals("1")) {
if (propertyItem.getTenant_fee_exempt() != null
&& propertyItem.getTenant_fee_exempt().equals("0")) {
holder.feesApply.setVisibility(View.VISIBLE);
} else {
holder.feesApply.setVisibility(View.GONE);
}
} else {
holder.feesApply.setVisibility(View.GONE);
}
} else {
holder.feesApply.setVisibility(View.GONE);
}
if (holder.feesApply != null) {
holder.feesApply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
TenentFeeDialogActivity.class);
startActivity(intent);
}
});
}
Util.setButtonBackgroundColor(holder.propertyStatusBG);
// propertyStatusBG.getBackground().setAlpha(88);
Util.setButtonBackgroundColor(holder.cornerLabel);
if (propertyItem.getStatus() != null && !propertyItem.getStatus().equals("")) {
updatePropertyStatus(propertyItem.getStatus(), holder.cornerLabel,
holder.propertyStatusBG);
} else {
holder.propertyStatusBG.setVisibility(View.GONE);
}
if (propertyItem.getPR() != null
&& !propertyItem.getPR().equals("")) {
double price = Math.round(Double.parseDouble(propertyItem
.getPR()));
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMinimumFractionDigits(0);
format.setCurrency(Currency.getInstance(Locale.UK));
if (propertyItem.getLetRentFrequency() != null
&& !propertyItem.getLetRentFrequency().equals("")
&& (Constants.filter_Parameter.getGoal().equals("2") || Constants.filter_Parameter
.getGoal().equals("3"))) {
if (Constants.OPTIONS_FREQUENCY.equals("")) {
holder.priceText.setText(format.format(price) + " "
+ Constants.OPTIONS_FREQUENCY
);
} else {
holder.priceText.setText(format.format(price) + " "
+ propertyItem.getLetRentFrequency());
}
}
else if (Constants.g_Setttings.getApp_property_commercial() != null
&& Constants.g_Setttings.getApp_property_commercial()
.equals("1")) {
if ((Constants.g_Setttings
.getIncl_property_commercial_sales() != null && Constants.g_Setttings
.getIncl_property_commercial_sales().equals("1"))
|| Constants.g_Setttings
.getIncl_property_commercial_rent() != null
&& Constants.g_Setttings
.getIncl_property_commercial_rent().equals(
"1")) {
if (Constants.OPTIONS_FREQUENCY.equals("")) {
holder.priceText.setText(format.format(price) + " "
+ Constants.OPTIONS_FREQUENCY
);
} else {
holder.priceText.setText(format.format(price) + " "
+ propertyItem.getLetRentFrequency());
}
}
} else {
holder.priceText.setText(format.format(price));
}
}
String contentText = "";
String propertyTypeCode = propertyItem.getPT();
String propertyType = "";
if (propertyTypeCode != null && !propertyTypeCode.equals("")
&& !propertyTypeCode.equals("null")
&& !propertyTypeCode.equals("0")) {
if (Constants.propertyTypeList != null
&& Constants.propertyTypeList.size() > 0) {
for (int i = 0; i < Constants.propertyTypeList.size(); i++) {
if (Constants.propertyTypeList.get(i).getId() == Integer
.parseInt(propertyTypeCode)) {
propertyType = Constants.propertyTypeList.get(i)
.getLabel();
break;
}
}
} else {
propertyType = "";
}
} else {
propertyType = "";
}
initRentOrSale();
if (propertyItem.getBD() != null
&& !propertyItem.getBD().equals("")) {
if (propertyItem.getBD().equals("0")) {
if (!propertyType.equals("")) {
contentText = propertyType + " " + forRentOrSale + " ";
} else {
contentText = forRentOrSale + " ";
}
} else {
if (!propertyType.equals("")) {
contentText += propertyItem.getBD() + " bed "
+ propertyType + " " + forRentOrSale + " ";
} else {
contentText += propertyItem.getBD() + " bed "
+ forRentOrSale + " ";
}
}
}
if (propertyItem.getA2() != null
&& !propertyItem.getA2().equals("")) {
contentText += "in "
+ Html.fromHtml(StringEscapeUtils
.unescapeHtml(propertyItem.getA2())) + " ";
}
if (contentText != null && !contentText.equals("")) {
holder.content.setText(contentText);
}
imageLoader.displayImage(imageUrl(), holder.imageview,options, new ImageLoadingListener(){
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.progressbar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
holder.progressbar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
holder.progressbar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
holder.progressbar.setVisibility(View.GONE);
}
});
holder.layout = new RelativeLayout(getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
(int) (belowheight / 1.1));
holder.layout.addView(rowView, params);
holder.propertyInfoView.getLayoutParams().height = (int) (belowheight / 4.60);
return holder.layout;
}
}
}
Could be you're mixing GridLayout and GridView. They are different entities.
In setUpGridLayout() you are inflating a grid_view_imageviewitem and adding it to a GridLayout, not GridView.
*
i have solve the issue using
Handler disconnectHandler = new Handler() {
public void handleMessage(Message msg) {
}
};
Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
/////////// load data from here ////
}
}
};
disconnectHandler.postDelayed(disconnectCallback, 1000);*
*