android recyclerview scroll making mess in chat using firebase - android

I'm simply implementing a RecyclerView for showing chat between two. Everything is working fine but there is one problem when I am scrolling up and again scrolling down the direction of sender message goes left(GRAVITY) which I have set only for the received ones. Please look the code below hope u will understand.
Screenshot before scrolling.
Screenshot after scrolling.
Here's my RecycleActivity.java
public class RecycleActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference databaseReference,temp;
EditText editText;
Button btnSend;
public static String nameOFUser = "";
LinearLayoutManager linearLayoutManager;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainer);
sharedPreferences = getSharedPreferences("MyLoginPref",MODE_PRIVATE);
nameOFUser = sharedPreferences.getString("name","");
Log.e("name",nameOFUser);
recyclerView = (RecyclerView) findViewById(R.id.recyclerid);
recyclerView.setHasFixedSize(true);
linearLayoutManager= new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
databaseReference = FirebaseDatabase.getInstance().getReference().child("msg");
editText = (EditText) findViewById(R.id.edittextmessagetosend);
btnSend = (Button) findViewById(R.id.button41);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
temp=databaseReference.push();
temp.child("name").setValue(nameOFUser);
temp.child("message").setValue(editText.getText().toString().trim());
editText.setText("");
recyclerView.setLayoutManager(linearLayoutManager);
}
});
}
#Override
protected void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<MessageBlog,MessageHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<MessageBlog, MessageHolder>(
MessageBlog.class,R.layout.message_row,MessageHolder.class,databaseReference
) {
#Override
protected void populateViewHolder(MessageHolder viewHolder, MessageBlog model, int position) {
String name = model.getName();
viewHolder.setSender(name);
viewHolder.SetMessage(model.getMessage());
viewHolder.setDirection(name);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
recyclerView.smoothScrollToPosition(firebaseRecyclerAdapter.getItemCount());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
The ViewHolder.java
public static class MessageHolder extends RecyclerView.ViewHolder{
View view;
LinearLayout lay,linearLayoutback;
CardView cardViewreal;
DatabaseReference mdatabase;
public MessageHolder(View itemView) {
super(itemView);
view = itemView;
linearLayoutback = (LinearLayout)
itemView.findViewById(R.id.linearlayoutback);
mdatabase=FirebaseDatabase.getInstance().getReference().child("msg");
lay = (LinearLayout) itemView.findViewById(R.id.idcardview);
cardViewreal = (CardView) itemView.findViewById(R.id.idrealcard);
}
void setDirection(final String name){
if(!name.equalsIgnoreCase(nameOFUser)) {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#ffffff"));
} else {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#f5f4f5"));
}
}
void setSender(String sender){
TextView tvsender = (TextView) view.findViewById(R.id.senderidtv);
tvsender.setText(sender);
}
void SetMessage(String message){
TextView tvmessage = (TextView) view.findViewById(R.id.messageidtv);
tvmessage.setText(message);
}
}

Check your set direction method. It always sets direction to the left
void setDirection(final String name){
if(!name.equalsIgnoreCase(nameOFUser)) {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#ffffff"));
//linearLayoutback.setBackgroundResource(R.drawable.white);
}
else{
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#f5f4f5"));
// linearLayoutback.setBackgroundResource(R.drawable.white);
}

Related

Error - com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String

I am getting error
"com.google.firebase.database.DatabaseException:
Can't convert object of type java.lang.String to type
krunoslavkovac.ferit.test.Add"
And can't figure it out why is it happening.
I've searched many solutions here but still didn't figure it out.
MAIN ACTIVITY :
public class MainActivity extends AppCompatActivity {
EditText et_task ;
Button btn_add;
RecyclerView recycler_view;
//Firebase
FirebaseDatabase database;
DatabaseReference dbRef ;
FirebaseRecyclerOptions<Add> options;
FirebaseRecyclerAdapter<Add, MyRecyclerViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_task = (EditText) findViewById(R.id.et_task);
btn_add = (Button) findViewById(R.id.btn_add);
recycler_view = (RecyclerView) findViewById(R.id.recycler_view);
recycler_view.setLayoutManager(new LinearLayoutManager(this));
database = FirebaseDatabase.getInstance();
dbRef = database.getReference("Test");
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTask();
}
});
displayTask();
}
private void addTask(){
String task = et_task.getText().toString();
Add add = new Add(task);
dbRef.push().setValue(task);
adapter.notifyDataSetChanged();
}
private void displayTask() {
options =
new FirebaseRecyclerOptions.Builder<Add>()
.setQuery(dbRef,Add.class)
.build();
adapter =
new FirebaseRecyclerAdapter<Add, MyRecyclerViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyRecyclerViewHolder holder, int position, #NonNull Add model) {
holder.tv_task.setText(model.getTask());
}
#NonNull
#Override
public MyRecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(getBaseContext()).inflate(R.layout.add_item,viewGroup, false);
return new MyRecyclerViewHolder(itemView);
}
};
adapter.startListening();
recycler_view.setAdapter(adapter);
}
}
Add class
public class Add {
private String task;
public Add(){
}
public Add(String task) {
this.task = task;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
}
RecyclervViewHolder
public class MyRecyclerViewHolder extends RecyclerView.ViewHolder {
TextView tv_task;
public MyRecyclerViewHolder(#NonNull View itemView) {
super(itemView);
tv_task = (TextView) itemView.findViewById(R.id.tv_task);
}
}
Database:
I want to display data from firebase.
Replace this
dbRef.push().setValue(task);
To
dbRef.push().setValue(add);

Recyclerview loads after I exit and reenter activity or when i press back button

I have a recyclerview in my app, but it only loads the data after i exit and re-enter the activity. I have tried the threads below,but couldn't get mine to work.
RecyclerView not populating the first time I enter the activity but showing after i exit and re-enter the activity
RecyclerView doesn't load items on first start of activity
I tried,
adapter.notifyDataSetChanged()
and still didn't work
Main Activity
public class Review1 extends AppCompatActivity {
private RecyclerView recent_patients_list;
private FirebaseAuth mAuth;
public static final String REVIEW_ID ="review_id";
FirebaseRecyclerAdapter<Patients, PatientsViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review1);
///Firebase Authentication
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String uId = mUser.getUid();
Query query = FirebaseDatabase.getInstance().getReference().child("Patients").child(uId).limitToLast(50);
query.keepSynced(true);
recent_patients_list = findViewById(R.id.recycler);
recent_patients_list.setHasFixedSize(true);
///FirebaseUI RecyclerView
FirebaseRecyclerOptions<Patients> options =
new FirebaseRecyclerOptions.Builder<Patients>()
.setQuery(query, Patients.class)
.build();
adapter = new FirebaseRecyclerAdapter<Patients, PatientsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull PatientsViewHolder holder, final int position, #NonNull Patients model) {
holder.setTitle(model.getName());
holder.setNote(model.getResidence());
holder.setNote1(model.getOccupation());
holder.setDate(model.getDate());
//To get the id and pass to Review2
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user_id = getRef(position).getKey(); //// get key to use in Review2.java
Intent intent = new Intent(getApplicationContext(),Review2.class);
intent.putExtra(REVIEW_ID, user_id);/// pass key into intent
startActivity(intent);
}
});
}
#NonNull
#Override
public PatientsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.patient_listview,viewGroup,false);
return new PatientsViewHolder(view);
}
};
recent_patients_list.setLayoutManager(new LinearLayoutManager(this));
recent_patients_list.setAdapter(adapter);///setting adapter for the recyclerView
adapter.startListening();
adapter.notifyDataSetChanged();
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
adapter.notifyDataSetChanged();
}
////ViewHolder for firebase recycler view
private class PatientsViewHolder extends RecyclerView.ViewHolder {
View mView;
public PatientsViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView mTitle = mView.findViewById(R.id.Title);
mTitle.setText("Name:" + title);
}
public void setNote(String note){
TextView mNote = mView.findViewById(R.id.other);
mNote.setText("Location:" + note);
}
void setNote1(String note1){
TextView mNote1 = mView.findViewById(R.id.other2);
mNote1.setText("Occupation" +note1);
}
public void setDate(String date){
TextView mDate = mView.findViewById(R.id.date);
mDate.setText(date);
}
}
}
Is there anything am missing?
Any suggestions or ideas?
Try to use: adapter.startListening(); before -> recent_patients_list.setAdapter(adapter); and remove adapter.notifyDataSetChanged(); from onCreate
And also modify your onStart() like:
#Override
protected void onStart() {
super.onStart();
}
You are doing nothing in onPause !

