RecyclerView setting a image in the wrong place - android

I have a recycle view, 2 differents adapter and I have a default Image. The problem is that when a user doesn't have an image, sometimes it loads an other user image instead of the default image.
(I also check if user doesn't have imagelink, it reset the default image programatically... so it should work => no problem for the text etc, only the image!)
Here is the xml code for one adapter (pretty much the same for the other):
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rella_rc_item_friend"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="8dp"
card_view:cardBackgroundColor="#color/colorCardView"
card_view:cardCornerRadius="5dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="10dp"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
card_view:cardBackgroundColor="#color/grey_200"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/icon_avata"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_margin="10dp"
android:src="#drawable/default_avata"
android:layout_weight="1"
app:civ_border_color="#color/colorPrimary"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_weight="5"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity=""
android:layout_weight="1"
android:orientation="horizontal"
android:paddingTop="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:layout_toLeftOf="#id/txtTime"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtTime"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity=""
android:layout_weight="1">
<TextView
android:id="#+id/txtMessage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="end"
android:gravity="center_vertical"
android:lines="1"
android:paddingBottom="10dp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
class ListContactAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<MessageInfo> ListContacts;
private Context context;
FirebaseAuth mAuth;
String currentuserid;
SimpleDateFormat DateFormat = new SimpleDateFormat("dd MMMM, yyyy");
SimpleDateFormat TimeFormat = new SimpleDateFormat("hh:mm a");
SimpleDateFormat YearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat DayFormat = new SimpleDateFormat("MMMM dd, hh:mm a");
FusionProject Fobj = new FusionProject();
DatabaseReference VuRef;
CommunActivit obj = new CommunActivit();
public ListContactAdapter(Context context,List<MessageInfo> listGroup){
this.context = context;
this.ListContacts = listGroup;
mAuth = FirebaseAuth.getInstance();
currentuserid = mAuth.getUid();
VuRef = FirebaseDatabase.getInstance().getReference().child("Seen");
}
public ListContactAdapter ()
{
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_contact_me, parent, false);
return new ItemForMe(view);
} else if (viewType == 2) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_friend, parent, false);
return new ItemForMyFriend(view);
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position)
{
String username = ListContacts.get(position).getFriendUsername();
String last_message = ListContacts.get(position).getLastMessage();
String time = ListContacts.get(position).getTime() ;
String image = ListContacts.get(position).getFriendPicture();
String FriendID = ListContacts.get(position).getFriendID();
Date Today = new Date(System.currentTimeMillis());
long yourmilliseconds = (Long.parseLong(time));
Date resultdate = new Date(yourmilliseconds);
String test = DateFormat.format(resultdate).toString(); /**DATE**/
String test2 = TimeFormat.format(resultdate).toString(); /**TIME**/
String test3 = YearFormat.format(resultdate);
String test4 = DayFormat.format(resultdate);
if (holder instanceof ItemForMe)
{
((ItemForMe) holder).username_friend.setText(username);
((ItemForMe) holder).last_message.setText("Me : " +last_message);
if (DateFormat.format(Today).equals(test))
{
((ItemForMe) holder).time.setText(test2);
}
else
{
if (YearFormat.format(Today).equals(test3))
{
String cap = test4.substring(0, 1).toUpperCase() + test4.substring(1);
((ItemForMe) holder).time.setText(cap);
}
else {
((ItemForMe) holder).time.setText(test);
}
}
if (!image.equals("")) {
Picasso.get().load(image).into(((ItemForMe) holder).Profil_friend);
}
else
{
((ItemForMe) holder).Profil_friend.setImageResource(R.drawable.default_avata);
}
VuRef.child(ListContacts.get(position).getIDMessage()).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.getValue().toString().equals("Vu"))
{
((ItemForMe) holder).imageView_vu.setImageDrawable(holder.itemView.getContext().getResources().getDrawable(R.drawable.icons8_seen));
}
else
{
((ItemForMe) holder).imageView_vu.setImageDrawable(holder.itemView.getContext().getResources().getDrawable(R.drawable.icons8_not_vu));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else
{
((ItemForMyFriend) holder).username_friend.setText(username);
((ItemForMyFriend) holder).last_message.setText(last_message);
if (DateFormat.format(Today).equals(test))
{
((ItemForMyFriend) holder).time.setText(test2);
}
else
{
if (YearFormat.format(Today).equals(test3))
{
String cap = test4.substring(0, 1).toUpperCase() + test4.substring(1);
((ItemForMyFriend) holder).time.setText(cap);
}
else {
((ItemForMyFriend) holder).time.setText(test);
}
}
if (!image.equals("")) {
Picasso.get().load(image).into(((ItemForMyFriend) holder).Profil_friend);
}
else
{
((ItemForMyFriend) holder).Profil_friend.setImageResource(R.drawable.default_avata);
}
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent groupeIntent = new Intent(v.getContext(), ChatActivity.class);
Fobj.writefile("FriendID",ListContacts.get(position).getFriendID(), context);
Fobj.writefile("MessageID",ListContacts.get(position).getIDMessage(), context);
Fobj.writefile("FriendName",ListContacts.get(position).getFriendUsername(), context);
Fobj.writefile("FriendPicture",ListContacts.get(position).getFriendPicture(), context);
obj.setsIDFRIEND(ListContacts.get(position).getFriendID());
obj.setsIDMESSAGE(ListContacts.get(position).getIDMessage());
obj.setsFRIENDName(ListContacts.get(position).getFriendUsername());
context.startActivity(groupeIntent);
}
});
}
#Override
public int getItemViewType(int position) {
String test = ListContacts.get(position).getSenderID();
if (test.equals(currentuserid))
{
return 1;
}
else
{
return 2;
}
}
#Override
public int getItemCount() {
return ListContacts.size();
}
}
Retrieve data :
List_of_friends.add(0,new MessageInfo(ID, newgroup, profilepicture,MessageID, Date, Message, Time, SenderID));
adapter.notifyDataSetChanged();
So as you can see on this image, the first message wasn't loaded correctly. The user doesn't have an image but get the image user of one other user...
If anyone can help, would be nice !
I have debugged and it seems that it sometimes go more times in the holder than in the listsize.

You can try with Glide like this.
Add this in app.gradle file
implementation "com.github.bumptech.glide:glide:4.8.0"
annotationProcessor "com.github.bumptech.glide:compiler:4.8.0"
Replace Picasso with glide like this
if (!image.trim().isEmpty())
Glide.with(context).load(image).into(((ItemForMyFriend) holder).Profil_friend);

