I have an issue where notifyDataSetChanged() in a response call will blank out the recyclerview but if the Adapter is initiated manually with a onClick, the recyclerview works. I have tested that the List has the items inside before calling notifyDataSetChanged() so i'm not sure what's wrong here.
[Main Activity] This works but i have to manually click the bnQuery.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = API_client.getClient().create(APIInterface.class);
etCoin = (EditText) findViewById(R.id.etCoin);
bnQuery = (Button) findViewById(R.id.bnQuery);
rcvMain = findViewById(R.id.rcvMain);
getCoinData("2");
//initRCV_Main();
bnQuery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getCoinData("2");
initRCV_Main();
}
});
}
private void initRCV_Main() {
rcvMainAdp = new rcvMainAdapter(cList);
rcvMain.setAdapter(rcvMainAdp);
rcvMain.setLayoutManager(new LinearLayoutManager(this));
}
private void getCoinData(String coinLimit){
Call<cInfoPack> call = apiInterface.doGetCoinData(coinLimit);
call.enqueue(new Callback<cInfoPack>() {
#Override
public void onResponse(Call<cInfoPack> call, Response<cInfoPack> response) {
cInfoPack list = response.body();
List<cData> listSorter = new ArrayList<>();
listSorter.addAll(list.getData());
Collections.sort(listSorter, new SortbyVolChg());
cList.clear();
cList = listSorter;
System.out.println("list " + list.getData().get(0).getQuote());
System.out.println("listSorter " + listSorter.get(0).getQuote());
System.out.println("cList " + cList.get(0).getQuote());
//rcvMainAdp.notifyDataSetChanged();
}
#Override
public void onFailure(Call<cInfoPack> call, Throwable t) {
Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
Log.d("XXXX", t.getLocalizedMessage());
call.cancel();
}
});
}
[Main Activity] If i initiate the recyclerview during onCreate and use the notifyDataSetChanged() during getCoinData, I get a blank recycleview. system.out shows that the lists all contain information in them.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = API_client.getClient().create(APIInterface.class);
etCoin = (EditText) findViewById(R.id.etCoin);
bnQuery = (Button) findViewById(R.id.bnQuery);
rcvMain = findViewById(R.id.rcvMain);
getCoinData("2");
initRCV_Main();
bnQuery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getCoinData("2");
//initRCV_Main();
}
});
}
private void initRCV_Main() {
rcvMainAdp = new rcvMainAdapter(cList);
rcvMain.setAdapter(rcvMainAdp);
rcvMain.setLayoutManager(new LinearLayoutManager(this));
}
private void getCoinData(String coinLimit){
Call<cInfoPack> call = apiInterface.doGetCoinData(coinLimit);
call.enqueue(new Callback<cInfoPack>() {
#Override
public void onResponse(Call<cInfoPack> call, Response<cInfoPack> response) {
cInfoPack list = response.body();
List<cData> listSorter = new ArrayList<>();
listSorter.addAll(list.getData());
Collections.sort(listSorter, new SortbyVolChg());
cList.clear();
cList = listSorter;
System.out.println("list " + list.getData().get(0).getQuote());
System.out.println("listSorter " + listSorter.get(0).getQuote());
System.out.println("cList " + cList.get(0).getQuote());
rcvMainAdp.notifyDataSetChanged();
}
#Override
public void onFailure(Call<cInfoPack> call, Throwable t) {
Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
Log.d("XXXX", t.getLocalizedMessage());
call.cancel();
}
});
}
[Adapter]
public class rcvMainAdapter extends RecyclerView.Adapter<rcvMainAdapter.ViewHolder> {
private List<cData> idxCoin;
//ItemClickListener itemClickListener;
rcvMainAdapter(List<cData> data) {this.idxCoin = data;}
#NonNull
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.rcv_main,parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull #NotNull ViewHolder holder, int position) {
cData cdata = idxCoin.get(position);
TextView tvSym = holder.tvSymbol;
tvSym.setText(cdata.getSymbol());
TextView tvQuo = holder.tvQuote;
BigDecimal tvQuote_BD = new BigDecimal(cdata.getQuote().getuSD().getPrice().toString());
tvQuote_BD.setScale(6, RoundingMode.DOWN);
tvQuo.setText(tvQuote_BD.toString());
TextView tvV24 = holder.tvVolume24;
BigDecimal tvVolume24_BD = new BigDecimal(cdata.getQuote().getuSD().getVolume24h().toString());
BigInteger tvVolume24_BI = tvVolume24_BD.toBigInteger();
tvV24.setText(tvVolume24_BI.toString());
}
#Override
public int getItemCount() {
return idxCoin.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvSymbol, tvQuote, tvVolume24;
public ViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
tvSymbol = itemView.findViewById(R.id.tvSymbol);
tvQuote = itemView.findViewById(R.id.tvQuote);
tvVolume24 = itemView.findViewById(R.id.tvVolume24);
//itemView.setOnClickListener(this);
}
}
/*
public interface ItemClickListener{
void onItemClick(View view, int position);
}
*/
}
PS: apologies for the rubbish coding as this is self taught and modifying some codes found online.
Remove this in response.
cList.clear();
Add This line in response
rcvMainAdp.setdata(listSorter);
In rcvMainAdp Adapter, Create a Method setdata()
public void setdata(ArrayList<cData> data) {
this.idxCoin = data;
notifyDataSetChanged();
}
Problem most likely is that when you call initRCV_Main() You set the adapter to the list as in rcvMainAdp = new rcvMainAdapter(cList); And when list is changed and you set it to adapter it functions.
But when you call getCoinData() and rcvMainAdp.notifyDataSetChanged(); at the end you never set the changed list to the adapter until you click initRCV_Main() again.
So maybe the fix is calling rcvMainAdp = new rcvMainAdapter(cList) and then
rcvMainAdp.notifyDataSetChanged();
Related
I'm trying to implement text counter where an integer will be incremented and decremented inside each firestore RecyclerView item for example 0 to 100. I've tried taking an int[] and Button onClick. I did holder.tvqty.setText(String.valueOf(a[position]++));. Here on Button click, all TextViews are successfully incremented with individual items. But the main problem is that when I click on first item button if the first position is the same, it's actually also incrementing last position i.e, in short, the first and last RecyclerView items are getting incremented together however rest of the items are working without any problem.
Please help me debug this any help will be appreciated.
This is my java class:
public class OrderItemFragment extends Fragment{
Context context;
int i=0;
// private List<Ex> exlist;
RecyclerView recyclerView;
FirebaseFirestore db;
FirestoreRecyclerAdapter adapter;
ArrayList<String> list = new ArrayList<String>();
int [] a;
public static OrderItemFragment newInstance() {
OrderItemFragment fragment = new OrderItemFragment();
return fragment;
}
public OrderItemFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orderitem, container, false);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recorder);
recyclerView.setLayoutManager(layoutManager);
initializeData();
//initializeAdapter();
db=FirebaseFirestore.getInstance();
return view;
}
private void initializeData()
{
db=FirebaseFirestore.getInstance();
Query query = db.collection("Items");
FirestoreRecyclerOptions<FriendsResponse> response = new FirestoreRecyclerOptions.Builder<FriendsResponse>()
.setQuery(query, FriendsResponse.class)
.build();
adapter = new FirestoreRecyclerAdapter<FriendsResponse, FriendsHolder>(response) {
#Override
public void onBindViewHolder(FriendsHolder holder, int position, FriendsResponse model) {
/* for (int i=0;i < ids.size();i++)
{
holder.exname.setText(ids.get(i));
}*/
//Toast.makeText(getContext(),String.valueOf(getItemCount()),Toast.LENGTH_LONG).show();
// String id = getSnapshots().getSnapshot(position).getId();
String id = getSnapshots().getSnapshot(position).getId();
for (i=0;i<getSnapshots().size();i++) {
list.add(getSnapshots().getSnapshot(position).getId());
}
a= new int [list.size()];
holder.exname.setText(id);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.tvqty.setText(String.valueOf(a[position]++));
}
});
holder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public FriendsHolder onCreateViewHolder(ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.menu_item, group, false);
return new FriendsHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView exname,tvqty;
ImageView add,remove;
public FriendsHolder(View itemView) {
super(itemView);
exname= itemView.findViewById(R.id.menuname);
add=itemView.findViewById(R.id.additem);
remove=itemView.findViewById(R.id.removeitem);
tvqty=itemView.findViewById(R.id.tvqty);
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
/*
public class Ex {
String name;
int logoId;
int count=0;
Ex(String name, int logoId) {
this.name = name;
this.logoId = logoId;
}
}
*/
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
In this line of code holder.tvqty.setText(String.valueOf(a[position]++)), does a[position]++ the job ? Try to store the value of a[position] in a integer,and after that set it to tvqty.
int current_value = a[position];
and then
holder.tvqty.setText(String.valueOf((current_value++)));
I'm using a Cloud Firestore database to populate a RecyclerView in an Android app. I'm getting the data by using a Task in the onAttach method of a Fragment. I need to be able to update the UI, the RecyclerView with data from the Cloud Firestore.
I populated the RecyclerView with dummy data in the onAttach method of the Fragment and that worked, but when I put the same loop that inserts dummy data in the onComplete method of a OnCompleteListener that's used in the Task that pulls data from the Cloud Firestore, the RecyclerView doesn't update and the list stays blank. I need to do it there to eventually insert data from the Cloud Firestore.
Within the Fragment. The data coming back from the Firestore database is correct and I see all of the Log statements in the onComplete method in the Logcat.
ChatListFragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
chatRecyclerViewAdapter = new ChatRecyclerViewAdapter(ChatList.ITEMS, mListener);
recyclerView.setAdapter(chatRecyclerViewAdapter);
}
return view;
}
...
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
Log.d(LOG_TAG, "activity attached, creating Firestore instance");
FirebaseFirestore db = FirebaseFirestore.getInstance();
//Worked, but doesn't in OnCompleteListener
/*for (int i = 1; i <= 10; i++) {
ChatList.addItem(ChatList.createDummyItem(i));
}*/
Task<QuerySnapshot> task = db.collection("chats").get();
task.addOnCompleteListener(getActivity(), new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(LOG_TAG, "ID = " + document.getId() + " => " + document.getData());
ChatListMessage chatListMessage = document.toObject(ChatListMessage.class);
for (int i = 1; i <= 10; i++) {
Log.d(LOG_TAG, "adding message");
ChatList.addItem(ChatList.createDummyItem(i));
}
Log.d(LOG_TAG, "ChatListMessage members " + chatListMessage.getLastMessage());
}
} else {
Log.w(LOG_TAG, "Error getting documents.", task.getException());
}
}
});
}
Within the ChatList class
public static void addItem(ChatListItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.userId, item);
}
public static ChatListItem createDummyItem(int position) {
return new ChatListItem(String.valueOf(position), R.drawable.profile_circle, makeDetails(position),
new Timestamp(System.currentTimeMillis()));
}
public static class ChatListItem {
public final String userId;
public final int pictureUrl;
public final String lastMessage;
public final Timestamp timeStamp;
public ChatListItem(String userId, int pictureUrl, String details, Timestamp timeStamp) {
this.userId = userId;
this.pictureUrl = pictureUrl;
this.lastMessage = details;
this.timeStamp = timeStamp;
}
#Override
public String toString() {
return userId;
}
public Timestamp getTimeStamp() {
return timeStamp;
}
public String getTLastMessage() {
return lastMessage;
}
}
The custom RecyclerViewAdapter
public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerViewAdapter.ViewHolder> {
private final List<ChatListItem> mValues;
private final OnListFragmentInteractionListener mListener;
public ChatRecyclerViewAdapter(List<ChatListItem> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_chat, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.contactImageView.setImageResource(mValues.get(position).pictureUrl);
holder.contactImageView.setScaleType(ImageView.ScaleType.FIT_XY);
holder.mContentView.setText(mValues.get(position).lastMessage);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final ImageView contactImageView;
public final TextView messageMembersTextView;
public final TextView mContentView;
public final TextView timestampView;
public ChatListItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
messageMembersTextView = view.findViewById(R.id.message_members);
contactImageView = view.findViewById(R.id.contact_imageView);
mContentView = view.findViewById(R.id.content_textView);
timestampView = view.findViewById(R.id.timestamp_textView);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
How can I get the UI to be updated with the onComplete method of the OnCompleteListener?
For this, chatRecyclerViewAdapter.notifyDataSetChanged() needs to be called in the onComplete method of the OnCompleteListener. I forgot to do this outside of the listener since it looks like the list items are pulled in after the onAttach method is called.
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
I'm having a problem with this code, I created a personal chat, but when I send a message the RecyclerView does not show automatically the last message sent but I have to scroll down, how can I make sure that automatically displays the last message?
public class ChatListAdapter extends RecyclerView.Adapter {
private Activity mActivity;
private DatabaseReference mDataBaseReference;
private String mDisplayName;
private ArrayList<DataSnapshot> mDataSnapshot;
private ChildEventListener mListener = new ChildEventListener () {
#Override
public void onChildAdded(DataSnapshot dataSnapshot,String s) {
mDataSnapshot.add (dataSnapshot);
notifyDataSetChanged ();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot,String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot,String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
public ChatListAdapter(Activity activity, DatabaseReference ref, String name){
mActivity = activity;
mDataBaseReference = ref.child ("messaggi");
mDisplayName = name;
mDataSnapshot = new ArrayList <> ();
mDataBaseReference.addChildEventListener (mListener);
}
public class ChatViewHolder extends RecyclerView.ViewHolder{
TextView autore;
TextView messaggio;
LinearLayout.LayoutParams params;
public ChatViewHolder(View itemView) {
super (itemView);
autore = (TextView)itemView.findViewById (R.id.tv_autore);
messaggio = (TextView)itemView.findViewById (R.id.tv_messaggio);
params = (LinearLayout.LayoutParams) autore.getLayoutParams ();
}
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder(#NonNull ViewGroup parent,int viewType) {
LayoutInflater inflater = (LayoutInflater)mActivity.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate (R.layout.chat_msg_row, parent, false);
ChatViewHolder vh = new ChatViewHolder (v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ChatViewHolder holder,int position) {
DataSnapshot snapshot = mDataSnapshot.get (position);
Messaggio msg = snapshot.getValue (Messaggio.class);
holder.autore.setText (msg.getAutore ());
holder.messaggio.setText (msg.getMessaggio ());
boolean sonoIo = msg.getAutore ().equals (mDisplayName);
setChatItemStyle(sonoIo, holder);
}
private void setChatItemStyle(boolean sonoIo, ChatViewHolder holder){
if(sonoIo){
holder.params.gravity = Gravity.END;
holder.autore.setTextColor (Color.GREEN);
holder.messaggio.setBackgroundResource(R.drawable.in_msg_bg);
}else{
holder.params.gravity = Gravity.START;
holder.autore.setTextColor (Color.CYAN);
holder.messaggio.setBackgroundResource(R.drawable.out_msg_bg);
}
holder.autore.setLayoutParams (holder.params);
holder.messaggio.setLayoutParams (holder.params);
}
#Override
public int getItemCount() {
return mDataSnapshot.size ();
}
public void clean(){
mDataBaseReference.removeEventListener (mListener);
}
}
You can set stackFromEnd to be true on your LinearLayoutManager. If your chat messages are coming back most recent first, you can also reverse on the manager rather than in data. Then to auto scroll on dataset changed, simply set android:transcriptMode to normal (scroll only if already at bottom) or alwaysScroll (always scroll to bottom after a change) on your RecyclerView xml.
boolean reverseLayout = true; // Or false if your data is already reversed
LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, reverseLayout);
manager.setStackFromEnd(true);
yourRecyclerView.setLayoutManager(manager);
I am assuming you are using a recycler view to populate messages.
So here it is
Variable Declaration
private RecyclerView rvChat;
onCreate
rvChat = findViewById(R.id.a_individual_chat_rv_chat);
onChildAdded (After notifyDataSetChanged)
rvChat.smoothScrollToPosition(rvChat.getAdapter().getItemCount());
My cart
This is what i need.
Total value need to be updated when one item removed.
I managed to remove the item and get the total value as json respose in adapter viewholder . don't know how to set the update the text in Fragment.
this is my cart fragment
Cart.java
public class Cart extends Fragment {
public Cart() {
// Required empty public constructor
}
Context context;
Activity activity;
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://192.168.0.106/slbros/index.php/get/cart?p_d_id=12&lan=en";
String Total_URL = "http://192.168.0.106/slbros/index.php/get/total?p_d_id=12";
String JSON_CDID = "cart_dtl_id";
String JSON_IMG_URL = "img_url";
String JSON_QTY = "qty";
String JSON_NAME = "name";
String JSON_UNIT = "unit";
String JSON_PRICE = "price";
String JSON_P_ID = "product_id";
JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_cart, container, false);
TextView total_tv = (TextView)v.findViewById(R.id.total_payment_value);
//recycler view
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.rv_cart_list);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar2);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Cart");
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "some error....", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue = Volley.newRequestQueue(getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1));
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImg_url(json.getString(JSON_IMG_URL));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setPrice(json.getInt(JSON_PRICE));
GetDataAdapter2.setProduct_id(json.getInt(JSON_P_ID));
GetDataAdapter2.setCart_dtl_id(json.getInt(JSON_CDID));
GetDataAdapter2.setProduct_qty(json.getInt(JSON_QTY));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapterCart(GetDataAdapter1, getContext());
recyclerView.setAdapter(recyclerViewadapter);
}}
this is my adapter
RecyclerViewAdapterCart.java
public class RecyclerViewAdapterCart extends RecyclerView.Adapter<RecyclerViewAdapterCart.ViewHolder> {
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
String baseURL = "http://192.168.0.106/slbros/index.php/";
Context context;
Activity activity;
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapterCart(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImg_url(),
ImageLoader.getImageListener(
Viewholder.product_image_view,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.product_image_view.setImageUrl(getDataAdapter1.getImg_url(), imageLoader1);
Viewholder.product_name_TextView.setText(getDataAdapter1.getName()+" - "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_price_qty_TextView.setText(getDataAdapter1.getPrice()+".00 Rs X "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_t_price_TextView.setText(String.valueOf(getDataAdapter1.getProduct_qty()*getDataAdapter1.getPrice())+".00 Rs");
Viewholder.product_id_TextView.setText(String.valueOf(getDataAdapter1.getProduct_id()));
Viewholder.cart_dtl_id_TextView.setText(String.valueOf(getDataAdapter1.getCart_dtl_id()));
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public NetworkImageView product_image_view;
public TextView product_name_TextView;
public TextView product_price_qty_TextView;
public TextView product_t_price_TextView;
public TextView product_id_TextView;
public TextView cart_dtl_id_TextView;
public Button p_cancel_btn;
public ViewHolder(View itemView) {
super(itemView);
product_image_view = (NetworkImageView) itemView.findViewById(R.id.item_image1);
product_name_TextView = (TextView) itemView.findViewById(R.id.product_name);
product_price_qty_TextView = (TextView) itemView.findViewById(R.id.p_qty_price);
product_t_price_TextView = (TextView) itemView.findViewById(R.id.p_t__price);
product_id_TextView = (TextView) itemView.findViewById(R.id.product_id_tv);
cart_dtl_id_TextView = (TextView) itemView.findViewById(R.id.cart_dtl_id_tv);
p_cancel_btn = (Button)itemView.findViewById(R.id.p_cancel_btn);
// set item view
p_cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(final View v) {
String str = product_name_TextView.getText().toString();
//Toast.makeText(v.getContext(), str, Toast.LENGTH_SHORT).show();
String cart_dtl_id = cart_dtl_id_TextView.getText().toString();
String url = baseURL + "delete/select?cart_dtl_id="+cart_dtl_id;
jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
Toast.makeText(v.getContext(), "response -- " + response, Toast.LENGTH_LONG).show();
// here, I have to change the total TextView in Fragment
// Total_TextView.setText("1000rs")
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(v.getContext(), "error", Toast.LENGTH_LONG).show();
}
}
);
requestQueue = Volley.newRequestQueue(v.getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000,0,1));
requestQueue.add(jsonArrayRequest);
getDataAdapter.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(),getDataAdapter.size());
}
}}
Thanks in Advance
add to ReyclerView.
private ItemsChangedListener itemsChangedListener;
public interface ItemsChangedListener {
void onItemsChanged(int sum);
}
public void setItemsChangedListener(ItemsChangedListener listener) {
this.itemsChangedListener = listener;
}
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
// Calc here the Value if you can.
if(listener != null) listener.onItemsChanged(sum);
}
Fragment
public class Cart extends Fragment implements ItemsChangedListener
recyclerView.setItemsChangedListener(this);
#override
public void onItemsChanged(int sum) {
//Update TextView
}