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.
Related
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;
}
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 have a recyclerview adapter in which each view has a button. I want to implement a fuc=nctionality such that if I click button on any view all the views of the recyclerview should be updated. How this can be achieved ?
This is what I have done in onBindViewHolder
public class StoryItemAdapter extends RecyclerView.Adapter<StoryItemAdapter.ViewHolder> {
LayoutInflater inflater;
Context context;
Bitmap bm;
ImageLoader imloader;
static ArrayList<StoryDetails> stories;
OnItemClickListener mItemClickListener;
public StoryItemAdapter(Context context,ArrayList<StoryDetails> stories) {
this.context = context;
this.stories = stories;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imloader = ImageLoader.getInstance();
imloader.init(ImageLoaderConfiguration.createDefault(context));
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getItemCount() {
return stories != null ? stories.size() : 0;
}
#SuppressWarnings("deprecation")
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(stories.get(position).getType()==null) {
holder.user_handle.setText(stories.get(position).getUsername() + "( " + stories.get(position).getHandle() + " )");
File file = imloader.getDiscCache().get(stories.get(position).getImage());
if (!file.exists()) {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.build();
imloader.displayImage(stories.get(position).getImage(), holder.image, options);
} else {
holder.image.setImageURI(Uri.parse(file.getAbsolutePath()));
}
holder.about.setText(stories.get(position).getAbout());
holder.followers.setText("Followers\n\r" + stories.get(position).getFollowers());
holder.following.setText("Following\n\r" + stories.get(position).getFollowing());
}
else
{
holder.user_handle.setText(stories.get(position).getTitle());
File file = imloader.getDiscCache().get(stories.get(position).getSi());
if (!file.exists()) {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.build();
imloader.displayImage(stories.get(position).getSi(), holder.image, options);
} else {
holder.image.setImageURI(Uri.parse(file.getAbsolutePath()));
}
holder.about.setText(stories.get(position).getDescription());
holder.followers.setText("Likes \n\r" + stories.get(position).getLikes_count());
holder.following.setText("Comments \n\r" + stories.get(position).getComment_count());
}
if(stories.get(position).getIs_following())
{
holder.follow.setText("Following");
}
else
holder.follow.setText("Follow");
final int p = position;
final ViewHolder h = holder;
holder.follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(stories.get(p).getIs_following())
{
stories.get(p).setIs_following(false);
h.follow.setText("Follow");
}
else {
stories.get(p).setIs_following(true);
h.follow.setText("Following");
}
for(int i =0;i <stories.size();i++) {
if (stories.get(p).getDb() != null) {
if(stories.get(p).getDb().equals(stories.get(i).getId()))
{
stories.get(p).setIs_following(stories.get(i).getIs_following());
}
}
}
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.story_adapter, viewGroup,
false);
return new ViewHolder(itemView);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView user_handle, about, followers,following,userSince;
Button follow;
public ViewHolder(View itemView) {
super(itemView);
user_handle = (TextView) itemView.findViewById(R.id.user_handle);
about = (TextView) itemView.findViewById(R.id.about);
followers = (TextView) itemView.findViewById(R.id.followers);
following = (TextView) itemView.findViewById(R.id.following);
// userSince = (TextView) itemView.findViewById(R.id.user_since);
image = (ImageView) itemView.findViewById(R.id.user_image);
follow =(Button) itemView.findViewById(R.id.follow);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
image.setLayoutParams(rlp);
image.setAdjustViewBounds(true);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getPosition());
}
}
}
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
You need to notify the Adapter about any dataset changed.
Try this..
holder.follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(stories.get(p).getIs_following())
{
stories.get(p).setIs_following(false);
h.follow.setText("Follow");
}
else {
stories.get(p).setIs_following(true);
h.follow.setText("Following");
}
for(int i =0;i <stories.size();i++) {
if (stories.get(p).getDb() != null) {
if(stories.get(p).getDb().equals(stories.get(i).getId()))
{
stories.get(p).setIs_following(stories.get(i).getIs_following());
}
}
}
notifyDataSetChanged();
}
In my app I'm showing data in listview. While scrolling through listview my app is crashing. What changes should I make?
as given in the error my RecipeListFragment.java file is:
public class RecipeListFragment extends Fragment {
MyDatabase db;
boolean isfav = false;
Context context;
ListView lvrecipe;
ArrayList<RecipePojo> recipelist = new ArrayList<RecipePojo>();
LinearLayout ll;
DisplayImageOptions options;
private ProgressDialog progress;
int position;
String recipeid;
int checkcounter = 0;
private Custom_Adapter adapter;
public RecipeListFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recipe_list_actvity, container, false);
context = getActivity();
lvrecipe = (ListView) rootView.findViewById(R.id.lvrecipe);
// adView = (MoPubView)rootView. findViewById(R.id.mopub_sample_ad);
new getrecipe().execute();
db = new MyDatabase(getActivity());
// recipelist = DataManager.recipelist;
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
/* if(recipeid!=null){
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();*/
lvrecipe.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataManager.selectedposition = position;
Intent i = new Intent(getActivity(), RecipeDescription.class);
i.putExtra("cusinename", DataManager.cusinename);
startActivity(i);
getActivity().finish();
}
});
// adddisplay();
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public class Custom_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
public Custom_Adapter(Context c) {
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
if (recipelist != null) {
return recipelist.size();
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
if (recipelist != null) {
return recipelist.get(position);
} else {
return 0;
}
}
#Override
public long getItemId(int position) {
if (recipelist != null) {
return position;
} else {
return 0;
}
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.recipelist, null);
holder = new ViewHolder();
holder.txttile = (TextView) convertView.findViewById(R.id.txttile);
holder.imgrecipe = (ImageView) convertView.findViewById(R.id.imgrecipe);
holder.fav_unfav = (ImageView) convertView.findViewById(R.id.fav_unfav);
holder.ratingbar = (RatingBar) convertView.findViewById(R.id.ratingbar);
holder.txtduration = (TextView) convertView.findViewById(R.id.txtduration);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (recipelist != null) {
recipeid = recipelist.get(position).getRecipeid();
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();
if (isfav) {
holder.fav_unfav.setImageResource(R.drawable.favourite);
} else {
holder.fav_unfav.setImageResource(R.drawable.favourites);
}
Typeface face1 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_300_light.ttf");
Typeface face2 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_400_regular.ttf");
holder.txttile.setTypeface(face2);
holder.txtduration.setTypeface(face1);
holder.txttile.setText(recipelist.get(position).getRecipename());
try {
String[] prep = recipelist.get(position).getPrep_time().split(" ");
String[] cook = recipelist.get(position).getCooking_time().split(" ");
int totalTime = Integer.parseInt(prep[0]) + Integer.parseInt(cook[0]);
holder.txtduration.setText(""+totalTime+" min");
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String url = DataManager.photourl + "recipe/" + recipelist.get(position).getRecipeid() + ".jpg";
try {
url = URLDecoder.decode(url, "UTF-8");
url = url.replaceAll(" ", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (recipelist.get(position).getVideo_link().equals("none")) {
// holder.imgvideo.setVisibility(View.GONE);
}
String rating = recipelist.get(position).getRatings();
if (rating != null && rating.trim().length() > 0) {
holder.ratingbar.setRating(Float.valueOf(rating));
}
//holder.imgrecipe.setImage(url,getResources().getDrawable(R.drawable.cusine));
if (holder.imgrecipe != null) {
if (url != null && url.trim().length() > 0) {
//final ProgressBar pbar = holder.pbar;
final ImageView imageView = holder.imgrecipe;
//final RelativeLayout imgRL = holder.imageRL;
ImageLoader.getInstance().displayImage(url, holder.imgrecipe, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
imageView.setAdjustViewBounds(true);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
}
#Override
public void onLoadingStarted(String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
}
});
} else {
}
}
return convertView;
}
class ViewHolder {
TextView txttile, txtduration;
ImageView imgrecipe;
ImageView fav_unfav;
RatingBar ratingbar;
}
}
public class getrecipe extends AsyncTask<String, Void, String> {
boolean response = false;
#Override
protected void onPreExecute() {
//progress = ProgressDialog.show(context, "Getting Data...","Please wait....");
progress = new ProgressDialog(getActivity());
progress.setMessage("Please wait....");
progress.show();
}
#Override
protected String doInBackground(String... params) {
response = APIManager.getrecipebycusine(DataManager.CUISINE_ID);
return "";
}
#Override
protected void onPostExecute(String result) {
progress.cancel();
if (response) {
if (DataManager.status.equalsIgnoreCase("1")) {
recipelist = DataManager.recipelist;
adapter.notifyDataSetChanged();
//Intent i = new Intent(getActivity(),RecipeListActvity.class);
//startActivity(i);
} else {
connectionerror();
}
} else {
connectionerror();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void alert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("No Recipe!");
alertDialog.setMessage("No Recipe for this Cusine");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new getrecipe().execute();
}
});
alertDialog.show();
}}
The errors that are showing in Crashlytics is:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
at com.raccoonfinger.salad.RecipeListFragment.connectionerror(RecipeListFragment.java:381)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:335)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:296)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please do not use getActivity() directly in Fragment because sometimes it returns null..
Always pass activity as a parameter in constructor..!!
Please use below method to create your Fragment and use activity reference instead of getActivity()..
public static AboutFragment newInstance(Activity activity) {
AboutFragment aboutFragment = new AboutFragment();
aboutFragment.mActivity = activity;
return aboutFragment;
}
Hope it will help.
Thanks ..!!
I have a problem with click on image in item in ListView. When I click I want to show layout which is gone. This is my code:
public class MyActualOffers extends BaseActivity {
private IResponse iResponse = null;
private ListView actualOffersList;
private ActualOffersListAdapter actualOffersAdapter;
private ArrayList<Offers> actualOffersFromJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_actual_offers);
actualOffersFromJson = new ArrayList<Offers>();
actualOffersList = (ListView) findViewById(R.id.actualOffersList);
iResponse = new IResponse() {
#Override
public void onResponse(JSONObject jObject) {
// messageUser = new User();
// messageUser.parseJsonResponse(jObject);
// usersMessages.add(messageUser);
// new DownloadImageTask(profileP)
// .execute("http://"+messageUser.getAvatarURL());
//
// messagesListView.refreshDrawableState();
// adapter.notifyDataSetChanged();
// adapter.notifyDataSetInvalidated();
}
#Override
public void onResponse(JSONArray jArray) {
try {
for (int i = 0; i < 3; i++) {
JSONObject messageJSON = (JSONObject)jArray.get(i);
Offers offer = new Offers();
offer.parseJsonResponse(messageJSON);
actualOffersFromJson.add(offer);
}
}catch (JSONException e) {
e.printStackTrace();
}
actualOffersAdapter = new ActualOffersListAdapter(getApplicationContext(), actualOffersFromJson);
actualOffersList.setAdapter(actualOffersAdapter);
// adapter = new MessagesListAdapter(getApplicationContext(), myMessagesList, usersMessages);
// messagesListView.setAdapter(adapter);
}
#Override
public void onError(JSONObject jObject) {
ErrorObject error = new ErrorObject();
error.parseJsonResponse(jObject);
error.showErrorDialog(MyActualOffers.this);
}
};
getActualMyOffers();
}
private void getActualMyOffers(){
SharedPreferencesData sharedData = new SharedPreferencesData();
String url = ConnectionParams.URL_OFFERS_FETCH_CURRENT_USER_OFFERS.replace("{0}", ""+"get");
String token = "?auth_token="+sharedData.getTokenData(getBaseContext());
connection.get(url + token + "&state=active", iResponse);
}
private class ActualOffersListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Offers> offersList;
private LayoutInflater inflater;
private ViewHolder holder;
boolean isExpand = false;
public ActualOffersListAdapter(Context context, ArrayList<Offers> offersList) {
this.context = context;
this.offersList = offersList;
inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return offersList.size();
}
#Override
public Object getItem(int position) {
return offersList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(
R.layout.actual_offers_list_item, null);
holder = new ViewHolder();
holder.cities = (TextViewWithImage) convertView.findViewById(R.id.actualOffersFromCityTXT);
holder.date = (TextView) convertView.findViewById(R.id.actualOffersCalendarTXT);
holder.type = (TextView) convertView.findViewById(R.id.actualOffersTripTypeTXT);
holder.shipment = (TextView) convertView.findViewById(R.id.actualOffersShipmentTypeTXT);
holder.transport = (TextView) convertView.findViewById(R.id.actualOffersTransportTypeTXT);
holder.deleteOffer = (TextView) convertView.findViewById(R.id.actualOffersDeleteTXT);
holder.editOffer = (TextView) convertView.findViewById(R.id.actualOffersEditOfferTXT);
holder.addSimilar = (TextView) convertView.findViewById(R.id.actualOffersAddSimilarTXT);
holder.addOpposite = (TextView) convertView.findViewById(R.id.actualOffersAddOppositeTXT);
holder.infoIcon = (ImageView) convertView.findViewById(R.id.actualOffersInfoICON);
holder.shipmentIcon = (ImageView) convertView.findViewById(R.id.actualOffersShipmentTypeICON);
holder.transportIcon = (ImageView) convertView.findViewById(R.id.actualOffersTransportTypeICON);
holder.typeIcon = (ImageView) convertView.findViewById(R.id.actualOffersTripTypeICON);
holder.expandIcon = (ImageView) convertView.findViewById(R.id.expandIcon);
holder.actualOffersExpandLayout = (RelativeLayout) convertView.findViewById(R.id.actualOffersExpandLayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.cities.setText(offersList.get(position).getStart() + " [img src=ic_in_text_arrow/] " + offersList.get(position).getDestination());
holder.date.setText(offersList.get(position).getCreatedAt());
if(offersList.get(position).getFrequency().equals("once")){
holder.typeIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_in_text_once));
}else{
holder.typeIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_in_text_infinity));
}
holder.type.setText(offersList.get(position).getType());
holder.shipmentIcon.setImageDrawable(ShipmentTypeEnum.setIconForShipmentType(ShipmentTypeEnum.fromString(offersList.get(position).getShipmentType()), getApplicationContext()));
holder.transportIcon.setImageDrawable(TransportTypeEnum.setIconForTransportType(TransportTypeEnum.fromString(offersList.get(position).getTransportType()), getApplicationContext()));
holder.deleteOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.editOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.addSimilar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.addOpposite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.expandIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isExpand){
holder.actualOffersExpandLayout.setVisibility(View.INVISIBLE);
isExpand = false;
}else{
holder.actualOffersExpandLayout.setVisibility(View.VISIBLE);
isExpand = true;
}
}
});
holder.infoIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
}
public static class ViewHolder {
public TextViewWithImage cities;
public TextView date;
public TextView type;
public TextView shipment;
public TextView transport;
public TextView deleteOffer;
public TextView editOffer;
public TextView addSimilar;
public TextView addOpposite;
public ImageView infoIcon;
public ImageView shipmentIcon;
public ImageView transportIcon;
public ImageView typeIcon;
public ImageView expandIcon;
public RelativeLayout actualOffersExpandLayout;
}
}
No when I click on holder.expandIcon in first item, expand layout show in last item of list. How can I create list with my item and properly working click on image in every item?
You are expanding the last item in the list because that was the last view retrieved by getView. The way the code is written now, there is only one isExpand value.
So you need to (a) add isExpand on the ViewHolder, and (b) use the ViewHolder attached to the View that was passed in the event handler. Like this:
holder.expandIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder vh = (ViewHolder)v.getTag();
if(vh.isExpand){
vh.actualOffersExpandLayout.setVisibility(View.INVISIBLE);
vh.isExpand = false;
}else{
vh.actualOffersExpandLayout.setVisibility(View.VISIBLE);
vh.isExpand = true;
}
}
});