Android RecyclerView and custom Adapter position elements changes - android

I have a RecylcerView filled with a Custom Adapter recylerView.setAdapter(myAdapter), and the adaper is filled with different elements by an ArrayList. In the ViewHolder i overrided the
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) method. In the custom ViewHolder i put a button. The button has a click listener on it. When i click the button i read the variable position and i am facing that the variable changes every time i click the same button.
Why this happens?
My Adapter is like this:
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.amplifyframework.core.Amplify;
import com.amplifyframework.core.model.query.Where;
import com.amplifyframework.datastore.generated.model.Comments;
import com.amplifyframework.datastore.generated.model.Likes;
import com.amplifyframework.datastore.generated.model.Posts;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import java.net.URL;
import java.util.LinkedList;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread;
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.PostViewHolder>
{
private LinkedList<Posts> usersPostsList;
private FirebaseAuth mAuth;
private Context context;
//private Boolean likeChecker;
private String currentUserId;
private MainActivity mainActivity;
private int currentPosition;
public PostsAdapter(Context context, String currentUserId, MainActivity mainActivity)
{
this.context = context;
this.currentUserId = currentUserId;
this.mainActivity = mainActivity;
}
public PostsAdapter(LinkedList<Posts> usersPostsList, Context context)
{
this.usersPostsList = usersPostsList;
this.context = context;
}
public void setMessages(LinkedList<Posts> usersPostsList) {
this.usersPostsList = usersPostsList;
}
public static class PostViewHolder extends RecyclerView.ViewHolder
{
View mView;
public static ImageButton LikePostButton, CommentPostButton;
public TextView DisplayNoOfLikes, modifyPost;
private TextView DisplayNoOfComments;
String currentUserID;
ExpandableTextView PostDescription;
private Context context;
public PostViewHolder(#NonNull View itemView, Context context)
{
super(itemView);
mView = itemView;
this.context = context;
LikePostButton = (ImageButton) mView.findViewById(R.id.like_button);
CommentPostButton = (ImageButton) mView.findViewById(R.id.comment_button);
DisplayNoOfLikes = (TextView) mView.findViewById(R.id.display_no_of_likes);
DisplayNoOfComments = (TextView) mView.findViewById(R.id.display_no_of_comments);
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
modifyPost = mView.findViewById(R.id.modify_post);
}
public void setLikeButtonStatus(final String PostKey) {
Amplify.DataStore.query(
Likes.class, Where.matches(Likes.POST_ID.eq(PostKey.trim()).and(Likes.SENDER.eq(currentUserID.trim()))),
items -> {
int countLikes = 0;
if (!items.hasNext()) {
LikePostButton.setImageResource(R.drawable.ic_star_border);
}
while (items.hasNext()) {
Likes item = items.next();
countLikes++;
LikePostButton.setImageResource(R.drawable.ic_star_fill);
Log.i("Amplify", "Id " + item.getId());
}
int finalCountLikes = countLikes;
DisplayNoOfLikes.setText(finalCountLikes + (" Likes"));
},
failure -> Log.e("Amplify", "Could not query DataStore", failure)
);
}
public void setFullname(String fullname)
{
TextView username = (TextView) mView.findViewById(R.id.post_user_name);
username.setText(fullname);
}
public void setProfileimage(Context ctx, String profileimage)
{
CircleImageView image = (CircleImageView) mView.findViewById(R.id.post_profile_image);
Amplify.Storage.getUrl(profileimage,
result -> {
URL url = result.getUrl();
runOnUiThread(() -> Glide.with(ctx)
.load(url)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(image));
},
error -> Log.i("Amplify", "error while retrieving url"));
}
public void setTime(String time)
{
TextView PostTime = (TextView) mView.findViewById(R.id.post_time);
PostTime.setText(" " + time);
}
public void setDate(String date)
{
TextView PostDate = (TextView) mView.findViewById(R.id.post_date);
PostDate.setText(" " + date);
}
public void setDescription(String description)
{
PostDescription = mView.findViewById(R.id.post_description);
PostDescription.setText(description);
}
public void setPostimage(Context ctx, String postimage, String id)
{
ImageView postImageInner = mView.findViewById(R.id.post_image);
Amplify.Storage.getUrl(postimage,
result -> {
URL url = result.getUrl();
runOnUiThread(() -> Glide.with(ctx)
.load(url)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(postImageInner));
Log.i("Amplify---------", "url ok----");
},
error -> Log.e("Amplify---------", "error while retrieving url: " + error.getCause().toString()));
postImageInner.setOnClickListener(v -> {
Intent clickPostIntent = new Intent(context, ClickPostActivity.class);
clickPostIntent.putExtra("PostKey", id);
clickPostIntent.putExtra("postImagePath", postimage);
context.startActivity (clickPostIntent);
});
}
public void setCountry(String country)
{
TextView CountryName = (TextView) mView.findViewById(R.id.post_country_name);
CountryName.setText(country);
}
public void setCity(String city)
{
TextView City = (TextView) mView.findViewById(R.id.post_city_name);
City.setText("- " + city);
}
public void setCommentStatus(final String PostKey) {
Amplify.DataStore.query(
Comments.class, Where.matches(Comments.POST_ID.eq(PostKey.trim())),
items -> {
int i = 0;
while (items.hasNext()) {
Comments comments = items.next();
i++;
int finalI = i;
runOnUiThread(() -> DisplayNoOfComments.setText(finalI + " comments"));
Log.i("amplify?", "comment id: " + comments.getId());
}
},
failure -> Log.e("Amplify", "Could not query DataStore", failure)
);
}
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View V = LayoutInflater.from(parent.getContext())
.inflate(R.layout.all_posts_layout, parent,false);
mAuth = FirebaseAuth.getInstance();
return new PostViewHolder(V, context);
}
#Override
public int getItemViewType(int position) {
currentPosition = position;
return position;
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder viewHolder, int position) {
viewHolder.setFullname(usersPostsList.get(position).getFullname());
viewHolder.setTime(usersPostsList.get(position).getTime());
viewHolder.setDate(usersPostsList.get(position).getDate());
viewHolder.setDescription(usersPostsList.get(position).getDescription());
viewHolder.setProfileimage(context, usersPostsList.get(position).getProfileimage());
viewHolder.setPostimage(context, usersPostsList.get(position).getPostimage(), usersPostsList.get(position).getId());
viewHolder.setCountry(usersPostsList.get(position).getCountry());
viewHolder.setCity(usersPostsList.get(position).getCity());
if( viewHolder.PostDescription.originalText.length() > 100 ) {
viewHolder.PostDescription.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!((ExpandableTextView)v).read) {
((ExpandableTextView)v).expandText();
((ExpandableTextView)v).read = true;
} else {
((ExpandableTextView)v).truncateText();
((ExpandableTextView)v).read = false;
}
}
});
}
viewHolder.CommentPostButton.setOnClickListener(v -> {
Intent commentsIntent = new Intent(context, CommentActivity.class);
commentsIntent.putExtra("PostKey",usersPostsList.get(currentPosition).getId());
context.startActivity(commentsIntent);
});
viewHolder.LikePostButton.setOnClickListener(v -> {
Amplify.DataStore.query(
Likes.class, Where.matches(Likes.POST_ID.eq(usersPostsList.get(currentPosition).getId().trim())
.and(Likes.SENDER.eq(currentUserId.trim()))
.and((Likes.RECEIVER.eq(usersPostsList.get(currentPosition).getUid())))
),
items -> {
if (items.hasNext()) {
Likes item = items.next();
Amplify.DataStore.delete(item,
deleted -> Log.i("Amplify", "Deleted item."),
failure -> Log.e("Amplify", "Delete failed.", failure)
);
Log.i("Amplify", "Id " + item.getId());
} else {
Likes likes = Likes.builder()
.receiver(usersPostsList.get(currentPosition).getUid().trim())
.sender(currentUserId.trim())
.postId(usersPostsList.get(currentPosition).getId().trim())
.value("true")
.build();
Amplify.DataStore.save(
likes,
success -> Log.i("Amplify", "Item updated: " + success.item().getId()),
error -> Log.e("Amplify", "Could not save item to DataStore", error)
);
}
},
failure -> {
Log.e("Amplify", "Could not query DataStore", failure);
}
);
notifyDataSetChanged();
});
viewHolder.modifyPost.setOnClickListener(v -> {
Intent intent = new Intent(context, ClickPostActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("PostKey", usersPostsList.get(currentPosition).getId());
intent.putExtra("postImagePath", usersPostsList.get(currentPosition).getPostimage());
context.startActivity(intent);
});
}
#Override
public int getItemCount() {
return usersPostsList.size() ;
}
}
Seems that method getItemViewType is called after the click on LikePostButton so that : viewHolder.LikePostButton.setOnClickListener(v -> { gets an older currentPosition variable value
Thanks to everyone helping me to understand

you can override getItemViewType(position:Int) method and replace the line of super to return it with only position like this in Kotlin:
override fun getItemViewType(position: Int): Int {
return position
}
in Java :
#Override
public int getItemViewType(int position) {
return position;
}

Thanks, i solved it setting the listener on the button in the ViewHolder and then just calling getAbsoluteAdapterPosition() to get the correct position

Related

The specified child already has a parent. You must call removeView() on the child's parent first in my chat application

Guy's I am creating a chat application. My Text messages are uploaded successfully but I am trying to upload an image to my chat application to the server this time I have some error.
That is: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
This is my code for image upload:
final String filename = "" + m[0];
String s1 = filename;
String f_name = s1.substring(7);
String type = "image";
DatabaseReference dbs = FirebaseDatabase.getInstance().getReference();
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
String dateToStr = format.format(today);
ChatMessagepojo chatmsg = new ChatMessagepojo(profileimageurl, dateToStr, type, id, name, f_name);
dbs.child("chats").push().setValue(chatmsg);
alertDialogimage.dismiss();
alertDialog.dismiss();
Whats this problem. How to solve it.
This is my view Holder:
package com.blood4pet.app.Adaptor;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.blood4pet.app.R;
import com.blood4pet.app.pojo.ChatMessagepojo;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.List;
import static android.os.Environment.DIRECTORY_DOWNLOADS;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class ChatsList extends RecyclerView.Adapter<ChatsList.ViewHolder> {
private static final int MSG_TYPE_LEFT = 0;
private static final int MSG_TYPE_RIGHT = 1;
private static final int MSG_IMAGE_TYPE_RIGHT = 2;
private static final int MSG_IMAGE_TYPE_LEFT = 3;
private Context mContext;
private List<ChatMessagepojo> mChat;
private String name;
String type;
FirebaseUser firebaseUser;
StorageReference storageReference;
StorageReference ref;
public ChatsList(Context mContext, List<ChatMessagepojo> mChat, String name, String type) {
this.mContext = mContext;
this.mChat = mChat;
this.name = name;
this.type = type;
}
#NonNull
#Override
public ChatsList.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_IMAGE_TYPE_RIGHT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_image_right, parent, false);
return new ChatsList.ViewHolder(view);
}
if (viewType == MSG_IMAGE_TYPE_LEFT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_image_left, parent, false);
return new ChatsList.ViewHolder(view);
}
if (viewType == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new ChatsList.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new ChatsList.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
ChatMessagepojo chat = mChat.get(position);
if (mChat.get(position).getSid().equals(firebaseUser.getUid()) && chat.getType().equals("image")) {
Glide.with(mContext).load(chat.getMessage()).into(holder.loadedimage);
holder.my_name.setText(chat.getName());
} else if (mChat.get(position).getSid().equals(firebaseUser.getUid()) && chat.getType().equals("text")) {
holder.show_message.setText(chat.getMessage());
holder.my_name.setText(chat.getName());
} else if (chat.getType().equals("image")) {
Glide.with(mContext).load(chat.getMessage()).into(holder.loadedimage);
holder.my_name.setText(chat.getName());
holder.download_image_file.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedposition = position;
ChatMessagepojo productid = mChat.get(position);
String message = productid.getMessage();
String filename = productid.getImagename();
downloadimage(message, filename);
}
});
} else if (chat.getType().equals("text")) {
holder.show_message.setText(chat.getMessage());
holder.my_name.setText(chat.getName());
}
}
private void downloadimage(String message, String file) {
Log.d(TAG, "image url: " + message);
storageReference = FirebaseStorage.getInstance().getReference().child("chat");
final String filename = file;
Log.d(TAG, "Original File Name: " + filename);
ref = storageReference.child(filename + ".jpg");
Log.d(TAG, "download Url: " + ref.getDownloadUrl());
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
download(mContext, filename, ".jpg", DIRECTORY_DOWNLOADS, url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
// download();
}
public void download(Context context, String filename, String file_extension, String destinationDirectory, String url) {
DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
request.setDestinationInExternalFilesDir(context, destinationDirectory, filename + file_extension);
Long refeerence = downloadManager.enqueue(request);
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView show_message;
public TextView my_name;
public ImageView loadedimage, download_image_file;
public ViewHolder(#NonNull View itemView) {
super(itemView);
loadedimage = (ImageView) itemView.findViewById(R.id.show_image);
download_image_file = (ImageView) itemView.findViewById(R.id.download_image_file);
show_message = (TextView) itemView.findViewById(R.id.show_message);
my_name = (TextView) itemView.findViewById(R.id.my_name);
}
}
#Override
public int getItemViewType(int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
ChatMessagepojo chat = mChat.get(position);
String type = chat.getType();
if (mChat.get(position).getSid().equals(firebaseUser.getUid()) && type.equals("text")) {
return MSG_TYPE_RIGHT;
} else if (mChat.get(position).getSid().equals(firebaseUser.getUid()) && type.equals("image")) {
return MSG_IMAGE_TYPE_RIGHT;
} else if (type.equals("image")) {
return MSG_IMAGE_TYPE_LEFT;
} else {
return MSG_TYPE_LEFT;
}
}
}
But I have an error on the image browsing button clicking:
btn_attach = (ImageButton) findViewById(R.id.btn_attach);
btn_attach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = alert.create();
alertDialog.setTitle("Select File Type");
// alertDialog.getWindow().setGravity(Gravity.BOTTOM);
alertDialog.show();
}
});
I think you are creating the application in the wrong way. You try to create a chat application means. first, pass the image picer in another activity and get it after upload image go back it same activity. Try This way.