Add button to FirebaseUI ViewHolder

well im doing a recycler view with a database on firebase . that is working perfectly... now i want to implement a share button but i cant make the button reference each img. i found a tutorial to do so but when i try to implement this line (if i remove it the apps goes well but doest reference to the button position)
public BlogViewHolder(View itemView) {
...
button = (Button)mView.findViewById(R.id.share);
...
the app crashes when i open the activity
im only using toast to testing.
public class NoticiasActivity extends AppCompatActivity {
private RecyclerView mBlogList;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noticias);
//Recycler View
mBlogList = (RecyclerView)findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
// Send a Query to the database
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Data");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<ModelClass, BlogViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<ModelClass, BlogViewHolder>(
ModelClass.class,
R.layout.design_row,
BlogViewHolder.class,
myRef) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, ModelClass model,int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "esto es un boton"+ view.getNextFocusUpId(), Toast.LENGTH_SHORT).show();
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
//View Holder For Recycler View
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
Button button ;
public BlogViewHolder(View itemView) {
super(itemView);
button = (Button)mView.findViewById(R.id.share);
mView= itemView;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// click en la imagen hace algo
//aƱadir luego
Toast.makeText(v.getContext(), "hola", Toast.LENGTH_SHORT).show();
}
});
}
public void setTitle(String title){
TextView post_title = (TextView)mView.findViewById(R.id.titleText);
post_title.setText(title);
}
public void setImage(Context ctx , String image){
ImageView post_image = (ImageView)mView.findViewById(R.id.imageViewy);
// We Need TO pass Context
Picasso.with(ctx).load(image).into(post_image);
}
}
}
You need to switch these lines
button = (Button)mView.findViewById(R.id.share);
mView= itemView;
Or find the button from the itemView