Try loading image like this in your recyclerview
if (!image.trim().isEmpty())
Picasso.with(context).load(image)
.error(R.drawable.default_avata)
.placeholder(R.drawable.default_avata)
.into(((ItemForMyFriend) holder).Profil_friend);

Related

How to properly implement a nested recyclerview, child recyclerviews behaving oddly

I am developing a chat application. The chat messages consists of normal text messages and sometimes it can be a list of items in a recyclerview.
So I've implemented nested Recyclerview. So what happens is in the json response if the message is just a normal text is a textview will be displayed but the message contains a URL then the horizantal recyclerview is shown in place of textview.
The problem is if in the json reponse let's say there are 10 messages and in that 10, 4 of them are URL's so i should be seeing 6 normal texts and 4 Recyclerviews. But the nested recyclerview is behaving very oddly sometimes it doesn't even display, sometimes i can see 2 Recyclerviews and sometimes 4 of them but with the same URL (same list of items).
I don't what i am doing wrong. can someone take a look at the code and tell me what's wrong?
My Parent(Vertical) Recyclerview layout
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="messageViewModel"
type="com.sukshi.sukshichat.viewmodel.MessageFragmViewModel"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.fragment.MessagesFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#ffffff"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:layout_marginTop="0dp"
android:layout_below="#+id/kjk"
android:layout_above="#+id/rv_message_container"
tools:listitem="#layout/test"
/>
</RelativeLayout>
</layout>
Vertical Recyclerview child layout
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import
alias="cons"
type="com.sukshi.sukshichat.utils.ConstantsFirebase"/>
<import type="android.view.View"/>
<variable
name="messageViewModel"
type="com.sukshi.sukshichat.viewmodel.MessageAdapterViewModel"/>
</data>
<android.support.percent.PercentRelativeLayout
android:layout_height="wrap_content"
android:id="#+id/rv_container"
android:layout_width="wrap_content">
<android.support.v7.widget.RecyclerView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:id="#+id/nested_recyclerview"
>
</android.support.v7.widget.RecyclerView>
<RelativeLayout
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:id="#+id/sender"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="4dp"
app:layout_widthPercent="70%">
<hani.momanii.supernova_emoji_library.Helper.EmojiconTextView
android:layout_height="wrap_content"
android:id="#+id/tv_item_message"
android:layout_width="wrap_content"
android:maxWidth="300dp"
android:textColor="#ffffff"
android:text="#{messageViewModel.message}"
android:background="#drawable/chat_sender"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:padding="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{messageViewModel.time}"
android:layout_marginRight="4dp"
android:id="#+id/tv_item_message_time"
android:layout_alignBottom="#+id/tv_item_message"
android:layout_toLeftOf="#+id/tv_item_message"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxHeight="#dimen/item_message_max_height"
android:maxWidth="#dimen/item_message_max_width"
android:onClick="#{messageViewModel::onItemClick}"
android:scaleType="centerCrop"
android:transitionName="shared"
android:visibility="#{messageViewModel.typeMessage ? View.GONE : View.VISIBLE}"
app:mapLocation="#{messageViewModel.mapLocation}"
app:photoUrlMessage="#{messageViewModel.message}"/>
</FrameLayout>
</RelativeLayout>
<RelativeLayout
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:id="#+id/reciever"
android:layout_marginBottom="4dp"
app:layout_widthPercent="70%">
<hani.momanii.supernova_emoji_library.Helper.EmojiconTextView
android:layout_height="wrap_content"
android:id="#+id/tv_item_message1"
android:layout_width="wrap_content"
android:background="#drawable/chat_recieve"
android:maxWidth="300dp"
android:textColor="#000000"
android:text="#{messageViewModel.message}"
android:padding="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/show_garments2"
android:text="Show Garments"
android:visibility="gone"
android:background="#drawable/chat_recieve"
android:elevation="10dp"
android:paddingLeft="10dp"
android:textColor="#000000"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{messageViewModel.time}"
android:id="#+id/tv_item_message_time11"
android:layout_marginLeft="4dp"
android:layout_alignBottom="#+id/tv_item_message1"
android:layout_toRightOf="#+id/tv_item_message1"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_image1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxHeight="#dimen/item_message_max_height"
android:maxWidth="#dimen/item_message_max_width"
android:onClick="#{messageViewModel::onItemClick}"
android:scaleType="centerCrop"
android:transitionName="shared"
android:visibility="#{messageViewModel.typeMessage ? View.GONE : View.VISIBLE}"
app:mapLocation="#{messageViewModel.mapLocation}"
app:photoUrlMessage="#{messageViewModel.message}"/>
</FrameLayout>
</RelativeLayout>
</android.support.percent.PercentRelativeLayout>
</layout>
Vertical Recyclerview adapter
private void initializeFirebase() {
if (valueUserListener == null) {
valueUserListener = createFirebaseUsersListeners();
}
mRefUsers = FirebaseDatabase.getInstance().getReference(ConstantsFirebase.FIREBASE_LOCATION_USERS);
mRefUsers.keepSynced(true);
mRefUsers.addValueEventListener(valueUserListener);
Query messagesRef = FirebaseDatabase.getInstance()
.getReference(ConstantsFirebase.FIREBASE_LOCATION_CHAT)
.child(mChildChatKey)
.orderByKey().limitToLast(50);
messagesRef.keepSynced(true);
attachMessagesToRecyclerView(messagesRef);
}
private void attachMessagesToRecyclerView(final Query messagesReference) {
mAdapter = new FirebaseRecyclerAdapter<Message, MessageItemHolder>(Message.class,
R.layout.test123, MessageItemHolder.class, messagesReference) {
#Override
public MessageItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Test123Binding adapterItemMessageBinding = DataBindingUtil.inflate(LayoutInflater
.from(parent.getContext()), viewType, parent, false);
return new MessageItemHolder(adapterItemMessageBinding);
}
#Override
protected void populateViewHolder(final MessageItemHolder viewHolder, final Message message, int position) {
int index = mUsersEmails.indexOf(message.getEmail());
if (index != -1) {
viewHolder.bindMessage(mUsers.get(index), message, MessagesFragment.this);
}
if (viewHolder.mAdapterItemMessageBinding.getMessageViewModel().isSender()){
viewHolder.mAdapterItemMessageBinding.reciever.setVisibility(View.GONE);
viewHolder.mAdapterItemMessageBinding.sender.setVisibility(View.VISIBLE);
}else {
viewHolder.mAdapterItemMessageBinding.reciever.setVisibility(View.VISIBLE);
viewHolder.mAdapterItemMessageBinding.sender.setVisibility(View.GONE);
}
String http = message.getMessage();
// if (htttpmessage != null){
if (http.contains("google") && message.getType() == 0){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setLayoutParams(params);
filterLink = message.getMessage();
ListOfdataAdapter.clear();
JSON_HTTP_CALL(filterLink);
nestedRecyclerview(viewHolder);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setVisibility(View.VISIBLE);
viewHolder.mAdapterItemMessageBinding.tvItemMessage1.setVisibility(View.INVISIBLE);
// filterLink = message.getFilterLink();
}else{
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(0,
0);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setLayoutParams(params);
viewHolder.bindMessage(mUsers.get(index), message, MessagesFragment.this);
viewHolder.mAdapterItemMessageBinding.tvItemMessage1.setVisibility(View.VISIBLE);
}
if (message.getType() == 1 || message.getType() == 2){
viewHolder.mAdapterItemMessageBinding.tvItemMessage.setVisibility(View.INVISIBLE);
}else {
viewHolder.mAdapterItemMessageBinding.tvItemMessage.setVisibility(View.VISIBLE);
}
/* viewHolder.mAdapterItemMessageBinding.showGarments2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showpDialog();
filterLink = message.getMessage();
ListOfdataAdapter.clear();
JSON_HTTP_CALL(filterLink);
}
});
*/
}
};
mFragmentMessagesBinding.rvMessage.setAdapter(mAdapter);
mFragmentMessagesBinding.rvMessage.getAdapter().registerAdapterDataObserver(
new RecyclerView.AdapterDataObserver() {
#Override public void onItemRangeInserted(int position, int itemCount) {
super.onItemRangeInserted(position, itemCount);
mFragmentMessagesBinding.rvMessage.scrollToPosition(position);
}
});
}
So whenever there is a URl in the message key below method will be called
public void JSON_HTTP_CALL(String url){
RequestOfJSonArray = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
UploadImage GetDataAdapter2 = new UploadImage();
JSONObject json = null;
try {
hidepDialog();
json = array.getJSONObject(i);
GetDataAdapter2.setBrand_name(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImage(json.getString(Image_URL_JSON));
GetDataAdapter2.setGarment_price(json.getString(garment_price));
GetDataAdapter2.setGarment_name(json.getString(garment_name));
GetDataAdapter2.setImage_full(json.getString(image_full));
GetDataAdapter2.setDesc_text(json.getString(desc_text));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
// showFragment();
}
}
Horizantal Recyclerview adapter
final WrapContentLinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(WrapContentLinearLayoutManager.HORIZONTAL);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setLayoutManager(linearLayoutManager);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setHasFixedSize(true);
//mFragmentMessagesBinding.recyclerview1.addItemDecoration(new PaddingItemDecoration(size));
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setItemAnimator(new DefaultItemAnimator());
DialogRecyclerViewAdapter rvAdapter = new DialogRecyclerViewAdapter(ListOfdataAdapter, getActivity());
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setAdapter(rvAdapter);
rvAdapter.notifyDataSetChanged();
Horizantal Recyclerview Adapter
public class DialogRecyclerViewAdapter extends RecyclerView.Adapter<DialogRecyclerViewAdapter.ViewHolder> {
Context context;
List<UploadImage> dataAdapters;
private SharedPreferences.Editor mSharedPrefEditor;
ImageLoader imageLoader;
public DialogRecyclerViewAdapter(List<UploadImage> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
final UploadImage dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImage(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.drawable.loading_1,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView, garment_price, size;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
Vertical Recyclerview ViewHolder
public static class MessageItemHolder extends RecyclerView.ViewHolder {
private Test123Binding mAdapterItemMessageBinding;
public MessageItemHolder(Test123Binding adapterItemMessageBinding) {
super(adapterItemMessageBinding.rvContainer);
mAdapterItemMessageBinding = adapterItemMessageBinding;
}
public void bindMessage(User user, Message message, MessageAdapterViewModelContract contract) {
if (mAdapterItemMessageBinding.getMessageViewModel() == null) {
mAdapterItemMessageBinding.setMessageViewModel(new MessageAdapterViewModel(user,
encodedMail, message, contract));
} else {
mAdapterItemMessageBinding.getMessageViewModel().setUser(user);
mAdapterItemMessageBinding.getMessageViewModel().setMessage(message);
}
}
}

How to update imageview from the parent recyclerview after click on nested recyclerview's imageview

Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.
Parent Recyclerview Adapter:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String itemTitle = dataList.get(i).getTitle();
final String itemDescription = dataList.get(i).getDescription();
ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();
itemRowHolder.itemTitle.setText(Html.fromHtml("<b>" + itemTitle + " </b> " + itemDescription));
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);
itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle, expandImage;
protected ImageView bookmarkImage,largeImage;
protected RecyclerView recyclerSmallImageList;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.title);
this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
this.largeImage = (ImageView) view.findViewById(R.id.large_image);
this.expandImage = (TextView) view.findViewById(R.id.expand);
this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);
}
}
}
Nested Recyclerview Adapter:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SmallImages> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SmallImages singleItem = itemsList.get(i);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
//this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.
/////Adapter class
public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {
private Context mContext;
private int rowLayout;
private List<ModelRouteDetailsUp> dataMembers;
private ArrayList<ModelRouteDetailsUp> arraylist;
private ArrayList<ModelKidDetailsUp> arraylist_kids;
List<String> wordList = new ArrayList<>();
Random rnd = new Random();
int randomNumberFromArray;
private ModelRouteDetailsUp personaldata;
private ProgressDialog pDialog;
private ConnectionDetector cd;
String img_baseurl = "";
String item = "";
public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
this.mContext = mcontext;
this.rowLayout = rowLayout;
this.dataMembers = tripList;
wordList.clear();
this.img_baseurl = img_baseurl;
arraylist = new ArrayList<>();
arraylist_kids = new ArrayList<>();
arraylist.addAll(dataMembers);
cd = new ConnectionDetector(mcontext);
pDialog = KPUtils.initializeProgressDialog(mcontext);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new AdapterTodayTrip.VHItem(v);
}
#Override
public int getItemCount() {
return dataMembers.size();
}
#Override
public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
try {
personaldata = dataMembers.get(position);
if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
}
****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
if (personaldata.getKidlist().size() > 0) {
viewHolder.linear_childview.setVisibility(View.VISIBLE);
viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
viewHolder.id_gallery.removeAllViews();
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(0, 0, 8, 0);
LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < personaldata.getKidlist().size(); i++) {
View view = layoutInflater.inflate(R.layout.view_child_list, null);
view.setLayoutParams(buttonLayoutParams);
RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);
TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
int count = i + 1;
String count1 = "0";
if (count <= 10) {
count1 = "0" + count;
}
tv_count.setText(String.valueOf(count1));
viewHolder.id_gallery.addView(view);
final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
if(!baseurl.isEmpty()) {
iv_circular.setTag(baseurl);
}
if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
bgShape.setColor(Color.parseColor("#A6b1a7a6"));
rl_txt.setVisibility(View.GONE);
//rl_img.setVisibility(View.VISIBLE);
tv_name.setVisibility(View.GONE);
Log.d("aimg_baseurl", baseurl);
try {
Picasso.with(mContext)
.load(baseurl)
.resize(60,60)
.centerCrop()
.into(iv_circular);
iv_circular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url=iv_circular.getTag().toString().trim();
if(!url.isEmpty())
KPUtils.showToastShort(mContext,url);
Picasso.with(mContext)
.load(url)
.resize(60,60)
.centerCrop()
.into(viewHolder.img_child);
}
});
} catch (Exception e) {
}
} else {
}
}
}else{
viewHolder.linear_childview.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
class VHItem extends RecyclerView.ViewHolder {
CardView cv_members;
ImageView img_child;
TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
LinearLayout id_gallery,linear_childview;
public VHItem(View itemView) {
super(itemView);
img_child= (ImageView) itemView.findViewById(R.id.img_child);
cv_members = (CardView) itemView.findViewById(R.id.cv_members);
tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
}
}
}
/////////////////////////// this layout is inflated in every row
view_child_list
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/iv_circular"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#d27959"
app:civ_border_width="1dp" />
<RelativeLayout
android:id="#+id/rl_txt"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="gone">
<com.app.kidpooldriver.helper.CircularTextView
android:id="#+id/tv_name"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="70dp"
android:layout_height="70dp"
android:gravity="center"
android:text="01"
android:textColor="#color/white"
android:textSize="35sp"
tools:ignore="MissingPrefix" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="visible">
<TextView
android:id="#+id/tv_count"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="01"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#ffffff"
android:textStyle="bold"
tools:ignore="MissingPrefix" />
</RelativeLayout>
</FrameLayout>
///// this is the mianlayout which is inflated.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv_members"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin"
android:elevation="#dimen/elevation"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/main_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:layout_marginTop="#dimen/fifteen"
android:orientation="horizontal"
android:paddingLeft="#dimen/ten">
<TextView
android:id="#+id/tv_trip_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#KD09201701"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/twenty"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_trip_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/light_green"
android:gravity="center"
android:padding="5dp"
android:text="In Progress"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
</LinearLayout>
<TextView
android:id="#+id/tv_vehicle_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:text="Route 26U-26D"
android:visibility="gone"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/route_textcolor" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_trip_start_time"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="06:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor" />
<TextView
android:id="#+id/tv_trip_end_time"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="08:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/tv_trip_way"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:visibility="gone"
android:paddingRight="20dp"
android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/grey_textcolor"
android:textStyle="normal" />
<ImageView
android:id="#+id/img_child"
android:layout_width="200dp"
android:layout_gravity="center"
android:layout_height="200dp" />
<LinearLayout
android:id="#+id/linear_childview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fifteen"
android:orientation="horizontal">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:scrollbars="none">
<LinearLayout
android:id="#+id/id_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
<LinearLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/ly_ring_circular"
android:gravity="center_vertical">
<TextView
android:id="#+id/tv_total_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:ignore="MissingPrefix"
fontPath="fonts/Poppins-Bold.ttf"
android:text="+20"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/white"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
/////POJO CLASS &json parsing & Adapter /////
public class ModelRouteDetailsUp {
String city_id;
String area_name;
String area_status;
String is_active;
String areas;
private ArrayList<ModelKidDetailsUp> kidlist;
///////this is the kid list
public ArrayList<ModelKidDetailsUp> getKidlist() {
return kidlist;
}
public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
this.kidlist = kidlist;
}
}
**///json parsing.......**
public boolean addRideDetails(JSONObject jsonObject) {
Boolean flag = false;
String isstatus = "";
if (jsonObject != null && jsonObject.length() > 0) {
try {
JSONArray mainArray = jsonObject.getJSONArray("schedules");
for (int i = 0; i < mainArray.length(); i++) {
ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
JSONObject c = mainArray.getJSONObject(i);
////// For Route Details //////
JSONObject route_details = c.getJSONObject("route_details");
modelRouteDetails.setDs_id(route_details.optString("ds_id"));
modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
modelRouteDetails.setRoute_id(route_details.optString("route_id"));
modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
modelRouteDetails.setStart_time(route_details.optString("start_time"));
modelRouteDetails.setEnd_time(route_details.optString("end_time"));
////// For Allotted Kids //////
JSONArray kidArray = c.getJSONArray("alloted_kids");
ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
if (kidArray.length() > 0) {
for (int j = 0; j < kidArray.length(); j++) {
ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
JSONObject kidObject = kidArray.getJSONObject(j);
kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
genre.add(kidDetailsUp);
}
}
///////add the kidlist here
modelRouteDetails.setKidlist(genre);
////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
//}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
**/////adapter callfrom class**
private void showData() {
if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
rv_trip_list.setAdapter(adapterTodayTrip);
}else {
tv_msg.setVisibility(View.VISIBLE);
}
}
Generally, the solution is to pass custom interface listener into the nested adapter and than the nested adapter will report any time one of his item clicked.
1.
You can create interface like:
public interface INestedClicked {
onNestedItemClicked(Drawable drawble)
}
2.
Pass in the constructor of SectionListDataAdapter a INestedClicked:
SectionListDataAdapter itemListDataAdapter = newSectionListDataAdapter(mContext, singleSectionItems, new INestedClicked() {
#Override
void onNestedItemClicked(Drawable drawble) {
// Do whatever you need after the click, you get the drawable here
}
});
In the constructor of SectionListDataAdapter save the instance of the listener as adapter parameter
private INestedClicked listener;
4.
When nested item clicked report the listener:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onNestedItemClicked(imageView.getDrawable());
}
}

Recycler view onBindViewHolder is repeating a weird pattern

I am working on a messaging app which has swipe option to mute or lock conversations, when we press the mute or lock button, small icons are displayed on Recycler view item, but when I try to mute or even lock a certain message it shows the icons on that item but the icons also appears on elements after every 10 counts.
For Example, If I lock the message at position 1, element at position 12 also shows the same icons, if I removed the icon from the first position, icons from the later position is also removed. Any help would be highly appreciated as I am new to android development and still trying to learn.
Picture:
Recycler view items xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="80dp"
android:id="#+id/sample1"
>
<!-- Bottom View Start-->
<LinearLayout
android:id="#+id/leftWrapper"
android:layout_width="120dp"
android:weightSum="1"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:background="#365cf5"
android:layout_width="60dp"
android:weightSum="1"
android:layout_height="match_parent"
android:id="#+id/panelArchieve"
android:orientation="horizontal">
<ImageView
android:id="#+id/archieve"
android:src="#drawable/archieve"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
<LinearLayout
android:background="#d20909"
android:id="#+id/bottom_wrapper"
android:layout_width="60dp"
android:weightSum="1"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/trash"
android:src="#drawable/trash"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/bottom_wrapper_2"
android:layout_width="120dp"
android:weightSum="1"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:background="#365dea"
android:layout_width="60dp"
android:weightSum="1"
android:layout_height="match_parent"
android:id="#+id/panelLock"
android:orientation="horizontal">
<ImageView
android:id="#+id/lock"
android:src="#drawable/lock"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
<LinearLayout
android:background="#0e9b04"
android:layout_width="60dp"
android:weightSum="1"
android:id="#+id/panelMute"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/mute"
android:src="#drawable/mute"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
</LinearLayout>
<!-- Bottom View End-->
<!-- Surface View Start -->
<LinearLayout
android:padding="10dp"
android:background="#303030"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/rv_img_name"
android:src="#drawable/logo"
android:padding="3dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:layout_marginLeft="10dp"
android:layout_marginTop="9dp"
android:layout_marginRight="2dp"
android:id="#+id/rv_title"
android:textColor="#ffffff"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/rv_img_name"
android:layout_toEndOf="#+id/rv_img_name"
android:maxLines="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/rv_content"
android:textColor="#ffffff"
android:layout_below="#+id/rv_title"
android:layout_alignLeft="#+id/rv_title"
android:layout_alignStart="#+id/rv_title"
android:maxLines="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=""
android:id="#+id/txtTime"
android:textColor="#ffffff"
android:maxLines="1"
android:layout_alignTop="#+id/rv_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="18dp"
android:layout_height="18dp"
android:id="#+id/imgMute"
android:src="#drawable/mute"
android:padding="2dp"
android:layout_marginTop="11dp"
android:layout_toRightOf="#+id/rv_title"
/>
<ImageView
android:layout_width="18dp"
android:layout_height="18dp"
android:id="#+id/imgLock"
android:src="#drawable/lock"
android:padding="2dp"
android:layout_marginTop="11dp"
android:layout_toRightOf="#+id/imgMute" />
</RelativeLayout>
</LinearLayout>
<!-- Surface View End -->
</com.daimajia.swipe.SwipeLayout>
RecyclerViewAdapter
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
//final int position = Texty.position;
final tblMsgs name = mDataset.get(position);
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
}
#Override
public void onClose(SwipeLayout layout) {
viewHolder.btnDel.setTag("trash");
viewHolder.btnDel.setImageResource(R.drawable.trash);
}
});
//Double click
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
//Toast.makeText(mContext, "Position: " + position, Toast.LENGTH_SHORT).show();
}
});
//Open conversation.
viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(viewHolder.swipeLayout.getOpenStatus() == SwipeLayout.Status.Open) {
mItemManger.closeAllItems();
viewHolder.btnDel.setTag("trash");
viewHolder.btnDel.setImageResource(R.drawable.trash);
}
else{ //Open conversation
mItemManger.closeAllItems();
Toast.makeText(mContext, " onClick : " + position, Toast.LENGTH_SHORT).show();
}
}
});
//Delete
viewHolder.panelDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (viewHolder.btnDel.getTag().equals("trash")){
viewHolder.btnDel.setTag("del");
viewHolder.btnDel.setImageResource(R.drawable.delete);
YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.trash));
}
else if (viewHolder.btnDel.getTag().equals("del")){
viewHolder.btnDel.setTag("trash");
//viewHolder.btnDel.setImageResource(R.drawable.trash);
ds.deleteChat(viewHolder.textViewPos.getTag().toString());
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataset.size());
mItemManger.closeAllItems();
}
}
});
//Mute/Unmute
viewHolder.panelMute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Mute unmute pos: " + position, Toast.LENGTH_SHORT).show();
if (viewHolder.btnMute.getTag().equals("bell")){
mItemManger.closeAllItems();
viewHolder.imgMute.setVisibility(View.GONE);
viewHolder.btnMute.setTag("mute");
viewHolder.btnMute.setImageResource(R.drawable.mute);
ds.unMute(name.getrNumber());
}
else{
//Save Sender Settings
ds.open();
if(ds.selectCount_tblSender(name.getrNumber()) == 0){
//Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
tblSender sndr = new tblSender();
sndr.setNumber(name.getrNumber());
ds.create_tblSender(sndr);
}
mItemManger.closeAllItems();
viewHolder.imgMute.setImageResource(R.drawable.mute);
viewHolder.imgMute.setVisibility(View.VISIBLE);
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.imgMute));
viewHolder.btnMute.setTag("bell");
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.mute));
ds.mute(name.getrNumber());
viewHolder.btnMute.setImageResource(R.drawable.bell);
}
//mItemManger.closeAllItems();
//Toast.makeText(view.getContext(), "Deleted " + viewHolder.textViewPos.getText().toString() + "!", Toast.LENGTH_SHORT).show();
}
});
//Lock / Unlock
viewHolder.panelLock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (viewHolder.btnLock.getTag().equals("locked")){
//Save Sender Settings
ds.open();
if(ds.selectCount_tblSender(viewHolder.textViewPos.getTag().toString()) == 0){
//Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
tblSender sndr = new tblSender();
sndr.setNumber(viewHolder.textViewPos.getTag().toString());
ds.create_tblSender(sndr);
}
mItemManger.closeAllItems();
viewHolder.imgLock.setImageResource(R.drawable.lock);
viewHolder.imgLock.setVisibility(View.VISIBLE);
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.imgLock));
viewHolder.btnLock.setTag("unlocked");
viewHolder.btnLock.setImageResource(R.drawable.unlock);
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.lock));
ds.Lock(viewHolder.textViewPos.getTag().toString());
}
else{
mItemManger.closeAllItems();
viewHolder.imgLock.setVisibility(View.GONE);
viewHolder.btnLock.setTag("locked");
viewHolder.btnLock.setImageResource(R.drawable.lock);
ds.unLock(viewHolder.textViewPos.getTag().toString());
}
//mItemManger.closeAllItems();
}
});
//Archieve
viewHolder.panelArchieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataset.size());
mItemManger.closeAllItems();
ds.open();
if(ds.selectCount_tblSender(viewHolder.textViewPos.getTag().toString()) == 0){
//Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
tblSender sndr = new tblSender();
sndr.setNumber(viewHolder.textViewPos.getTag().toString());
ds.create_tblSender(sndr);
}
ds.archieve(viewHolder.textViewPos.getTag().toString());
}
});
viewHolder.textViewPos.setText(name.getSenderName());
viewHolder.textViewPos.setTag(name.getrNumber());
viewHolder.textViewData.setText(name.getMessage().trim());
//Log.i(Log_tag, "Msg: " + name.getMessage().trim());
//viewHolder.txtTime.setText(name.getTime());
//Time Text
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String dateNowStr = formatter.format(date);
Date dateNow = null;
dateNow = formatter.parse(dateNowStr);
String dateSmsStr = name.getTime().substring(0,10);
Date dateSMS = formatter.parse(dateSmsStr);
if (dateSMS.compareTo(dateNow)<0)
{
viewHolder.txtTime.setText(dateSmsStr.substring(0,10)); // + " " + name.getTime().substring(11,name.getTime().length()));
}
else {
viewHolder.txtTime.setText(name.getTime().substring(11,name.getTime().length()));
}
} catch (ParseException e) {
e.printStackTrace();
}
//ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
//int colorRandom = generator.getRandomColor(); // generate random color
//int colorAlpha = generator.getColor(mDataset.get(position).getrName().substring(0,1));//(same key returns the same color)
// declare the builder object once.
TextDrawable.IBuilder builder = TextDrawable.builder()
.beginConfig()
.withBorder(0)
.toUpperCase()
.endConfig()
.round();
int greenColorValue = Color.parseColor("#FF457BDF");
TextDrawable ic1 = builder.build(mDataset.get(position).getrName().substring(0,1), greenColorValue);
viewHolder.imgName.setImageDrawable(ic1);
if(ds.select_tblSender(name.getrNumber()).getIsMute() == 1){ //Mute sign
Log.i(Log_tag, name.getrNumber() + " was muted at position " + position);
viewHolder.btnMute.setTag("bell");
viewHolder.btnMute.setImageResource(R.drawable.bell);
viewHolder.imgMute.setVisibility(View.VISIBLE);
}
if(ds.select_tblSender(name.getrNumber()).getIsProtected() == 1){ //Mute sign
viewHolder.btnLock.setTag("unlocked");
viewHolder.btnLock.setImageResource(R.drawable.unlock);
viewHolder.imgLock.setVisibility(View.VISIBLE);
}
mItemManger.bindView(viewHolder.itemView, position);
}
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
updateBarHandler = new Handler();
//Fill Inbox
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// Layout Managers:
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ds = new dataSource(this);
activity = this;
mAdapter = new RecyclerViewAdapter(activity, listInboxAll);
((RecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
recyclerView.setAdapter(mAdapter);
recyclerView.setOnScrollListener(onScrollListener);
//All conversations
GetAllMsgs task = new GetAllMsgs();
task.execute();
}
GetAllMsgs()
private class GetAllMsgs extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
ContentResolver contentResolver = getContentResolver();
final String[] projection = new String[]{"*"};
Uri uriSMSURI = Uri.parse("content://mms-sms/conversations/");
Cursor cur = contentResolver.query(uriSMSURI, projection, null, null, "date DESC");
int i = 0;
while (cur.moveToNext()) {
String address = cur.getString(cur.getColumnIndex("address"));
final String body = cur.getString(cur.getColumnIndexOrThrow("body"));
final String date = cur.getString(cur.getColumnIndex("date"));
final Long timestamp = Long.parseLong(date);
//Log.i(Log_tag, "Msg: " + body + " from: " + address);
address = address.trim();
if(address.toString().startsWith("92"))
{
address = address.toString().replace("92", "0");
}
else if(address.toString().startsWith("3")){
address = "0" + address;
}
else if(address.toString().startsWith("+92"))
{
address = address.toString().replace("+92", "0");
}
final String nAdd = address;
time = DateFormat.is24HourFormat(activity);
if(time){
dateFormat = new SimpleDateFormat("dd/MM/yyyy k:mm");
}
else{
dateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm a");
}
String usr = getContactName(activity, nAdd);
tblMsgs msg = new tblMsgs();
msg.setMessage(body);
msg.setSenderName(usr); //Fuzool hai for now
msg.setIsSent(1);
msg.setIsReply(0);
msg.setIsUploaded(0);
msg.setIsLocked(0);
msg.setTime(dateFormat.format(timestamp));
msg.setrName(usr); //Name from phone book
msg.setrNumber(nAdd);
msg.setTimeStamp(timestamp);
//listInboxAll.add(msg);
Texty.position = i;
((RecyclerViewAdapter) mAdapter).addnewItem(msg);
i++;
final int j = i;
if(i % 5 == 0){
updateBarHandler.post(new Runnable() {
#Override
public void run () {
((RecyclerViewAdapter) mAdapter).Update(j);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(activity));
}
});
}
//listInboxAll.add(msg);
//ds.create(msg);
}
return "done";
}
catch(Exception ex){
Log.e(Log_tag, ex.getMessage());
return "failed";
}
}
#Override
protected void onPostExecute(String result) {
}
}
#Gabe Sechan solved my problem, I had to change the visibility of icons initially.