Unable to fetch the data from Firebase Database

I am trying to retrive values from firebase database. But when I am trying to run the app it crashes. Here is the java file:
package com.example.fresh24;
import android.content.Context;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class DBqueries {
public static FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
public static List<MachineCategoryModel> machineCategoryModelList = new ArrayList<>();
public static List<HomePageModel> homePageModelList = new ArrayList<>();
public static void loadCategories(final MachineCategoryAdapter machineCategoryAdapter, final Context context){
firebaseFirestore.collection("CATEGORIES").orderBy("index").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for(QueryDocumentSnapshot documentSnapshot : task.getResult()){
machineCategoryModelList.add(new MachineCategoryModel(documentSnapshot.get("categoryName").toString()));
}
machineCategoryAdapter.notifyDataSetChanged();
} else{
String error = task.getException().getMessage();
Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
}
}
});
}
public static void loadFragmentData(final HomePageAdapter adapter, final Context context){
firebaseFirestore.collection("CATEGORIES")
.document("CoolingCabinet")
.collection("TRAYS").orderBy("index").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for(QueryDocumentSnapshot documentSnapshot : task.getResult()){
if((long)documentSnapshot.get("view_type") == 0){
List<WishlistModel>viewAllProductList = new ArrayList<>();
List<HorizontalProductScrollModel> horizontalProductScrollModelList = new ArrayList<>();
long no_of_products= (long)documentSnapshot.get("no_of_products");
for(long x = 1; x < no_of_products; x++){
horizontalProductScrollModelList.add(new HorizontalProductScrollModel(documentSnapshot.get("product_ID_"+x).toString(),
documentSnapshot.get("product_location_"+x).toString(),
documentSnapshot.get("product_image_"+x).toString(),
documentSnapshot.get("product_title_"+x).toString(),
documentSnapshot.get("product_stock_"+x).toString(),
documentSnapshot.get("product_price_"+x).toString()));
viewAllProductList.add(new WishlistModel(
documentSnapshot.get("product_image_"+x).toString(),
documentSnapshot.get("product_title_"+x).toString(),
(long)documentSnapshot.get("free_coupons_"+x),
documentSnapshot.get("average_rating_"+x).toString(),
(long)documentSnapshot.get("tol_rating_"+x),
documentSnapshot.get("product_price_"+x).toString(),
documentSnapshot.get("product_cut_price_"+x).toString()
));
}
homePageModelList.add(new HomePageModel(0,documentSnapshot.get("layout_title").toString(),documentSnapshot.get("layout_background").toString(),horizontalProductScrollModelList,viewAllProductList));
}
}
adapter.notifyDataSetChanged();
} else{
String error = task.getException().getMessage();
Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is my Model class
package com.example.fresh24;
public class WishlistModel {
private String productImage;
private String productTitle;
private long freeCoupon;
private String rating;
private long totalRatings;
private String productPrice;
private String cutPrice;
public WishlistModel(String productImage, String productTitle, long freeCoupon, String rating, long totalRatings, String productPrice, String cutPrice) {
this.productImage = productImage;
this.productTitle = productTitle;
this.freeCoupon = freeCoupon;
this.rating = rating;
this.totalRatings = totalRatings;
this.productPrice = productPrice;
this.cutPrice = cutPrice;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductTitle() {
return productTitle;
}
public void setProductTitle(String productTitle) {
this.productTitle = productTitle;
}
public long getFreeCoupon() {
return freeCoupon;
}
public void setFreeCoupon(long freeCoupon) {
this.freeCoupon = freeCoupon;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public long getTotalRatings() {
return totalRatings;
}
public void setTotalRatings(long totalRatings) {
this.totalRatings = totalRatings;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getCutPrice() {
return cutPrice;
}
public void setCutPrice(String cutPrice) {
this.cutPrice = cutPrice;
}
}
Here is the the adapter file:
package com.example.fresh24;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
public class WishlistAdapter extends RecyclerView.Adapter<WishlistAdapter.ViewHolder> {
private List<WishlistModel> wishlistModelList;
private Boolean wishlist;
public WishlistAdapter(List<WishlistModel> wishlistModelList, Boolean wishlist) {
this.wishlistModelList = wishlistModelList;
this.wishlist = wishlist;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.wishlist_item_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WishlistAdapter.ViewHolder viewHolder, int position) {
String resource = wishlistModelList.get(position).getProductImage();
String title = wishlistModelList.get(position).getProductTitle();
long freeCoupon = wishlistModelList.get(position).getFreeCoupon();
String rating = wishlistModelList.get(position).getRating();
long totalRatings = wishlistModelList.get(position).getTotalRatings();
String productPrice = wishlistModelList.get(position).getProductPrice();
String cutPrice = wishlistModelList.get(position).getCutPrice();
viewHolder.setData(resource, title, freeCoupon, rating, totalRatings, productPrice, cutPrice);
}
#Override
public int getItemCount() {
return wishlistModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView productImage;
private TextView productTitle;
private TextView freeCoupons;
private TextView rating;
private TextView totalRatings;
private View priceCut;
private ImageView couponIcon;
private TextView productPrice;
private TextView cutPrice;
private ImageView deleteBtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
productImage = itemView.findViewById(R.id.product_image);
productTitle = itemView.findViewById(R.id.product_title);
freeCoupons = itemView.findViewById(R.id.free_coupon);
rating = itemView.findViewById(R.id.tv_product_rating_miniview);
totalRatings = itemView.findViewById(R.id.total_ratings);
priceCut = itemView.findViewById(R.id.price_cut);
couponIcon = itemView.findViewById(R.id.coupon_icon);
productPrice = itemView.findViewById(R.id.product_price);
cutPrice = itemView.findViewById(R.id.cut_price);
deleteBtn = itemView.findViewById(R.id.delete_btn);
}
private void setData(String resource, String title, long freeCouponsNo, String averageRate, long totalRatingsNo, String price, String cutPriceValue) {
Glide.with(itemView.getContext()).load(resource).apply(new RequestOptions().placeholder(R.drawable.home_icon_green)).into(productImage);
productTitle.setText(title);
if (freeCouponsNo != 0) {
couponIcon.setVisibility(View.VISIBLE);
if (freeCouponsNo == 1) {
freeCoupons.setText("free " + freeCouponsNo + " coupon");
} else {
freeCoupons.setText("free " + freeCouponsNo + " coupons");
}
}else{
couponIcon.setVisibility(View.INVISIBLE);
freeCoupons.setVisibility(View.INVISIBLE);
}
rating.setText(averageRate);
totalRatings.setText(totalRatingsNo+"(ratings)");
productPrice.setText(price);
cutPrice.setText(cutPriceValue);
if(wishlist){
deleteBtn.setVisibility(View.VISIBLE);
}else{
deleteBtn.setVisibility(View.GONE);
}
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(),"Testing Deleted",Toast.LENGTH_SHORT).show();
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent productDetailsIntent = new Intent(itemView.getContext(),ProductDetailsActivity.class);
itemView.getContext().startActivity(productDetailsIntent);
}
});
}
}
}
Here is the logcat error:
Process: com.example.fresh24, PID: 9413
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at com.example.fresh24.DBqueries$2.onComplete(DBqueries.java:68)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
The error is on this line in the java file - (long)documentSnapshot.get("free_coupons_"+x). I have selected numbers for the 'free coupons' and 'total ratings' field in the Firebase database. I have read that the number fields are converted to Long when fetched from the firebase database and hence I have casted them to long. I am unable to locate the source of my error. Please help. Thanks in advance.
This is due to the fact you are not checking if the value if null or not.So just put the whole code which fetches the long value inside a if loop with condition that it is != null this will solve the issue.Hope it is helpful.