Passing values from recyclerview cardview to deatilactivity onitemclick

I'm new to android development, I have been trying to pass values from recyclerview cardview to detailActivity, after searching for couple of hours I came up with this code, before implementing this code I was able to view all the cardview on MainActivity, Now when I implemented this code app is crashing when I start the app, event log.
This is my Fragment which contain Firebaserecycler Adapter and viewholder class:
public class MakingFragment extends Fragment {
private FloatingActionButton fab;
ScaleAnimation shrinkAnim;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private TextView tvNoMovies;
Context c;
ArrayList<Food> spacecrafts;
//Getting reference to Firebase Database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = database.getReference();
private static final String userId = "53";
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.making,container,false);
//Initializing our Recyclerview
mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
tvNoMovies = (TextView) v.findViewById(R.id.tv_no_movies);
//scale animation to shrink floating actionbar
shrinkAnim = new ScaleAnimation(1.15f, 0f, 1.15f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
if (mRecyclerView != null) {
//to enable optimization of recyclerview
mRecyclerView.setHasFixedSize(true);
}
//using staggered grid pattern in recyclerview
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mLayoutManager.setReverseLayout(true); // to reverse the items updating on recycleview
mLayoutManager.setStackFromEnd(true); // to scroll from top when layout is reversed
//Say Hello to our new FirebaseUI android Element, i.e., FirebaseRecyclerAdapter
FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
Food.class,
R.layout.food_item,
FoodViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("food").getRef()
) {
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, final Food model, int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvFoodName.setText(model.getFoodName());
viewHolder.ratingBar.setRating(model.getFoodRating());
viewHolder.tvFoodCategory.setText(model.getFoodCategory());
viewHolder.tvFoodAvailableUpto.setText(model.getFoodAvailableUpto());
viewHolder.tvFoodPrice.setText(model.getFoodPrice());
Picasso.with(getActivity().getApplicationContext()).load(model.getFoodPoster()).into(viewHolder.ivFoodPoster);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
//OPEN DETAI ACTIVITY
openDetailActivity(model.getFoodName(),model.getFoodCategory(),model.getFoodAvailableUpto(),model.getFoodPrice());
}
});
}
#Override
public int getItemCount() {
return spacecrafts.size();
}
//OPEN DETAIL ACTIVITY
private void openDetailActivity(String...details)
{
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("TITLE_KEY",details[0]);
i.putExtra("CAT_KEY",details[1]);
i.putExtra("AVAIL_KEY",details[2]);
i.putExtra("PRI_KEY",details[3]);
c.startActivity(i);
}
};
mRecyclerView.setAdapter(adapter);
fab = (FloatingActionButton) v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchactivity=new Intent(getActivity().getApplicationContext(),AddFoodDetailsActivity.class);
startActivity(launchactivity);
//animation being used to make floating actionbar disappear
shrinkAnim.setDuration(400);
fab.setAnimation(shrinkAnim);
shrinkAnim.start();
shrinkAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//changing floating actionbar visibility to gone on animation end
fab.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
return v;
}
public void onBackPressed() {
getActivity().onBackPressed();
if (fab.getVisibility() == View.GONE)
fab.setVisibility(View.VISIBLE);
}
//ViewHolder for our Firebase UI
public static class FoodViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvFoodName;
RatingBar ratingBar;
ImageView ivFoodPoster;
TextView tvFoodCategory;
TextView tvFoodAvailableUpto;
TextView tvFoodPrice;
ImageView ivNextArrow;
ItemClickListener itemClickListener;
public FoodViewHolder(View v) {
super(v);
tvFoodName = (TextView) v.findViewById(R.id.tvName);
ratingBar = (RatingBar) v.findViewById(R.id.rating_bar);
ivFoodPoster = (ImageView) v.findViewById(R.id.imgThumb);
tvFoodCategory = (TextView) v.findViewById(R.id.tvCategory);
tvFoodAvailableUpto= (TextView) v.findViewById(R.id.tvavailable);
tvFoodPrice = (TextView) v.findViewById(R.id.tvprice);
ivNextArrow = (ImageView) v.findViewById(R.id.NextArrow);
v.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
#Override
public void onClick(View view) {
this.itemClickListener.onItemClick(this.getLayoutPosition());
}
}
}
This is my DetailActivity
public class DetailActivity extends AppCompatActivity {
TextView nameTxt,catTxt,availTxt,priceTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nameTxt = (TextView) findViewById(R.id.titleTxt);
catTxt= (TextView) findViewById(R.id.catTxt);
availTxt = (TextView) findViewById(R.id.availTxt);
priceTxt = (TextView) findViewById(R.id.pricesTxt);
//GET INTENT
Intent i=this.getIntent();
//RECEIVE DATA
String title=i.getExtras().getString("TITLE_KEY");
String cat=i.getExtras().getString("CAT_KEY");
String avail=i.getExtras().getString("AVAIL_KEY");
String price=i.getExtras().getString("PRI_KEY");
//BIND DATA
nameTxt.setText(title);
catTxt.setText(cat);
availTxt.setText(avail);
priceTxt.setText(price);
}
}
Please help me out, thank you.
Initialize the arraylist in oncreate()
spacecrafts= new ArrayList<>();
also these in oncreate()
database = FirebaseDatabase.getInstance();
mDatabaseReference = database.getReference();
and check spacecrafts is null or not