Listview update another raw on update of selected raw

I working on one Shopping Cart application.
In which i show list of products and in that every raw there is "Add to Cart" button,
Whenever user clicks on it then that button goes to disable and another view which holds add and subtract quantity should be display.
But when i clicks on any single product "Add to Cart" button then that view is going to be update, But when i scroll listview then another view gets update automatically (Not all).
Adapter
public class CategoryProductListAdapter extends BaseAdapter {
Context context;
ArrayList<ProductDetailsModel> productDetailsModels;
FragmentManager fragmentManager;
LayoutInflater inflater;
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels) {
this.context = context;
this.productDetailsModels = productDetailsModels;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels,FragmentManager fragmentManager) {
this.context = context;
this.productDetailsModels = productDetailsModels;
this.fragmentManager = fragmentManager;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return productDetailsModels.size();
}
#Override
public Object getItem(int i) {
return productDetailsModels.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public class Holder {
LinearLayout llProductRawMain, llProductQty;
ImageView imgProduct;
TextView txtProductTitle, txtProductUnit;
Spinner spProductUnits;
Button btnAddProduct, btnSubProduct;
EditText etNoOfProduct;
TextView txtProductPrice;
Button btnAddToCart;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final Holder holder;
if (view == null) {
holder = new Holder();
view = inflater.inflate(R.layout.category_product_list_raw, viewGroup, false);
holder.llProductRawMain = (LinearLayout) view.findViewById(R.id.llProductRawMain);
holder.llProductQty = (LinearLayout) view.findViewById(R.id.llProductQty);
holder.imgProduct = (ImageView) view.findViewById(R.id.imgProduct);
holder.txtProductTitle = (TextView) view.findViewById(R.id.txtProductTitle);
holder.txtProductUnit = (TextView) view.findViewById(R.id.txtProductUnit);
holder.spProductUnits = (Spinner) view.findViewById(R.id.spProductUnits);
holder.btnAddProduct = (Button) view.findViewById(R.id.btnAddProduct);
holder.btnSubProduct = (Button) view.findViewById(R.id.btnSubProduct);
holder.etNoOfProduct = (EditText) view.findViewById(R.id.etNoOfProduct);
holder.txtProductPrice = (TextView) view.findViewById(R.id.txtProductPrice);
holder.btnAddToCart = (Button) view.findViewById(R.id.btnAddToCart);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.txtProductTitle.setText(Html.fromHtml(productDetailsModels.get(i).getName()));
if (productDetailsModels.get(i).getUnits().size() > 0) {
holder.txtProductUnit.setVisibility(View.GONE);
holder.spProductUnits.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(0).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(0).getPrice());
ArrayList<ProductUnitModel> units = new ArrayList<>();
units.clear();
units.addAll(productDetailsModels.get(i).getUnits());
ProductUnitsListAdapter productUnitsListAdapter = new ProductUnitsListAdapter(context, units);
holder.spProductUnits.setAdapter(productUnitsListAdapter);
holder.spProductUnits.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int j, long l) {
holder.etNoOfProduct.setText("1");
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(j).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(j).getPrice());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} else {
holder.spProductUnits.setVisibility(View.GONE);
holder.txtProductUnit.setVisibility(View.VISIBLE);
holder.txtProductUnit.setText(productDetailsModels.get(i).getUnit());
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getImage(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getPrice());
}
holder.llProductRawMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (productDetailsModels.get(i).getUnits().size() > 0) {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", true);
intent.putExtra("productUnitPos", holder.spProductUnits.getSelectedItemPosition());
context.startActivity(intent);*/
//FragmentManager fragmentManager = fra;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = true;
int productUnitPos = holder.spProductUnits.getSelectedItemPosition();
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
} else {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", false);
intent.putExtra("productUnitPos", 0);
context.startActivity(intent);*/
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = false;
int productUnitPos = 0;
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
}
}
});
holder.btnAddProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty++;
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
}
});
holder.btnSubProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty--;
if (qty > 0) {
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
} else {
Toast.makeText(context, "Quntity can not be zero!", Toast.LENGTH_SHORT).show();
}
}
});
holder.btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final boolean isUserLogin = AppMethod.getBooleanPreference((Activity) context, AppConstant.PREF_IS_LOGGED_IN);
if (isUserLogin) {
holder.llProductQty.setVisibility(View.VISIBLE);
holder.btnAddToCart.setVisibility(View.GONE);
String product_id;
String variation_id;
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, 1);
} else {
Toast.makeText(context, "Please Login for Add to Cart !", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void updateCart(String product_id, String variation_id, int qty) {
String customer_id = AppMethod.getStringPreference((Activity) context, AppConstant.PREF_USER_ID);
if (AppMethod.isNetworkConnected((Activity) context)) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product_id", product_id);
jsonObject.put("variation_id", variation_id);
jsonObject.put("qty", qty);
jsonObject.put("customer_id", customer_id);
WsHttpPostJson wsHttpPostJson = new WsHttpPostJson(context, AppConstant.ADD_CART_WS, jsonObject.toString());
wsHttpPostJson.execute(AppConstant.ADD_CART_WS_URL);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, AppConstant.NO_INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}
}
XML of Adapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductRawMain"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:background="#drawable/product_grid_item_bg"
android:orientation="horizontal"
android:padding="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgProduct"
android:layout_width="match_parent"
android:layout_height="#dimen/_80sdp"
android:padding="#dimen/_5sdp"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:padding="#dimen/view_margin">
<TextView
android:id="#+id/txtProductTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:minLines="2"
android:textSize="#dimen/_11sdp"
android:text="Product Title"
android:textColor="#000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtProductUnit"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center_vertical"
android:padding="5dp"
android:textSize="#dimen/_11sdp"
android:text="Product Unit" />
<Spinner
android:id="#+id/spProductUnits"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center"
android:background="#drawable/icon_dropdown"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/txtProductPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="\u20B9 200"
android:textStyle="bold"
android:textSize="#dimen/_13sdp"
android:textColor="#185401" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductQty"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/app_color"
android:orientation="horizontal"
android:visibility="gone">
<Button
android:id="#+id/btnSubProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_minus"
android:gravity="center" />
<EditText
android:id="#+id/etNoOfProduct"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:background="#null"
android:ems="10"
android:enabled="false"
android:textSize="#dimen/_10sdp"
android:gravity="center"
android:inputType="number"
android:text="1"
android:textColor="#color/white" />
<Button
android:id="#+id/btnAddProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_plus"
android:gravity="center" />
</LinearLayout>
<Button
android:id="#+id/btnAddToCart"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/add_to_cart_btn_bg"
android:text="ADD TO CART"
android:textSize="#dimen/_12sdp"
android:textColor="#color/app_color" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I suffer from this also and realize that i think this links are help you.
Answer-1
Answer-2
Thanks

Chat Bubble Alignment on ListView

I have connected my android application to Firebase and I am sending messages with attributes 'name' and 'status'. status being either sent or received.
I am facing issue while aligning the chat bubble left/right depending upon the status.
Here is the code snippet
message_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/singleMessageContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/message_bubble_received">
<TextView
android:id="#+id/username_text_view"
android:layout_width="wrap_content"
android:paddingLeft="10dip"
android:layout_margin="5dip"
android:text="Hello bubbles!"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/message_text_view"
android:layout_width="wrap_content"
android:paddingLeft="1dip"
android:layout_margin="5dip"
android:text="Hello bubbles!"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ECECEC">
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:divider="#null"
android:layout_marginTop="10dp"
android:listSelector="#android:color/transparent"
android:transcriptMode="alwaysScroll"
android:layout_marginBottom="80dp"/>
<RelativeLayout
android:id="#+id/form"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="#+id/message_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="left"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:layout_weight="3"
android:autoText="true"
android:background="#drawable/note_backgroud"
android:hint="Write your question here"
android:minLines="1"
android:paddingLeft="20dp"
android:paddingRight="8dp"
android:paddingBottom="16dp"
android:paddingTop="8dp"/>
<ImageButton
android:id="#+id/cameraButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#null"
android:src="#drawable/camera"
android:gravity="top|right"
android:layout_marginRight="8dp"
android:layout_marginLeft="-52dp"
/>
<ImageButton
android:id="#+id/chatSendButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/sent"
android:background="#null"
android:layout_gravity="center"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp"
android:text="Send"
android:onClick="onSendButtonClick"
android:textColor="#ffffff" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
Following is the code snipet for the MessageAdapter
MessageAdapter.java
public abstract class MessageAdapter<T> extends BaseAdapter {
private Query mRef;
private Class<T> mModelClass;
private int mLayout;
private LayoutInflater mInflater;
private List<T> mModels;
private List<String> mKeys;
private ChildEventListener mListener;
private Context context;
private LinearLayout message_row;
private ProgressDialog mProgressDialog;
public MessageAdapter(Query mRef, Class<T> mModelClass, int mLayout, Activity activity) {
this.mRef = mRef;
this.mModelClass = mModelClass;
this.mLayout = mLayout;
this.context = activity.getApplicationContext();
mInflater = activity.getLayoutInflater();
mModels = new ArrayList<T>();
mKeys = new ArrayList<String>();
mProgressDialog = new ProgressDialog(activity);
mProgressDialog.show();
// Look for all child events. We will then map them to our own internal ArrayList, which backs ListView
mListener = this.mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
T model = dataSnapshot.getValue(MessageAdapter.this.mModelClass);
String key = dataSnapshot.getKey();
// Insert into the correct location, based on previousChildName
if (previousChildName == null) {
mModels.add(0, model);
mKeys.add(0, key);
} else {
int previousIndex = mKeys.indexOf(previousChildName);
int nextIndex = previousIndex + 1;
if (nextIndex == mModels.size()) {
mModels.add(model);
mKeys.add(key);
} else {
mModels.add(nextIndex, model);
mKeys.add(nextIndex, key);
}
}
notifyDataSetChanged();
mProgressDialog.dismiss();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// One of the mModels changed. Replace it in our list and name mapping
String key = dataSnapshot.getKey();
T newModel = dataSnapshot.getValue(MessageAdapter.this.mModelClass);
int index = mKeys.indexOf(key);
mModels.set(index, newModel);
notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// A model was removed from the list. Remove it from our list and the name mapping
String key = dataSnapshot.getKey();
int index = mKeys.indexOf(key);
mKeys.remove(index);
mModels.remove(index);
notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
// A model changed position in the list. Update our list accordingly
String key = dataSnapshot.getKey();
T newModel = dataSnapshot.getValue(MessageAdapter.this.mModelClass);
int index = mKeys.indexOf(key);
mModels.remove(index);
mKeys.remove(index);
if (previousChildName == null) {
mModels.add(0, newModel);
mKeys.add(0, key);
} else {
int previousIndex = mKeys.indexOf(previousChildName);
int nextIndex = previousIndex + 1;
if (nextIndex == mModels.size()) {
mModels.add(newModel);
mKeys.add(key);
} else {
mModels.add(nextIndex, newModel);
mKeys.add(nextIndex, key);
}
}
notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
}
});
}
public void cleanup() {
// We're being destroyed, let go of our mListener and forget about all of the mModels
mRef.removeEventListener(mListener);
mModels.clear();
mKeys.clear();
}
#Override
public int getCount() {
return mModels.size();
}
#Override
public Object getItem(int i) {
return mModels.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = mInflater.inflate(mLayout, viewGroup, false);
message_row = (LinearLayout) view.findViewById(R.id.singleMessageContainer);
}
T model = mModels.get(i);
Message m = (Message) model;
Log.i("status", m.getStatus());
if (m.getStatus().equals("sent")){
message_row.setGravity(Gravity.LEFT);
message_row.setBackgroundResource(R.drawable.message_bubble_received);
}
else {
message_row.setGravity(Gravity.RIGHT);
message_row.setBackgroundResource(R.drawable.message_bubble_sent);
}
// Call out to subclass to marshall this model into the provided view
populateView(view, model);
return view;
}
protected abstract void populateView(View v, T model);
}
I noticed that the getView() is called more times than the count in the list (eg : if I have 2 messages getview() is called 4 to 5 times).
With the current code chat bubbles are always to the left irrespective of the chat status.
Firebase Data
I recommend to use two layouts - for your bubbles and your opponent. Use them in getView() method of your adapter. For list_item_message_own.xml use right allignment and for list_item_message_opponent.xml use left allignment, it depends on message status.
#Override
public View getView(Context context, Cursor cursor, ViewGroup parent) {
View view;
ViewHolder viewHolder = new ViewHolder();
MessageCache messageCache = ChatManager.getMessageCacheFromCursor(cursor);
boolean ownMessage = isOwnMessage(messageCache.getSenderId());
if (messageCache.getMessagesNotificationType() == null) {
if (ownMessage) {
view = layoutInflater.inflate(R.layout.list_item_message_own, null, true);
} else {
view = layoutInflater.inflate(R.layout.list_item_message_opponent, null, true);
}
viewHolder.timeAttachMessageTextView = (TextView) view.findViewById(R.id.time_attach_message_textview);
viewHolder.verticalProgressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.vertical_progressbar));
viewHolder.centeredProgressBar = (ProgressBar) view.findViewById(R.id.centered_progressbar);
} else {
view = layoutInflater.inflate(R.layout.list_item_notification_message, null, true);
viewHolder.messageTextView = (EmojiTextView) view.findViewById(R.id.message_textview);
viewHolder.timeTextMessageTextView = (TextView) view.findViewById(
R.id.time_text_message_textview);
}
view.setTag(viewHolder);
return view;
}

Categories

Resources