GridView Always Scroll To The Top After Success Load Next Page

I face a difficulty when working using recyclerview and Gridview. The problem is when my application success load next page (next data), the recyclerview always back to the top.
I want the recyclerview start from last index.
Example : First page load 10 items, after success loan next page, the recycler view start scrolling from item 8.
For resolve that problem, i have tried all the solution on stackoverflow still get nothing.
Here are my code :
package com.putuguna.sitehinduapk.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.putuguna.sitehinduapk.R;
import com.putuguna.sitehinduapk.activities.DetailBlogPostActivity;
import com.putuguna.sitehinduapk.models.listposts.ItemPostModel;
import com.putuguna.sitehinduapk.utils.GlobalFunction;
import com.putuguna.sitehinduapk.utils.GlobalVariable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class ListPostAdapter extends RecyclerView.Adapter<ListPostAdapter.ViewHolder>{
private List<ItemPostModel> mListPost;
private Context mContext;
public ListPostAdapter(List<ItemPostModel> mListPost, Context mContext) {
this.mListPost = mListPost;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.adapter_item_list_post, null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ItemPostModel post = mListPost.get(position);
List<String> listURL = extractUrls(post.getContentPosting());
Glide.with(mContext)
.load(listURL.get(0))
.into(holder.ivImagePost);
holder.tvTitle.setText(post.getTitle());
holder.llItemPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TO DO OnClick
}
});
List<String> listLabel = post.getListLabel();
String labelPost="";
for(int i=0; i<listLabel.size();i++){
labelPost += "#"+listLabel.get(i) + " ";
}
holder.tvLabel.setText(labelPost);
if ((position >= getItemCount() - 1))
load();
}
public abstract void load();
#Override
public int getItemCount() {
return mListPost.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView ivImagePost;
public TextView tvTitle;
public LinearLayout llItemPost;
public TextView tvLabel;
public ViewHolder(View itemView) {
super(itemView);
ivImagePost = (ImageView) itemView.findViewById(R.id.iv_image_post);
tvTitle = (TextView) itemView.findViewById(R.id.tv_blog_title);
llItemPost = (LinearLayout) itemView.findViewById(R.id.ll_item_post);
tvLabel = (TextView) itemView.findViewById(R.id.textview_label_adapter);
}
}
public static List<String> extractUrls(String input) {
List<String> result = new ArrayList<String>();
Pattern pattern = Pattern.compile(
"\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" +
"(\\w+:\\w+#)?(([-\\w]+\\.)+(com|org|net|gov" +
"|mil|biz|info|mobi|name|aero|jobs|museum" +
"|travel|[a-z]{2}))(:[\\d]{1,5})?" +
"(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" +
"((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" +
"(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" +
"(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
result.add(matcher.group());
}
return result;
}
}
This code of MainActivity.java
private void getListPost(){
mSwipeRefreshLayout.setRefreshing(true);
String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);
BloggerApiService apiService = BloggerApiClient.getClient().create(BloggerApiService.class);
Call<ListPostModel> call = apiService.getListPost(GlobalVariable.APP_KEY_V3);
call.enqueue(new Callback<ListPostModel>() {
#Override
public void onResponse(Call<ListPostModel> call, Response<ListPostModel> response) {
ListPostModel listpost = response.body();
initDataView(listpost);
mSwipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<ListPostModel> call, Throwable t) {
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
/**
* this method used for post (next page)
*/
private void getNextListPost(){
mSwipeRefreshLayout.setRefreshing(true);
String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);
BloggerApiService apiService = BloggerApiClient.getClient().create(BloggerApiService.class);
Call<ListPostModel> call = apiService.getNexPageListPost(GlobalVariable.APP_KEY_V3,nextPageToken);
call.enqueue(new Callback<ListPostModel>() {
#Override
public void onResponse(Call<ListPostModel> call, Response<ListPostModel> response) {
ListPostModel listpost = response.body();
initDataView2(listpost);
mSwipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<ListPostModel> call, Throwable t) {
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onRefresh() {
mListPost.clear();
getListPost();
}
private void initDataView(ListPostModel listpost){
GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
mListPost.addAll(listpost.getListItemsPost());
mPostAdapter = new ListPostAdapter(mListPost, this) {
#Override
public void load() {
ItemPostModel item = mListPost.get(mListPost.size()-1);
getNextListPost();
}
};
mRecyclerviewPost.setAdapter(mPostAdapter);
//mPostAdapter.notifyDataSetChanged();
mRecyclerviewPost.setHasFixedSize(true);
mGridViewLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mGridViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
mRecyclerviewPost.setLayoutManager(mGridViewLayoutManager);
}
/**
* this method used for set view (next page)
* #param listpost
*/
private void initDataView2(ListPostModel listpost){
GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);
List<ItemPostModel> itemNextPost = listpost.getListItemsPost();
// itemNextPost.addAll(mListPost);
mListPost.addAll(itemNextPost);
mPostAdapter = new ListPostAdapter(mListPost, this) {
#Override
public void load() {
ItemPostModel item = mListPost.get(mListPost.size()-1);
if(nextPageToken==null){
}else{
getNextListPost();
}
}
};
mRecyclerviewPost.setAdapter(mPostAdapter);
mRecyclerviewPost.setHasFixedSize(true);
mGridViewLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mGridViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
mRecyclerviewPost.setLayoutManager(mGridViewLayoutManager);
an
}
Any suggestion will be appreciated.
The problem with the code is, your resetting the complete data again into your adapter and setting it to RecyclerView again, That's why it is re instanced everything in RecyclerView and i.e scrolling to top. Instead of that you can try something like just add /append the updated data into the list ( where you holds the data ) and then just call the adapter.notifyDataSetChanged(); method. automatically it will add the updated data and you no need to set the recycler view again.
Probably for your case you need to change your initDataView2() mehtod like below
private void initDataView2(ListPostModel listpost){
GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
mListPost.addAll(listpost.getListItemsPost());\
mPostAdapter .notifyDataSetChanged();
}
For nextPageToken thing you can move into your main code onCreate() or the initDataView() method where you already have the adapter initialization
like this,
private void initDataView(ListPostModel listpost){
GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);
mListPost.addAll(listpost.getListItemsPost());
mPostAdapter = new ListPostAdapter(mListPost, this) {
#Override
public void load() {
ItemPostModel item = mListPost.get(mListPost.size()-1);
if(nextPageToken==null){
}else{
getNextListPost();
}
}
};
mRecyclerviewPost.setAdapter(mPostAdapter);
//mPostAdapter.notifyDataSetChanged();
mRecyclerviewPost.setHasFixedSize(true);
mGridViewLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mGridViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
mRecyclerviewPost.setLayoutManager(mGridViewLayoutManager);
}
I hope it will work :)

How to start activity from onClick on RecyclerView in actvity

Hello Everyone I am trying to start activity when I click on RecyclerView , it is started when I add the code in the Custom Adapter , but when I write it in Activity it Just give me the position on Log ..
so any help
here is the code OnClick in activity and that's what I tried to do
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = v.getContext();
Intent intent = new Intent(context.getApplicationContext() , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.getApplicationContext().startActivity(intent);
finish();
}
here is the activity
package com.abed.montage.hijabapptest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class FrameListActivity extends AppCompatActivity implements PhotoRecyclerViewAdapter.MyClickListener {
private RecyclerView photoRecyclerView;
private RecyclerView.Adapter mAdapter;
private List<Integer> framePhotoList ;
List<PhotoClass> results ;
private static String LOG_TAG = "CardViewActivity";
String positionId ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame_list);
photoRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
photoRecyclerView.setHasFixedSize(true);
int numberOfColumns = 2;
// mLayoutManager = new LinearLayoutManager();
photoRecyclerView.setLayoutManager(new GridLayoutManager(this , numberOfColumns));
mAdapter = new PhotoRecyclerViewAdapter(getDataSet() , this);
photoRecyclerView.setAdapter(mAdapter);
}
#Override
protected void onResume() {
super.onResume();
((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private List<PhotoClass> getDataSet() {
fillPhotoFrameList();
results = new ArrayList<>();
for (int index = 0; index < framePhotoList.size(); index++) {
PhotoClass obj = new PhotoClass();
obj.setImage(framePhotoList.get(index));
results.add(index, obj);
}
return results;
}
private void fillPhotoFrameList(){
framePhotoList = new ArrayList<>();
framePhotoList.add(R.drawable.frame_1);
framePhotoList.add(R.drawable.frame_2);
framePhotoList.add(R.drawable.frame_3);
framePhotoList.add(R.drawable.frame_4);
framePhotoList.add(R.drawable.frame_5);
framePhotoList.add(R.drawable.frame_6);
framePhotoList.add(R.drawable.frame_7);
framePhotoList.add(R.drawable.frame_8);
framePhotoList.add(R.drawable.frame_2);
framePhotoList.add(R.drawable.frame_10);
framePhotoList.add(R.drawable.frame_11);
framePhotoList.add(R.drawable.frame_12);
framePhotoList.add(R.drawable.frame_13);
framePhotoList.add(R.drawable.frame_14);
framePhotoList.add(R.drawable.frame_15);
framePhotoList.add(R.drawable.frame_16);
framePhotoList.add(R.drawable.frame_17);
framePhotoList.add(R.drawable.frame_18);
framePhotoList.add(R.drawable.frame_19);
framePhotoList.add(R.drawable.frame_20);
}
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = v.getContext();
Intent intent = new Intent( context , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.startActivity(intent);
finish();;
}
public String createImageFromBitmap(Bitmap bitmap , String fileNameForSave) {
String fileName = fileNameForSave;//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
}
and here is the Adapter ....
package com.abed.montage.hijabapptest;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.List;
/**
* Created by hp15-AY on 02/27/2017.
*/
public class PhotoRecyclerViewAdapter extends RecyclerView.Adapter<PhotoRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<PhotoClass> mDataset;
private static MyClickListener myClickListener;
Context context;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
ImageView photo;
public DataObjectHolder(View itemView) {
super(itemView);
photo = (ImageView) itemView.findViewById(R.id.photo);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
// Context context = v.getContext();
// Intent intent = new Intent(context, FinalActivity.class);
// context.startActivity(intent);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public PhotoRecyclerViewAdapter(List<PhotoClass> myDataset , Context context) {
this.context = context ;
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_photo, parent, false);
view.setBackgroundResource(R.drawable.rounded_frame);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.photo.setImageBitmap(BitmapFactory.decodeResource(context.getResources() ,mDataset.get(position).getImage()));
}
public void addItem(PhotoClass dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
and here is the class ...
public class PhotoClass {
int id;
int image ;
public PhotoClass() {
}
public void setId(int id) {
this.id = id;
}
public void setImage(int image) {
this.image = image;
}
public int getId() {
return id;
}
public int getImage() {
return image;
}
}
FinalActivity OnCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Activity Created");
setContentView(R.layout.activity_final);
mGlobal = (Global) getApplicationContext();
imageViewThumbnail = (ImageView) findViewById(R.id.selectedimage);
saveIcon = (ImageView) findViewById(R.id.imageSave);
filterIcon = (ImageView) findViewById(R.id.editImage);
mImageViewFrame = (ImageView) findViewById(R.id.frameimage);
// mInterstitialAd = new InterstitialAd(this);
// mInterstitialAd.setAdUnitId(getApplicationContext().getString(R.string.admob_intersitials));
// mAdRequest= new AdRequest.Builder().build();
// mInterstitialAd.loadAd(mAdRequest);
imageViewThumbnail.setOnTouchListener(new MultiTouchListener());
mDialog = Utils.SetProgressBar(mDialog, FinalActivity.this);
mDialog.dismiss();
loadImage(imageViewThumbnail, mGlobal.getPath());
String result = getIntent().getStringExtra("resultpos");
pos = Integer.parseInt(result);
Log.w("Position===", "" + pos);
String imagevalue = frames[pos];
Log.w("imagename=====++++", "" + imagevalue);
int resID = getResources().getIdentifier(imagevalue, "drawable", getPackageName());
mImageViewFrame.setImageResource(resID);
saveIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// }
RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
SaveImage(bm);
}
});
filterIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
EditImage(bm);
}
});}
loadImage Function :
private void loadImage(ImageView iv, final String path) {
if(!isAirplaneModeOn(this.getApplicationContext())) {
Picasso.with(FinalActivity.this)
.load(Uri.fromFile(new File(path)))
.fit()
.centerInside()
.into(iv, new Callback() {
#Override
public void onSuccess() {
Log.i(TAG, "Picasso Success Loading Thumbnail - " + path);
}
#Override
public void onError() {
Log.i(TAG, "Picasso Error Loading Thumbnail Small - " + path);
}
});
}
else{
//do something else?
}
File image = new File(path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
engrave(bitmap);
// bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
}
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static boolean isAirplaneModeOn(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
} else {
return Settings.Global.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
}
I used setOnClickListener in itemView in the onBindViewHolder.
the itemView is like the container of all things that has the item...
public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyClassViewHolder> {
....
....
....
#Override
public void onBindViewHolder(#NonNull final MyClassViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , NewActivity.class);
context.startActivity(intent);
}
});
}
....
....
}
This is another example that I find
I created the setOnClickListener on view in onCreateViewHolder
public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyClassViewHolder> {
....
....
....
#NonNull
#Override
public MyClassViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.row_item_example, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Click in oncReateViewHolder");
}
});
return new SolicitudViewHolder(view);
}
....
....
}
Try this:
in your onResume(): you are already attaching setOnItemClickListener into the PhotoRecyclerViewAdapter
#Override
protected void onResume() {
super.onResume();
((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
Intent intent = new Intent(FrameListActivity.this , FinalActivity.class);
intent.putExtra("resultpos", "" + position);
startActivity(intent);
}
});
}
Use this:
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = FrameListActivity.this;
Intent intent = new Intent(context , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.startActivity(intent);
finish();
}
Hope this helps.
As far as I know, the proper way to attach an onClickListener to a recyclerView, is to do so in the onBindViewHolder method as mentioned as the first option in the answer below. This method binds the properties to each of the recyclerview item, therefore the onClickListener could also be attached similarly.