Unable to load more than one row using FirebaseRecyclerAdapter

I am trying to fetch the data from firebase, using firebaseRecyclerAdapter. But I am unable to populate all the data from the firebase database to the RecyclerView.
Database is as follows:
The output I am getting is only from the "qqq" row
rvlist Class:
public class rvlist {
String name, propellant;
public rvlist() {
}
public rvlist(String name, String propellant) {
this.name = name;
this.propellant = propellant;
}
public String getName() {
return name;
}
public String getPropellant() {
return propellant;
}
}
MyViewHolder:
public class MyViewHolder extends RecyclerView.ViewHolder {
View mView;
public MyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView field = (TextView) mView.findViewById(R.id.a);
field.setText(name);
}
public void setPropellant(String text) {
TextView field = (TextView) mView.findViewById(R.id.b);
field.setText(text);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseReference mRef;
RecyclerView rv;
ProgressBar pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pb = (ProgressBar)findViewById(R.id.pb);
pb.setVisibility(View.VISIBLE);
rv = (RecyclerView) findViewById(R.id.rvv);
rv.setLayoutManager(new LinearLayoutManager(this));
mRef = FirebaseDatabase.getInstance().getReference().child("table");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<rvlist, MyViewHolder> recyclerAdapter = new FirebaseRecyclerAdapter<rvlist, MyViewHolder>
(rvlist.class, R.layout.model, MyViewHolder.class, mRef) {
#Override
public void populateViewHolder(MyViewHolder itemsViewHolder, rvlist items, int position) {
pb.setVisibility(View.GONE);
itemsViewHolder.setName(items.getName());
itemsViewHolder.setPropellant(items.getPropellant());
}
};
rv.setAdapter(recyclerAdapter);
}
}
Make sure your RecyclerView and adapter layout_height is set to wrap_content not to match_parent
<android.support.v7.widget.RecyclerView
android:id="#+id/recv_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="LinearLayoutManager"
...>
</android.support.v7.widget.RecyclerView>

Categories

Resources