I am trying to come up with a chat app using Firebase Recycler adapter. The problem is that the sender's and receiver's chats are not displayed as expected. All the chats are displayed on the right. Despite the text being "Morning", the text is displayed as "Hello".
Below is my code
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ultramodern.activity.besha.Adapter.MessageAdapter;
import ultramodern.activity.besha.Model.Chat;
import ultramodern.activity.besha.Model.Users;
public class Complete_new_Group extends AppCompatActivity implements View.OnClickListener{
Button fab,paybtn, depobtn, borrowbtn, borrowicon, depoicon, payicon;
CircleImageView sendtextbutton;
EditText text_send;
RecyclerView chatrecyclerView;
MessageAdapter messageAdapter;
public static final int MESSAGE_RIGHT=0;
public static final int MESSAGE_LEFT=1;
//private String user_id;
#Override
protected void onCreate(Bundle savedInstanceState) { ;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete_new__group);
Toast.makeText(this, "This area is still under development", Toast.LENGTH_LONG).show();
fab = findViewById(R.id.fab_complete_group);
paybtn = findViewById(R.id.button6);
depobtn = findViewById(R.id.button5);
borrowbtn = findViewById(R.id.button3);
borrowicon = findViewById(R.id.button8);
depoicon = findViewById(R.id.button9);
payicon = findViewById(R.id.button10);
sendtextbutton = findViewById(R.id.sendtextButton);
text_send = findViewById(R.id.text_send);
chatrecyclerView = findViewById(R.id.chatrecycler);
chatrecyclerView.setLayoutManager(new LinearLayoutManager(this));
fab.setOnClickListener(this);
paybtn.setOnClickListener(this);
depobtn.setOnClickListener(this);
borrowbtn.setOnClickListener(this);
borrowicon.setOnClickListener(this);
depoicon.setOnClickListener(this);
payicon.setOnClickListener(this);
sendtextbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = text_send.getText().toString();
if (!message.equals("")){
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String userId = getIntent().getStringExtra("userId");
sendmessage(message,userId,firebaseUser.getUid());
}
else {
Toast.makeText(Complete_new_Group.this, "You can't send an empty message", Toast.LENGTH_SHORT).show();
}
text_send.setText("");
}
});
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final String user_id;
Intent intent = getIntent();
user_id = intent.getStringExtra("userId");
assert user_id != null;
// Log.d("TRACK",user_id);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Users users = snapshot.getValue(Users.class);
readMessage(firebaseUser.getUid(),user_id,users.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onClick(View view) {
if (view==fab){
paybtn.setVisibility(View.VISIBLE);
depobtn.setVisibility(View.VISIBLE);
borrowbtn.setVisibility(View.VISIBLE);
borrowicon.setVisibility(View.VISIBLE);
depoicon.setVisibility(View.VISIBLE);
payicon.setVisibility(View.VISIBLE);
}
if (view==paybtn){
Intent intent = new Intent(getApplicationContext(),Group_pay.class);
startActivity(intent);
}
if (view==payicon){
Intent intent = new Intent(getApplicationContext(),Group_pay_icon_activity.class);
startActivity(intent);
}
if (view==depobtn){
Intent intent = new Intent(getApplicationContext(),Group_deposit_button_activity.class);
startActivity(intent);
}
if (view==depoicon){
Intent intent = new Intent(getApplicationContext(),Group_depo_icon_activity.class);
startActivity(intent);
}
if (view==borrowbtn){
Intent intent = new Intent(getApplicationContext(),Group_deposit_button_activity.class);
startActivity(intent);
}
if (view==borrowicon){
Intent intent = new Intent(getApplicationContext(),Group_borrow_icon_activity.class);
startActivity(intent);
}
if (view==sendtextbutton){
}
}
private void sendmessage(String message,String sender, String reciever){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("sender",sender);
hashMap.put("reciever",reciever);
hashMap.put("message",message);
reference.child("Chats").push().setValue(hashMap);
}
private void readMessage(final String myId, final String userId, String imageURL){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
FirebaseRecyclerOptions<Chat> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Chat>().setQuery(databaseReference, new SnapshotParser<Chat>() {
#NonNull
#Override
public Chat parseSnapshot(#NonNull DataSnapshot snapshot) {
String message = String.valueOf(snapshot.child("message").getValue());
String sender = String.valueOf(snapshot.child("sender").getValue());
String receiver = String.valueOf(snapshot.child("reciever").getValue());
return new Chat(message,sender,receiver);
}
}).build();
final FirebaseRecyclerAdapter<Chat,ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Chat,ViewHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull final ViewHolder viewHolder, int i, #NonNull Chat chat) {
if (chat.getReceiver().equals(userId) && chat.getSender().equals(myId) || chat.getReceiver()
.equals(myId) && chat.getSender().equals(userId)){
viewHolder.showMessage.setText(chat.getMessage());
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MESSAGE_RIGHT){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_right,parent,false);
return new ViewHolder(view);
}
else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_left,parent,false);
return new ViewHolder(view);
}
}
#Override
public int getItemViewType(int position) {
Chat chat = getItem(position);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (chat.getSender().equals(firebaseUser.getUid())){
return MESSAGE_LEFT;
}
else {
return MESSAGE_RIGHT;
}
//return super.getItemViewType(position);
}
};
chatrecyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView showMessage;
public ImageView profilepic;
public ViewHolder(#NonNull View itemView) {
super(itemView);
showMessage=itemView.findViewById(R.id.showMessage);
profilepic=itemView.findViewById(R.id.profilepic);
}
public void setText(String paramString){
this.showMessage.setText(paramString);
}
}
}
This is the output on both the sender and the receiver
I need some assistance
Related
I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
i'm building an application that connects to my Drupal API. Somehow i'm not getting any data display within my application. I don't see any errors in the code and the debugging online gives the follow error: E/RecyclerView: No adapter attached; skipping layout
Here is my MainActivity code:
package com.example.eindopdrachtcmsapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity implements ExampleAdapter.onItemClickListener {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_BODY = "body";
public static final String EXTRA_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://vistudio.be/api/portfolio";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject portfolio = response.getJSONObject(i);
String title = portfolio.getString("title");
String body = portfolio.getString("body");
String link = portfolio.getString("field_website_url");
mExampleList.add(new ExampleItem(title, body, link));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
detailIntent.putExtra(EXTRA_BODY, clickedItem.getBody());
detailIntent.putExtra(EXTRA_LINK, clickedItem.getLink());
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
startActivity(detailIntent);
}
}
My Adapter code:
package com.example.eindopdrachtcmsapi;
import android.content.Context;
import android.graphics.PorterDuffColorFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.portfolioViewHolder>{
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private onItemClickListener mListener;
private onItemClickListener mListenerShare;
public interface onItemClickListener{
void onItemClick(int position);
}
public void setOnClickListener(onItemClickListener listener, onItemClickListener listenerShare){
mListener = listener;
mListenerShare = listenerShare;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> ExampleList) {
mContext = context;
mExampleList = ExampleList;
}
#Override
public portfolioViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.exampleitem, parent, false);
return new portfolioViewHolder(v);
}
#Override
public void onBindViewHolder(portfolioViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
String body = currentItem.getBody();
String link = currentItem.getLink();
holder.mTextViewTitle.setText(title);
holder.mTextViewBody.setText(body);
holder.mTextViewLink.setText(link);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class portfolioViewHolder extends RecyclerView.ViewHolder{
public TextView mTextViewTitle;
public TextView mTextViewBody;
public TextView mTextViewLink;
public Button mButton;
public portfolioViewHolder(View itemView) {
super(itemView);
mTextViewTitle = itemView.findViewById(R.id.text_view_title);
mTextViewBody = itemView.findViewById(R.id.text_view_body);
mTextViewLink = itemView.findViewById(R.id.text_view_link);
mButton = itemView.findViewById(R.id.share);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListenerShare != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListenerShare.onItemClick(position);
}
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
first remove inside oncreate()
mRecyclerView.setAdapter(mExampleAdapter);
after this code
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
add this:-
mExampleAdapter.notifyDataSetChanged();
I want to get an int value from my adapter class to my activity but I am getting nothing while using this code:
Here is my adapter:
package com.capi.ccecommerceapp.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder>
{
private Context context;
private List<Cart> cartList;
private String productImage;
public int overTotalPrice = 0;
public CartAdapter(Context context, List<Cart> cartList ) {
this.context = context;
this.cartList = cartList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cart_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.cartName.setText(cartList.get(position).getProductName());
holder.cartPrice.setText(cartList.get(position).getProductPrice());
holder.cart_qty.setText(String.valueOf(cartList.get(position).getProductQuantity()));
int oneTypeProductTPrice = ((Integer.parseInt(cartList.get(position).getProductPrice()))) * cartList.get(position).getProductQuantity();
overTotalPrice = overTotalPrice + oneTypeProductTPrice;
/*FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();*/
/* holder.cartPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty<10)
{
cartQty++;
}
}
});
holder.cartMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty>1)
{
cartQty--;
}
}
});
holder.cart_qty.setText(cartQty);
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cartList.remove(cartList.get(position));
}
});*/
/* holder.wishlistBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.wishlistBtn.getTag().equals("add"))
{
holder.wishlistBtn.setImageResource(R.drawable.ic_love_fill);
holder.wishlistBtn.setTag("added");
}
else
{
holder.wishlistBtn.setImageResource(R.drawable.love);
holder.wishlistBtn.setTag("add");
}
}
});*/
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Products")
.child(cartList.get(position).getProductId())
.child("productImage");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if (snapshot.exists()) {
productImage = snapshot.getValue(String.class);
Glide.with(context).load(productImage).into(holder.cartImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return cartList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView cartImage;
TextView cartName;
TextView cartPrice;
ImageView wishlistBtn;
ImageView deleteBtn;
ImageView cartPlus;
ImageView cartMinus;
TextView cart_qty;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cartImage = itemView.findViewById(R.id.cart_image);
cartName = itemView.findViewById(R.id.cart_name);
cartPrice = itemView.findViewById(R.id.cart_price);
wishlistBtn = itemView.findViewById(R.id.add_to_wishlist);
deleteBtn = itemView.findViewById(R.id.delete_cart);
cartPlus = itemView.findViewById(R.id.cart_add);
cartMinus = itemView.findViewById(R.id.cart_minus);
cart_qty = itemView.findViewById(R.id.cart_quantity);
}
}
}
and here is my activity code where I want to set it in textView:
package com.capi.ccecommerceapp.Fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.capi.ccecommerceapp.Adapter.CartAdapter;
import com.capi.ccecommerceapp.address.ShiptoActivity;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CartFragment extends Fragment
{
private RecyclerView cartRecyclerView;
private List<Cart> cartList;
private CartAdapter cartAdapter;
private Button next;
private FirebaseAuth auth;
private FirebaseUser user;
private TextView subtotal;
private TextView items;
private TextView shipping;
private TextView totalPrice;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
cartRecyclerView = view.findViewById(R.id.cartRecycler);
next = view.findViewById(R.id.checkout_btn);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), ShiptoActivity.class));
}
});
subtotal = view.findViewById(R.id.subtotal_price);
items = view.findViewById(R.id.items);
shipping = view.findViewById(R.id.shipping_price);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
cartRecyclerView.setLayoutManager(layoutManager);
cartList = new ArrayList<>();
cartAdapter = new CartAdapter(getContext(), cartList);
cartRecyclerView.setAdapter(cartAdapter);
loadCart();
return view;
}
private void loadCart()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Cart")
.child(user.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren())
{
Cart cart = dataSnapshot.getValue(Cart.class);
cartList.add(cart);
}
cartAdapter.notifyDataSetChanged();
subtotal.setText("$" + cartAdapter.overTotalPrice);
items.setText("Items("+cartAdapter.getItemCount()+")");
int shippingPrice = (cartAdapter.overTotalPrice / 20);
shipping.setText("$" + shippingPrice);
/*int totalPriceFinal = shippingPrice + cartAdapter.getOverTotalPrice();
totalPrice.setText("$" + totalPriceFinal);*/
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I want to get this int:public int overTotalPrice = 0;
And I am getting it as:subtotal.setText("$"+cartAdapter.overTotalPrice);
Anyone have a solution?
???????????????????????
????????????????????
??????????????????????
So, I'm not sure about the title of this question but here it goes. I have a recyclerview for my chat room. The first time the activity started it has no problem displaying the messages but after pressing the back button back to the main activity showing all chat rooms then click the same chat room again it displays nothing. Then, after sent a message it can display all the messages again. I'm not sure what happened, help, please. Oh, I already tried a few things and browse the internet but because I'm not sure what the keyword is, so I'm quite stuck now
Okay, here is the thing
First main activity, (ignore the other 2 tabs, it's empty)
Main Activity
Then open a chat room
First time open chat room fine
Then press back button, back to MainActivity, then open the same room and no chat displayed
chat room not displaying anything
Then it displays messages again after sending a new messages
new message
I have tried to place notifyDataSetChanged() on various event like onStart, onCreate etc but nothing works;
here is my chat activity
package com.divistant.chat.ui.chat;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.divistant.chat.R;
import com.divistant.signup.UserModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
LinearLayout layout;
ImageView send;
EditText message;
ScrollView scrollView;
DatabaseReference refrence1;
DatabaseReference refrence2;
RecyclerView rv;
List<ChatModel> chats = new ArrayList<>();
ChatActivityAdapter adapter;
FirebaseUser cUser;
UserModel target;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Log.w("EVENT","ON Create");
Intent intent = getIntent();
target = (new Gson()).fromJson(intent.getStringExtra("target"),UserModel.class);
send = (ImageView)findViewById(R.id.sendButton);
message = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
rv = (RecyclerView) findViewById(R.id.main_chat_rv);
cUser = FirebaseAuth.getInstance().getCurrentUser();
adapter = new ChatActivityAdapter(chats);
final LinearLayoutManager manager = new LinearLayoutManager(ChatActivity.this,
LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(manager);
refrence1 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(cUser.getUid() + "_" + target.getUserId());
refrence2 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(target.getUserId() + "_" + cUser.getUid());
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("SEND","send message");
if(message.getText().toString().length() > 0){
ChatModel chat = new ChatModel();
chat.setSender(cUser.getEmail());
chat.setMessage(message.getText().toString());
chat.setReceiver(target.getEmailAddress());
chat.setSenderUid(cUser.getUid());
chat.setReceiverUid(target.getUserId());
chat.setTimestamp((new Date()).getTime());
DatabaseReference ref1 = refrence1.push();
ref1.setValue(chat);
DatabaseReference ref2 = refrence2.push();
ref2.setValue(chat);
message.setText("");
}
}
});
refrence1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
Log.e("[CH]","DATACHANGE " + chats.size());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","CANCEL");
}
});
refrence1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","DB CHANGE");
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Log.e("[CH]","DB REMOVE");
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","Child Moved");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","DB ERROR");
}
});
rv.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
Log.e("[CH]","" + adapter.getItemCount());
}
}
Then, here is my ChatActivityAdapter
package com.divistant.chat.ui.chat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.divistant.chat.R;
import com.google.firebase.auth.FirebaseAuth;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int VIEW_TYPE_ME = 1;
private static final int VIEW_TYPE_OTHER = 2;
List<ChatModel> mChats;
public void setmChats(List<ChatModel> mChats) {
this.mChats = mChats;
}
public ChatActivityAdapter(List<ChatModel> mChats) {
this.mChats = mChats;
Log.e("ADAPTER","CONSTRUCTED " + mChats.size());
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case VIEW_TYPE_ME:
View viewChatMine = layoutInflater.inflate(R.layout.chat_item, parent, false);
viewHolder = new MyChatViewHolder(viewChatMine);
break;
case VIEW_TYPE_OTHER:
View viewChatOther = layoutInflater.inflate(R.layout.chat_item_other, parent, false);
viewHolder = new OtherChatViewHolder(viewChatOther);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
configureMyChatViewHolder((MyChatViewHolder) holder, position);
} else {
configureOtherChatViewHolder((OtherChatViewHolder) holder, position);
}
}
private void configureMyChatViewHolder(final MyChatViewHolder myChatViewHolder, int position) {
ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
myChatViewHolder.senderMsgTime.setText(date);
myChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
private void configureOtherChatViewHolder(final OtherChatViewHolder otherChatViewHolder, int position) {
final ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
otherChatViewHolder.receiverMsgTime.setText(date);
otherChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChats.size();
}
#Override
public int getItemViewType(int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
return VIEW_TYPE_ME;
} else {
return VIEW_TYPE_OTHER;
}
}
private static class MyChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView senderMsgTime;
public MyChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet);
senderMsgTime=(TextView) itemView.findViewById(R.id.senderMsgTime);
}
}
private static class OtherChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView receiverMsgTime;
public OtherChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message_ot);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet_ot);
receiverMsgTime=(TextView) itemView.findViewById(R.id.receiverMsgTime_ot);
}
}
}
Thanks
Thats because you are clearing the list on childevent listener and not adding the new child in list and not passing the list to the adapter.
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
Now change the code by adding the lines
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
in my case i used onResume()
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
Can you put rv.setAdapter(adapter) after rv.setLayoutManager(manager);?
And you verify if the method onDataChange(...) its always called??
You can use the following code in the adapter where you want to refresh recyclerview, for example in #Override public void onBackPressed(){} function. If your chats array changed, you should refresh this adapter.
mAdapter = new ChatActivityAdapter(context, chats.get(chats.size() - 1), chats);
recyclerView.setAdapter(mAdapter);
I am creating a chat app in which Users can create groups. when a users creates a group, he/she can choose a group profile image. but if i choose the image, it wont upload. what to do?
I have inspected the code, there is no error anywhere
CreateGroupActivity.java:
package com.satyamedh.chitchatmessenger;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import de.hdodenhof.circleimageview.CircleImageView;
public class CreateGroupActivity extends AppCompatActivity
{
private CircleImageView circleImageView;
private EditText editText;
private Button buttonconf, buttoncanc;
private Uri resultUri;
private final static int chosenProfileImage = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_group);
initializeFields();
buttoncanc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(CreateGroupActivity.this, MainActivity.class);
startActivity(profileIntent);
}
});
buttonconf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText.getText())){
Toast.makeText(CreateGroupActivity.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
else
{
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
Intent settingsIntent = new Intent(CreateGroupActivity.this, chooseUserActivity.class);
String key = rootref.push().getKey();
settingsIntent.putExtra("groupKey", key);
settingsIntent.putExtra("groupImage", resultUri);
settingsIntent.putExtra("groupName", editText.getText().toString());
startActivity(settingsIntent);
}
}
});
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, chosenProfileImage);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == chosenProfileImage && resultCode == RESULT_OK && data != null)
{
Uri imageUri = data.getData();
CropImage
.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK) {
resultUri = result.getUri();
circleImageView.setImageURI(resultUri);
}
}
}
private void initializeFields()
{
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.my_adView_createGroup);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
circleImageView = findViewById(R.id.create_group_image);
editText = findViewById(R.id.create_group_name);
buttonconf = findViewById(R.id.confirm_button);
buttoncanc = findViewById(R.id.cancel_button);
}
}
chooseUserActivity.java:
package com.satyamedh.chitchatmessenger;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {#link Fragment} subclass.
*/
public class chooseUserActivity extends AppCompatActivity {
private RecyclerView myRecyclerList;
private DatabaseReference ContactsRef, UsersRef;
private String currentUID;
private DatabaseReference groupsRef;
private Button confirmButton;
private String downloadUrl ;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_choose_user);
super.onCreate(savedInstanceState);
initializeFields();
}
private void initializeFields()
{
myRecyclerList = findViewById(R.id.users_choser_group);
myRecyclerList.setLayoutManager(new LinearLayoutManager(chooseUserActivity.this));
FirebaseAuth mAuth = FirebaseAuth.getInstance();
currentUID = mAuth.getCurrentUser().getUid();
ContactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
confirmButton = findViewById(R.id.confirm_group);
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.choose_user_adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
Toolbar toolbar = findViewById(R.id.users_chosers_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Choose users to be in " + getIntent().getExtras().get("groupName").toString());
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContactsRef, Contacts.class)
.build()
;
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>
adapter = new
FirebaseRecyclerAdapter <Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, final int position, #NonNull Contacts model)
{
final String string = getRef(position).getKey();
final String[] image = {"default_image"};
UsersRef
.child(string)
.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.hasChild("image"))
{
image[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(image[0]).placeholder(R.drawable.profile_image).into(holder.profileImageView);
}
final String name = dataSnapshot.child("name").getValue().toString();
holder.Username.setText(name);
holder.Userstatus.setText("Last seen: \n");
if(dataSnapshot.child("userState").hasChild("state"))
{
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if(Objects.equals(state, "online"))
{
holder.Userstatus.setText(getString(R.string.Online));
}
else
{
holder.Userstatus.setText(getString(R.string.last_seen) + time + " " + date);
}
}
else
{
holder.Userstatus.setText("Offline");
}
final HashMap<String, Object> hashMap = new HashMap<>();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!hashMap.containsKey(getRef(position).getKey())) {
holder.itemView.setPadding(15, 15, 15, 15);
holder.IsUserInGroup.setVisibility(View.VISIBLE);
if (hashMap.isEmpty()) {
hashMap.put(currentUID, "admin");
}
hashMap.put(getRef(position).getKey(), "non-admin");
}
else {
holder.itemView.setPadding(0, 0, 0, 0);
if (hashMap.size() == 1)
{
hashMap.remove(currentUID, "admin");
}
holder.IsUserInGroup.setVisibility(View.INVISIBLE);
hashMap.remove(getRef(position).getKey(), "non-admin");
}
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
}
});
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
final StorageReference ProfileImagesRef;
ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Groups profile images");
final StorageReference ref = ProfileImagesRef.child(getIntent().getExtras().get("groupKey").toString() + ".jpg");
ref.putFile((Uri) getIntent().getExtras().get("groupImage"))
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri)
{
Toast.makeText(chooseUserActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
downloadUrl = uri.toString();
}
});
}
});
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
groupsRef.child("Users").updateChildren(hashMap);
groupsRef.child("Messages").setValue("");
groupsRef.child("Group info").child("group name").setValue(getIntent().getExtras().get("groupName").toString());
groupsRef.child("Group info").child("group image").setValue(downloadUrl);
Toast.makeText(chooseUserActivity.this, "Group created successfully", Toast.LENGTH_SHORT).show();
Intent settingsIntent = new Intent(chooseUserActivity.this, MainActivity.class);
settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(settingsIntent);
finish();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
myRecyclerList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder
{
CircleImageView profileImageView;
TextView Username, Userstatus;
CheckBox IsUserInGroup;
ChatsViewHolder(#NonNull View itemView)
{
super(itemView);
profileImageView = itemView.findViewById(R.id.users_profile_image);
Username = itemView.findViewById(R.id.users_name);
Userstatus = itemView.findViewById(R.id.users_status);
IsUserInGroup = itemView.findViewById(R.id.IsUserInGroup);
}
}
}
Can anyone help me please?
I fixed it by moving the code in the on success listener itself