Save State of RecyclerView

I am making a app with RecylerView populated with data form an online server. It has a custom layout with a favorite button that when clicked the icon changes.I have a problem trying to save state of a selected view on the RecyclerView. The RecyclerView does not save the selected state on scrolling back up. Kindly help.
Model Class
package com.smartdevelopers.kandie.nicedrawer.newsModel;
/**
* Created by 4331 on 25/09/2015.
*/
public class Latest {
public String excerpt;
public String articleImage;
public String articleUrl;
public boolean mfavourite;
public boolean isFavourite(){
return mfavourite;
}
public String getArticleUrl() {
return articleUrl;
}
public void setArticleUrl(String articleUrl) {
this.articleUrl = articleUrl;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getArticleImage() {
return articleImage;
}
public void setArticleImage(String articleImage) {
this.articleImage = articleImage;
}
}
Adapter
package com.smartdevelopers.kandie.nicedrawer.newsAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.smartdevelopers.kandie.nicedrawer.R;
import com.smartdevelopers.kandie.nicedrawer.ReadArticleActivity;
import com.smartdevelopers.kandie.nicedrawer.newsModel.Latest;
import com.smartdevelopers.kandie.nicedrawer.util.SharedPreferenceRecycler;
import java.util.HashMap;
import java.util.List;
/**
* Created by 4331 on 29/09/2015.
*/
public class OtherNewsAdapter extends RecyclerView.Adapter<OtherNewsAdapter.ViewHolder> {
private List<Latest> feedItemList;
private Context mContext;
private static final String TAG = "ActivityGplus";
SharedPreferenceRecycler sharedPreference = new SharedPreferenceRecycler();
public OtherNewsAdapter(Context context, List<Latest> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_other_news, null);
ViewHolder mh = new ViewHolder(v);
return mh;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final Latest feedItem = feedItemList.get(i);
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.placeholder)
.showImageOnFail(R.drawable.placeholder)
.showImageOnLoading(R.drawable.placeholder).build();
//download and display image from url
imageLoader.displayImage(feedItem.getArticleImage(), viewHolder.thumbnail, options);
// Glide.with(mContext).load(feedItem.getArticleImage())
// .error(R.drawable.placeholder)
// .placeholder(R.drawable.placeholder)
// .into(viewHolder.thumbnail);
viewHolder.title.setText(Html.fromHtml(feedItem.getExcerpt()));
viewHolder.articleUrl.setText(Html.fromHtml(feedItem.getArticleUrl()));
viewHolder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ReadArticleActivity.class);
intent.putExtra("articleUrl", viewHolder.articleUrl.getText().toString());
mContext.startActivity(intent);
}
});
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(feedItem)) {
viewHolder.favImage.setImageResource(R.drawable.heart_red);
viewHolder.favImage.setSelected(true);
viewHolder.favImage.setTag("red");
hashMap.get(i);
}
else {
viewHolder.favImage.setImageResource(R.drawable.heart_grey);
viewHolder.favImage.setSelected(false);
viewHolder.favImage.setTag("grey");
}
viewHolder.title.setTag(viewHolder);
viewHolder.thumbnail.setId(R.id.otherImage);
viewHolder.articleUrl.setTag(viewHolder);
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
OtherNewsRowHolder holder = (OtherNewsRowHolder) view.getTag();
int position = holder.getPosition();
Latest feedItem = feedItemList.get(position);
Toast.makeText(mContext, feedItem.getExcerpt(), Toast.LENGTH_SHORT).show();
}
};
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Latest checkProduct) {
boolean check = false;
List<Latest> favorites = sharedPreference.getFavorites(mContext);
if (favorites != null) {
for (Latest product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView thumbnail, favImage;
protected TextView title,articleUrl;
public ViewHolder(View itemView) {
super(itemView);
this.thumbnail = (ImageView) itemView.findViewById(R.id.otherImage);
this.title = (TextView) itemView.findViewById(R.id.otherExcerpt);
this.articleUrl=(TextView)itemView.findViewById(R.id.otherUrl);
this.favImage = (ImageView) itemView.findViewById(R.id.imgbtn_favorite);
favImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String tag = favImage.getTag().toString();
if(!favImage.isSelected()) {
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(mContext, feedItemList.get(getItemCount() - 1));
// Toast.makeText(mContext, mContext.getResources().getString(R.string.add_favr),
// Toast.LENGTH_SHORT).show();
//SnackBack
SnackbarManager.show(
Snackbar.with(mContext)
.text(R.string.add_favr)
.textColor(Color.WHITE)
.color(Color.RED)
.duration(Snackbar.SnackbarDuration.LENGTH_SHORT));
//End of SnackBack
favImage.setTag("red");
favImage.setImageResource(R.drawable.heart_red);
}
}
else {
sharedPreference.removeFavorite(mContext, feedItemList.get(getItemCount() - 1));
favImage.setTag("grey");
favImage.setImageResource(R.drawable.heart_grey);
//SnackBack
SnackbarManager.show(
Snackbar.with(mContext)
.text(R.string.remove_favr)
.textColor(Color.WHITE)
.color(Color.RED) .duration(Snackbar.SnackbarDuration.LENGTH_SHORT).animation(false));
//End of SnackBack
}
}
}
}
I ran into this problem a couple of days ago - the reason is that you have not updated your feedItemList with the applicable changes. If you update the list by setting some of the member variables (like setExcerpt()) of the Latest class once it has change, your recyclerview will work properly.

Categories

Resources