currently i had come out a screen that using tab fragment and RecyclerView like below. I want to know how i going to handle the button click that circle in red. Every time i click, i have get the details of the product that i want to add into the cart. Since the screen that i come out is using RecyclerView , so i'm confusing how to get all the details of the product that i want.
enter image description here
Adapter code
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView row_image;
TextView title;
TextView description;
public ViewHolder(View v, Context c) {
super(v);
mContext = c;
row_image = (ImageView) v.findViewById(R.id.row_image);
title = (TextView) v.findViewById(R.id.row_title);
description = (TextView) itemView.findViewById(R.id.row_description);
}
}
public CatalogPageAdapter(List<CatalogViewData> dataset) {
mDataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.catalog_layout, parent, false);
return new ViewHolder(v,parent.getContext());
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final CatalogViewData fakePageVH = mDataset.get(i);
String points = Double.toString(Double.parseDouble(fakePageVH.getDescription()));
viewHolder.title.setText(fakePageVH.getTitle());
viewHolder.description.setText(points);
String var = fakePageVH.getImage();
new getImage(var, viewHolder).execute();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Title: " + fakePageVH.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
public class getImage extends AsyncTask<String, String, String> {
String imageUrl;
ViewHolder holder;
Bitmap downloadedBitmap;
Bitmap scaled;
public getImage(String url, ViewHolder h){
imageUrl = url;
holder = h;
}
#Override
protected String doInBackground(String... args) {
try {
URL url = new URL(imageUrl);
downloadedBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
scaled = Bitmap.createScaledBitmap(downloadedBitmap, 150, 100, true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "done";
}
#Override
protected void onPostExecute(String result) {
holder.row_image.setImageBitmap(scaled);
}
}
#Override
public int getItemCount() {
return mDataset == null ? 0 : mDataset.size();
}
}
I guess the green icon isn't an ImageView otherwise would be a silly question. Add an empty ImageView, place it exactly on your circle. Then add it into your viewholder and use viewHolder.dummyImageView.setOnClickListener.
EDIT
xml:
<ImageView
android:id="#+id/dummyImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
VievHolder:
public ViewHolder(View v, Context c) {
super(v);
dummyImage = (ImageView) v.findViewById(R.id.dummyImageView);
}
OnClickListener:
ImageView dummyImage;
viewHolder.dummyImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Click!", Toast.LENGTH_SHORT).show();
}
});
Related
I want to scroll recyclerview by click on category position of another recyclerview which is called in popup menu...Below is my code, I am using Sectional Recyclerview and i want to get section item position while click on second recyclerview item...Please note that both recyclerview item's category id is same;
CategoryMenuRecyclerview Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MenuItem.ProductCategory> mDataset;
private ItemListner itemListner;
RestaurantMenuActivity mContext;
public MyAdapter(RestaurantMenuActivity mContext, ArrayList<MenuItem.ProductCategory> productList, ItemListner itemListner) {
mDataset = productList;
this.itemListner = itemListner;
this.mContext = mContext;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mainView;
TextView tvCategory, tvCategoryNo;
public ViewHolder(View v) {
super(v);
mainView = v;
tvCategory = (TextView) v.findViewById(R.id.tvCategory);
tvCategoryNo = (TextView) v.findViewById(R.id.tvCategoryNo);
}
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.tvCategory.setText(mDataset.get(position).getCategoryName());
holder.mainView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemListner.Item(position);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
and i want to scroll below adapter with click item of upper recyclerview item;
RestaurantMenuAdapter;
public class RestaurantMenuAdapter extends SectionedRecyclerViewAdapter<RecyclerView.ViewHolder> {
private List<MenuItem.ProductCategory> allData;
public RestaurantMenuAdapter(List<MenuItem.ProductCategory> data) {
this.allData = data;
}
#Override
public int getSectionCount() {
return allData == null ? 0 : allData.size();
}
private MenuItem.ProductCategory getItem(int position) {
return allData.get(position);
}
#Override
public int getItemCount(int section) {
return allData.get(section).getProductDetails() == null ? 0 : allData.get(section).getProductDetails().size();
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int section) {
String sectionName = allData.get(section).getCategoryName();
SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
sectionViewHolder.tvCategory.setText(sectionName);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int section, final int relativePosition, int absolutePosition) {
final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.tvProductName.setText(allData.get(section).getProductDetails().get(relativePosition).getProductName());
itemViewHolder.tvDescription.setText("Grass Fed Beef with creespy bacon, tasty cheese, salad, relish and hot");
itemViewHolder.tvPrice.setText("$ " + allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
if (near_by_restaurant) {
rlAddCart.setVisibility(View.VISIBLE);
if (tvCategoryCount.getText().toString().matches("0")) {
rlAddCart.setVisibility(View.GONE);
} else {
rlAddCart.setVisibility(View.VISIBLE);
}
if (allData.get(section).getProductDetails().get(relativePosition).getIsOpen().equalsIgnoreCase("1")) {
itemViewHolder.ll_product.setAlpha(0.5f);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry kitchen is closed")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
} else if (allData.get(section).getProductDetails().get(relativePosition).getIsSoldout().equalsIgnoreCase("1")) {
itemViewHolder.tvSoldOut.setVisibility(View.VISIBLE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry all items are sold out")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
} else {
itemViewHolder.tvSoldOut.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPref = getSharedPreferences("cartitems", 0);
String strJson = sharedPref.getString("cartdata", "0");
try {
mainjsonArray = new JSONArray(strJson);
} catch (JSONException e) {
e.printStackTrace();
}
Intent i = new Intent(RestaurantMenuActivity.this, ProductCartActivity.class);
i.putExtra("product_id", allData.get(section).getProductDetails().get(relativePosition).getProductID());
i.putExtra("productCart", true);
i.putExtra("product_name", allData.get(section).getProductDetails().get(relativePosition).getProductName());
i.putExtra("product_price", allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
try {
i.putExtra("jsonArray", mainjsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
startActivityForResult(i, PRODUCT_CART);
}
});
}
} else {
rlAddCart.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry you are not in restaurant")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
}
if (allData.get(section).getProductDetails().get(relativePosition).getFavorited() == 0) {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
}
itemViewHolder.ivFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog pd = ProgressDialog.show(RestaurantMenuActivity.this, "", "Loading...");
JSONObject postdata = new JSONObject();
try {
YupITApplication.getJsonWithHTTPPost(RestaurantMenuActivity.this, 1, new ServiceCallBack() {
#Override
public void serviceCallback(int id, JSONObject jsonResult) {
pd.dismiss();
try {
if (jsonResult.has("Data") && !jsonResult.getString("Data").equals("")) {
// {"Status":"Success","StatusCode":"200","Message":"Item Favourited!","Data":[]}
if (jsonResult.getString("Message").equalsIgnoreCase("Item Favourited!")) {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
}
Toast.makeText(getApplicationContext(), jsonResult.getString("Message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, Utils.insertfavoriteitem + "&productid=" + allData.get(section).getProductDetails().get(relativePosition).getProductID() + "&userid=" + customer_id, postdata);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Glide.with(RestaurantMenuActivity.this).load(allData.get(section).getProductDetails().get(relativePosition).getPhotoImagePath())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(itemViewHolder.ivMenu);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, boolean header) {
View v = null;
if (header) {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_section, parent, false);
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
width = v.getMeasuredWidth();
height = v.getMeasuredHeight();
return new SectionViewHolder(v);
} else {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ItemViewHolder(v);
}
}
// SectionViewHolder Class for Sections
public class SectionViewHolder extends RecyclerView.ViewHolder {
final TextView tvCategory;
public SectionViewHolder(View itemView) {
super(itemView);
tvCategory = (TextView) itemView.findViewById(R.id.tvCategory);
}
}
// ItemViewHolder Class for Items in each Section
public class ItemViewHolder extends RecyclerView.ViewHolder {
final TextView tvProductName, tvDescription, tvPrice, tvSoldOut;
LinearLayout ll_product;
ImageView ivMenu, ivFav;
public ItemViewHolder(View itemView) {
super(itemView);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
ivMenu = (ImageView) itemView.findViewById(R.id.ivMenu);
ll_product = (LinearLayout) itemView.findViewById(R.id.ll_product);
tvSoldOut = (TextView) itemView.findViewById(R.id.tvSoldOut);
ivFav = (ImageView) itemView.findViewById(R.id.ivFav);
}
}
public int isSectionHeaderPosition(int position) {
return Integer.parseInt(allData.get(position).getCategoryID());
}
}
Please help
i think that the position of category in popup menu will be the same as section value of the second recyclerView if you get the position of clicked item in your activity by listening on item's click you can scroll the recyclerView using the LayoutManager.
recyclerView.getLayoutManager().scrollToPosition(youPositionInTheAdapter).
According to my app requirement I am showing a row with textbox,imageview and image capture button in a listview. I am capturing an image and immediately saving that image in that realm row. Then adapter loads that image from related realm object when adaoter getview method gets called.
My problem is when the row data for each list is blank, has more than 4 rows and capturing any image; captured image gets loaded in several position along with the position it is meant to be.
For example if I take image for position 0 it shows after scrolling in position 5,then again reloads to position 6. I have noticed that since after scrolling from position 0 to position 6 adapter position returns 0 again. Which is the reason of the image reloading during scrolling in other positions. When I click in any button for either taking picture/text input this reloaded row again returns to proper position.
I went through almost all possible suggested SO questions related to issue imageview shuffling in listview but none of them works for me.Could you suggest any solution to this problem.
My Adapter code is below-
public class ProgressImageAdapter extends RealmBaseAdapter<ImageCommentRealm> implements ListAdapter {
private Context mContext;
String categoryName;
ProgressListener progressListener;
PopAlertDialog alertDialog;
boolean fromHistory;
public ProgressImageAdapter(Context context, OrderedRealmCollection<ImageCommentRealm> data, ProgressListener progressListener, boolean fromHistory) {
super(context, data);
this.mContext = context;
this.progressListener = progressListener;
FragmentActivity activity = (FragmentActivity) (context);
alertDialog = PopAlertDialog.createAlert(activity.getSupportFragmentManager());
this.fromHistory = fromHistory;
}
#Override
public void updateData(OrderedRealmCollection<ImageCommentRealm> data) {
super.updateData(data);
}
public void resetListener() {
this.progressListener = null;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.image_comment_list_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.tv_title);
holder.editText = (TextView) convertView.findViewById(R.id.et_comment);
holder.imageView = (ImageView) convertView.findViewById(R.id.iv_camera_holder);
holder.imageButton = (ImageButton) convertView.findViewById(R.id.imgbtn_camera);
holder.btnDone = (Button) convertView.findViewById(R.id.btn_confirm);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ImageCommentRealm imageCommentRealm = getItem(position);
holder.textView.setText(String.format(Locale.getDefault(), "%s %d %2s %2s", mContext.getResources().getString(R.string.photo), position + 1, mContext.getString(R.string.of), categoryName));
if (Validator.blankCheck(imageCommentRealm.getFile_path()))
loadImage(holder.imageView, imageCommentRealm.getFile_path());
if (Validator.blankCheck(imageCommentRealm.getDesc()))
holder.editText.setText(imageCommentRealm.getDesc());
if (!fromHistory) {
holder.imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity) mContext).pickFromCamera();
((MainActivity) mContext).setPicker(new IPhotoPicker() {
#Override
public void setImageUri(String filePath) {
//loadImage(holder,filePath);
saveData(null, filePath, imageCommentRealm.getPk());
}
});
}
});
holder.editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = String.format(Locale.getDefault(), "%s %d %2s %2s", mContext.getResources().getString(R.string.description), position + 1, mContext.getString(R.string.of), categoryName);
alertDialog.showSingleInput(title, imageCommentRealm.getDesc(), imageCommentRealm.getPk(), new SingleInput.Listener() {
#Override
public void onClickGreen(String message, long id) {
if (Validator.blankCheck(message)) saveData(message, null, id);
}
});
}
});
}
return convertView;
}
protected void loadImage(ImageView imageView, String imgPath) {
if (imgPath.startsWith("http")) {
ImageUtility.loadProduct(mContext, imgPath, imageView, R.drawable.home);
} else {
try {
File image_file = new File(imgPath);
if (image_file.exists()) {
Bitmap image_profile = BitmapFactory.decodeFile(image_file.getAbsolutePath());
imageView.setImageBitmap(image_profile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void saveData(final String comment, final String filepath, final long pk) {
final Realm realm = Realm.getInstance(RealmUtility.getRealmConfig(mContext));
//ImageCommentRealm imageRealm = getItem(position);
//final long pk = imageRealm.getPk();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ImageCommentRealm imageCommentRealm = realm.where(ImageCommentRealm.class).equalTo("pk", pk).findFirst();
if (imageCommentRealm != null && imageCommentRealm.isLoaded()) {
if (Validator.blankCheck(comment)) {
imageCommentRealm.setDesc(comment);
}
if (Validator.blankCheck(filepath)) {
imageCommentRealm.setFile_path(filepath);
}
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
//notifyDataSetChanged();
realm.close();
try {
if (adapterData != null && adapterData.size() > 0) {
long count = adapterData.where().isNotNull("file_path").isNotNull("desc").count();
if (count == adapterData.size()) {
if (progressListener != null) progressListener.hasRequiredImage();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
error.printStackTrace();
realm.close();
}
});
}
static class ViewHolder {
TextView textView;
TextView editText;
ImageView imageView;
ImageButton imageButton;
Button btnDone;
}
}
Here is a screenshot after taking picture in first position and then scrolling to bottom
FYI: Testing device 4" Samsung J1 Nxt
Eh, this has nothing to do with Realm, you should clear the image if the image path is null.
if (Validator.blankCheck(imageCommentRealm.getFile_path())) {
loadImage(holder.imageView, imageCommentRealm.getFile_path());
} else {
holder.imageView.setImageBitmap(null);
}
if (Validator.blankCheck(imageCommentRealm.getDesc()))
holder.editText.setText(imageCommentRealm.getDesc());
} else {
holder.editText.setText("");
}
I have a ListView of elements composed with ImageView. I get a new image using an AsyncTask and in the onPostExecute(Object result) method I set the image using setImageUri(Uri uri) but it doesn't gets updated.
If I change of activity or between apps, image is shown perfectly, but I want to show the image immediately.
I tried calling invalidate() with all the combinations of the ImageView, the extended BaseAdapter, the parent ListView, but nothing worked. I tried many other techniques like calling setImageResource(0), setImageUri(null), but no results...
EDITED:
Here, part of the code:
public class ThingItemAdapter extends BaseAdapter {
protected List<Thing> things;
LayoutInflater inflater;
public ThingItemAdapter(Context context, List<Thing> things) {
this.things = things;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return things.size();
}
#Override
public Thing getItem(int position) {
return things.get(position);
}
#Override
public long getItemId(int position) {
return things.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.thing_list_item, parent, false);
holder.thingImageView = (ImageView) convertView.findViewById(R.id.thing_preview);
holder.button = (ImageButton) convertView.findViewById(R.id.apply_button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Thing thing = things.get(position);
final long thingId = thing.getId();
final Uri thingUri = thing.getPicture();
holder.thingImageView.setImageURI(thingUri);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// generate new file
final TypedFile typedFile = new TypedFile("multipart/form-data", new File(thingUri.getPath()));
new ReadAndStorePictureTask()
.execute(new Object[] { typedFile, holder.thingImageView, thing });
}
});
// item detailed view listener
holder.thingImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent((ThingApplication) ThingApplication.getContext(), ThingActivity.class);
intent.putExtra(ThingActivity.EXTRA_THING_ID, thingId);
context.startActivity(intent);
}
});
return convertView;
}
private class ViewHolder {
ImageView thingImageView;
ImageButton button;
}
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
Thing thing;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
thing = (Thing) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
thing.setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(thing);
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
imageView.setImageURI(thing.getPicture());
// force redraw. FIXME not working
/*
* ANSWER HERE, PLEASE
*/
}
}
}
How can I show the updated URI immediately inside onPostExecute(Object result) method?
onPostExecute you update the list of images that it's linked to the ListView adapter and after that you notify the adapter that you changed the items in the list by calling:
adapter.notifyDataSetChanged();
You can do something like this:
-Change third parameter in asynctask call.
new ReadAndStorePictureTask().execute(
new Object[] { typedFile, holder.thingImageView, pos });
-Then, modify the list items inside asynctask and refresh.
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
int position;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
position = (Integer) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
things.get(position).setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(things.get(position));
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
notifyDataSetChanged();
}
}
Good luck!
Here is my code. I have cardviews and in some i have one pic and in some there is no pic. But after scroll up and down i get pictures in every CardView (pics from previous cardview) event if there should not be any pic at all (***.size()=0). I think the problem is here
if (mDataset.get(position).getAdv_pics().size()>0){
String pic = mDataset.get(position).getAdv_pics().get(0);
ImageView image = new ImageView(mActivity);
Log.d("!!!!", position + " http://m2.biz.ua" + holder.pic + "_small.jpg");
holder.mLayout.addView(image, 1);
Picasso.with(mActivity)
.load("http://m2.biz.ua" + pic + "_small.jpg")
.resize(100, 100)
.centerCrop()
.into(image);
}
FlatListCardAdapter.class
public class FlatListCardAdapter extends RecyclerView.Adapter<FlatListCardAdapter.ViewHolder> {
private List<Flat> mDataset;
private Activity mActivity;
private String[] currency;
private OnCardClickListener mListener;
public interface OnCardClickListener{
void getFlat(Flat flatId);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mAdvText, mAdvRooms, mAdvPrice, mAdvAddr;
public LinearLayout mLayout;
public ImageButton mCallButton;
public Button test;
public String pic;
public ImageView smallImage;
public View view;
private CardView mCardView;
public ViewHolder(View v ) {
super(v);
view=v;
mAdvText = (TextView) v.findViewById(R.id.advText);
mAdvRooms = (TextView) v.findViewById(R.id.advRooms);
mAdvPrice = (TextView) v.findViewById(R.id.advPrice);
mAdvAddr = (TextView) v.findViewById(R.id.advAddr);
mLayout = (LinearLayout) v.findViewById(R.id.picMainLayout);
mCallButton = (ImageButton) v.findViewById(R.id.callAdv);
mCardView = (CardView) v.findViewById(R.id.card_view);
}
}
public FlatListCardAdapter(Activity activity, List<Flat> dataset, OnCardClickListener mListener) {
mDataset = dataset;
mActivity = activity;
this.mListener = mListener;
}
#Override
public FlatListCardAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_realty_list_card_custom, parent, false);
ViewHolder vh = new ViewHolder(v);
currency=mActivity.getResources().getStringArray(R.array.currency);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Flat mFlat = mDataset.get(position);
String mCurrency="";
if ( Integer.parseInt(mFlat.getAdv_currency())>0 ){
mCurrency=currency[Integer.parseInt(mFlat.getAdv_currency())];
}
holder.mAdvRooms.setText(mFlat.getAdv_rooms()+" ");
holder.mAdvPrice.setText(mFlat.getAdv_price()+" "+mCurrency);
holder.mAdvText.setText(mFlat.getAdv_text());
holder.mAdvAddr.setText(mFlat.getAdv_addr());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("!!!!", mFlat.getId());
try {
mListener = (MainActivity) mActivity;
mListener.getFlat(mFlat);
} catch (ClassCastException e) {
throw new ClassCastException(mActivity.toString() + " must implement OnArticleSelectedListener");
}
}
});
holder.mCallButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
List<String> phone = mFlat.getAdv_phone();
if (phone.size()>0) {
Toast.makeText(mActivity, phone.get(0), Toast.LENGTH_SHORT).show();
}
}
});
Log.d("!!!!", "SIZE: " +mDataset.get(position).getAdv_pics().size());
if (mDataset.get(position).getAdv_pics().size()>0){
String pic = mDataset.get(position).getAdv_pics().get(0);
ImageView image = new ImageView(mActivity);
Log.d("!!!!", position + " http://****" + holder.pic + "_small.jpg");
holder.mLayout.addView(image, 1);
Picasso.with(mActivity)
.load("http://****" + pic + "_small.jpg")
.resize(100, 100)
.centerCrop()
.into(image);
}
/**/
}
#Override
public int getItemCount() {
if (mDataset==null){
return 0;
}
return mDataset.size();
}
}
Item view is reused in the RecyclerView. The issue is here
if (mDataset.get(position).getAdv_pics().size()>0){
...
}
add else clause and set image as null there. As is shown in the code below
if (mDataset.get(position).getAdv_pics().size()>0){
...
}else{
image.setImageBitmap(null);
}
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;
}
}
});