I have manage to get my document id in my AdminOfferFragment and I want to pass the value into the to EditOffer to update my data. I have tried using intent put extra to get my id in another activity but it still display null. So how can I pass my id after onClick in AdminOfferFragment to my EditOffer?
AdminOfferFragment
String id;
RecyclerView myRecycleView;
private FirestoreAdapter2 adapter;
FirebaseFirestore fStore;
private String email = "";
Button Btn;
Button Btn2;
FirebaseAuth fAuth;
String userId ="";
private Integer position = 0;
ArrayList<String> arraylist = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_admin_offer, container, false);
myRecycleView = v.findViewById(R.id.recyclerView);
Btn = v.findViewById(R.id.editBtn);
Btn2 = v.findViewById(R.id.deleteBtn);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
Btn2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startActivity(new Intent(getActivity(),LoginUI.class));
}
});
Query query = fStore.collection("offer");
PagedList.Config config = new PagedList.Config.Builder().setInitialLoadSizeHint(10).setPageSize(3).build();
FirestorePagingOptions<OfferInfo> options = new FirestorePagingOptions.Builder<OfferInfo>().setLifecycleOwner(this)
.setQuery(query, config, new SnapshotParser<OfferInfo>() {
#NonNull
#Override
public OfferInfo parseSnapshot(#NonNull DocumentSnapshot snapshot) {
OfferInfo offerInfo = snapshot.toObject(OfferInfo.class);
String itemId = snapshot.getId();
offerInfo.setItem_id(itemId);
return offerInfo;
}
}).build();
adapter = new FirestoreAdapter2(options, this);
myRecycleView.setHasFixedSize(true);
myRecycleView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
myRecycleView.setAdapter(adapter);
return v;
}
#Override
public void onItemClick(DocumentSnapshot snapshot, int position) {
OfferInfo offerInfo = snapshot.toObject(OfferInfo.class);
Log.d("Item_CLICK", "Clicked the item : " + position + "and the ID:" + offerInfo.getName());
Log.d("Item_CLICK", "Clicked the item : " + position + "and the ID:" + snapshot.getId());
this.userId = snapshot.getId();
id = snapshot.getId();
String reward_name = offerInfo.getName();
String reward_description = offerInfo.getDescription();
String reward_point = Integer.toString(offerInfo.getPoint());
this.position = position;
Intent intent = new Intent(getActivity(), EditOffer.class);
intent.putExtra("ID", id);
intent.putExtra("REWARD_NAME", reward_name);
intent.putExtra("REWARD_DESCRIPTION", reward_description);
intent.putExtra("REWARD_POINT", reward_point);
startActivity(intent);
}
public String getOfferId(){
return id;
}
EditOffer
public class EditOffer extends AppCompatActivity {
EditText offer1, description1, point1;
Button editBtn;
FirebaseFirestore fStore;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_offer);
Intent intent = getIntent();
String reward_name = intent.getStringExtra("REWARD_NAME");
String reward_description = intent.getStringExtra("REWARD_DESCRIPTION");
String reward_point = intent.getStringExtra("REWARD_POINT");
offer1 = findViewById(R.id.Rewardinfo);
description1 = findViewById(R.id.description);
point1 = findViewById(R.id.point);
offer1.setText(reward_name);
description1.setText(reward_description);
point1.setText(reward_point);
id = intent.getStringExtra("ID");
editBtn = findViewById(R.id.Btn2);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Editable newname = offer1.getText();
Editable newdescription = description1.getText();
Editable newpoint = point1.getText();
updateDocument(newname, newdescription, newpoint, id);
}
});
}
private void updateDocument(Editable newname, Editable newdescription, Editable newpoint, String id) {
this.id = id;
DocumentReference documentReference = fStore.collection("offer").document(id);
documentReference.update("name", newname);
documentReference.update("description", newdescription);
documentReference.update("point", newpoint)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditOffer.this,"Document Updated",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditOffer.this,e.getMessage(),Toast.LENGTH_LONG).show();
Log.d("Androidview", e.getMessage());
}
});
}
}
FirestoreAdapter2
public class FirestoreAdapter2 extends FirestorePagingAdapter<OfferInfo, FirestoreAdapter2.OfferViewHolder> {
private OnItemClickListener onItemClickListener;
public FirestoreAdapter2(#NonNull FirestorePagingOptions<OfferInfo> options, OnItemClickListener onItemClickListener) {
super(options);
this.onItemClickListener = (OnItemClickListener) onItemClickListener;
}
#Override
protected void onBindViewHolder(#NonNull OfferViewHolder holder, int position, #NonNull OfferInfo model) {
holder.list_email.setText(model.getName());
holder.list_fname.setText(model.getDescription());
holder.list_point.setText(Integer.toString(model.getPoint()));
}
#NonNull
#Override
public OfferViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.offer_item, parent, false);
return new OfferViewHolder(view);
}
public class OfferViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView list_email;
private TextView list_fname;
private TextView list_point;
public OfferViewHolder(#NonNull View itemview) {
super(itemview);
list_email = itemView.findViewById(R.id.textView);
list_fname = itemView.findViewById(R.id.textView2);
list_point = itemView.findViewById(R.id.textView3);
itemview.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(getItem(getAdapterPosition()), getAdapterPosition());
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot snapshot, int position);
}
}
OfferInfo
public class OfferInfo {
private String item_id;
private String name;
private String description;
private int point;
private OfferInfo(){}
private OfferInfo(String name, String description, String item_id, int point){
this.name = name;
this.description = description;
this.point = point;
this.item_id = item_id;
}
public String getName(){
return name;
}
public void setEmail(String name){
this.name = name;
}
public String getDescription(){
return description;
}
public void setFName(String description){
this.description = description;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
}
In your new activity you don't initialize the firestoreref, so add this in the opened activity:
fStore = FirebaseFirestore.getInstance();
Related
I am writing this code in my RecyclerViewAdapter and I have a separate Java File from which I want to set an ItemOnClickListener and Context for my adapter class. However, they come out as null. This is the method from the Java File for the recyclerView.
public void update(){
userRef.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String imageUrl;
String name;
String extra;
String ready;
String ingredients;
String id;
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for( int i = 0; i < list.size(); i++){
DocumentSnapshot documentSnapshot = list.get(i);
if(documentSnapshot.exists()){
Map<String, Object> favFood = documentSnapshot.getData();
name = favFood.get(KEY_NAME).toString();
imageUrl = favFood.get(KEY_URL).toString();
extra = favFood.get(KEY_XTRAINFO).toString();
ready = favFood.get(KEY_READY).toString();
Log.d("TAGG", ready);
ingredients = favFood.get(KEY_INGREDIENTS).toString();
id = favFood.get(KEY_ID).toString();
allFavoritedFoods.add(new FoodItem(imageUrl, name, ready, extra, ingredients, id, FirebaseAuth.getInstance().getCurrentUser().getUid()));
}
}
foodAdapter = new FoodAdapter(allFavoritedFoods, FavItem.this);
recyclerView.setAdapter(foodAdapter);
foodAdapter.setOnItemClickListener(FavItem.this);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
This is for the relevant code from the Adapter Class:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
private ArrayList<FoodItem> foodItems;
private Context context;
static String id;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
#Override
public int getItemCount() {
return foodItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView name, readyTime, ingredients, extraInfo;
public ImageView picture;
Button favBtn;
FirebaseFirestore db = FirebaseFirestore.getInstance();
public static final String KEY_URL = "imageUrl", KEY_INGREDIENTS = "ingredients", KEY_READY = "ready";
public static final String KEY_NAME = "name";
public static final String KEY_XTRAINFO = "info";
public static final String KEY_ID = "id";
public static final String KEY_FAV = "favorited";
//public Button favBtn;
public ViewHolder(View itemView){
super(itemView);
name = itemView.findViewById(R.id.title);
picture = itemView.findViewById(R.id.thumbnail);
readyTime = itemView.findViewById(R.id.readyInMinutes);
ingredients = itemView.findViewById(R.id.ingredients);
extraInfo = itemView.findViewById(R.id.extraInfo);
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);
}
}
}
});
favBtn = itemView.findViewById(R.id.favBtn);
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
FoodItem foodItem = foodItems.get(position);
Map<String, Object> favFood = new HashMap<>();
favFood.put(KEY_NAME, foodItem.getTitle());
favFood.put(KEY_URL, foodItem.getImageUrl());
favFood.put(KEY_ID, foodItem.getId());
favFood.put(KEY_INGREDIENTS, foodItem.getIngredients());
favFood.put(KEY_READY, foodItem.getReadyTime());
favFood.put(KEY_XTRAINFO, foodItem.getExtraInfo());
db.collection(FirebaseAuth.getInstance().getCurrentUser().getEmail()).document(id+"").set(favFood)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(itemView.getContext(), "Added to Favorites", Toast.LENGTH_SHORT);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(itemView.getContext(), "Deleted From Favorites", Toast.LENGTH_SHORT);
Log.d("Error in Storing", e.toString());
}
});
}
});
}
}
public FoodAdapter(ArrayList<FoodItem> foodItems, Context context){
this.foodItems = foodItems;
this.context = context;
}
For the MainActivity.java, this worked, but foodAdapter.setOnItemClickListener(MainActivity.this);. But it isn't working similarly to the other Java File.
For the context what would I put and what would I put for the onItemClickListener for the method from the other Java File?
If you are writing update() method inside a fragment, pass context as follows.
foodAdapter = new FoodAdapter(allFavoritedFoods, getActivity());
If you are writing update() method inside an activity, pass context as follows.(assume activity name is MainActivity)
foodAdapter = new FoodAdapter(allFavoritedFoods, MainActivity.this);
I'm doing a search in my firebase database (real time database), but I'm having these errors in return, could someone help me fix it?
this search is being done through an application I have the following error
PID: 15597
com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.ArrayList to String
MAINACTIVITY
public class SalasActivity extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_salas);
mUserDatabase = FirebaseDatabase.getInstance().getReference("grupos");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(SalasActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("nome").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getName(), model.getStatus(), model.getImage());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userName, String userStatus, String userImage){
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_status = (TextView) mView.findViewById(R.id.status_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
user_name.setText(userName);
user_status.setText(userStatus);
Glide.with(ctx).load(userImage).into(user_image);
USERS.JAVA
public class Users {
public String nome, membros, id;
public Users(){
}
public String getName() {
return nome;
}
public void setName(String name) {
this.nome = name;
}
public String getImage() {
return membros;
}
public void setImage(String image) {
this.membros = image;
}
public String getStatus() {
return id;
}
public void setStatus(String status) {
this.id = status;
}
public Users(String name, String image, String status) {
this.nome = name;
this.membros = image;
this.id = status;
}
}
DATABASE
DATABASE IMAGE
I want to get key position in database.
getting error: getRef(position) : Cannot resolve method 'getRef(int)' on
final String post_key = getRef(position).getKey();
this is my code CustomPostAdapter
public class CustomPostAdapter extends RecyclerView.Adapter<CustomPostAdapter.ViewHolder>{
public List<Spacecraft> userList ;
public Context context ;
private boolean mProcessLike = false ;
private DatabaseReference mDatabaseLike ;
// public ImageView imagePostt ;
public CustomPostAdapter(Context context , List<Spacecraft> userList){
this.userList = userList ;
this.context = context;
}
#NonNull
#Override
public CustomPostAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_posts_item, parent,false);
return new CustomPostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseLike.keepSynced(true);
final String post_key = getRef(position).getKey();
final String name = userList.get(position).getName();
final String image_post = userList.get(position).getImage_post();
final String descrip = userList.get(position).getDescrip();
final String hachatg = userList.get(position).getHachtag();
final String user = userList.get(position).getUser();
final String time = userList.get(position).getTime();
//Text Post
holder.nameText.setText(name);
holder.descripText.setText(descrip);
holder.hachtagText.setText(" " + hachatg);
holder.timeText.setText(" " + time);
//Imgae Post if null set Visibtly Gone to ImageView
if (TextUtils.isEmpty(image_post)){
holder.imagePostt.setVisibility(View.GONE);
}else {
//Image Post
Picasso.with(context).load(image_post).into(holder.imagePostt , new Callback() {
#Override
public void onSuccess() {
holder.imagePostt.setVisibility(View.VISIBLE);
}
#Override
public void onError() {
holder.imagePostt.setVisibility(View.GONE);
}
});
}
//Onclick items
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , ContentActivity.class);
intent.putExtra("NAME_KEY", name);
intent.putExtra("HACHTAG_KEY", hachatg);
intent.putExtra("DESCRIP_KEY", descrip);
intent.putExtra("USER_KEY", user);
intent.putExtra("IMAGE_POST", image_post);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
//Button Like Onclice
holder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
if (mProcessLike){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Chek if user already Like or not
if (dataSnapshot.child(post_key).hasChild(user)){
}else {
mDatabaseLike.child(post_key).child(user).setValue("RandomValue");
mProcessLike = false;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public TextView nameText , hachtagText , descripText, urlText , timeText;
public ImageView imagePostt ;
public ImageButton mLikeBtn ;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
nameText = (TextView)mView.findViewById(R.id.text_nameProblem);
hachtagText = (TextView)mView.findViewById(R.id.text_nameUser);
// urlText = (TextView)mView.findViewById(R.id.textUrl);
descripText = (TextView)mView.findViewById(R.id.text_Discription);
timeText = (TextView)mView.findViewById(R.id.timeText);
imagePostt = (ImageView)mView.findViewById(R.id.imagePost);
mLikeBtn = (ImageButton)mView.findViewById(R.id.btnLike);
}
}
}
You should be using FirebaseRecyclerAdapter which has the method getRef(). follow this link to learn how to use it
There are two ways in which you can solve this. The first one would be to store the key as a property in your user object and use:
final String key = userList.get(position).getKey();
And the second one would be to simply use FirebaseRecyclerAdapter instead and call:
mFirebaseRecyclerAdapter.getKey(position);
As explained here by #Puf.
Hey guys iam trying to build a Social Media Application useing Firebase Realtime Database
but am Stuck in how to get the posts generated key to add the Comments inside it so how to get the push key generated to the post and how to show the comment inside the Clicked Post
Database Structure
Here is the Activity that Shows the Post Details When i click on the post in Recyclerview it Intents me to this Activity
public class ShowThePost extends AppCompatActivity {
Dialog dialog;
FirebaseUser mAuth;
DatabaseReference dbRef;
Intent intent;
#BindView(R.id.imgPostShow) PhotoView PostImage;
#BindView(R.id.Show_profile_image) CircularImageView UserProfilePicture;
#BindView(R.id.postTitleShow) TextView PostTitle;
#BindView(R.id.txt_Show_UserName) TextView UserProfileName;
#BindView(R.id.txt_Post_Date) TextView PostDateTime;
#BindView(R.id.Show_price) TextView RealPrice;
#BindView(R.id.txtShowDescription) TextView PostDescription;
#BindView(R.id.fabComment) com.getbase.floatingactionbutton.FloatingActionButton floatingActionsMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_the_post);
ButterKnife.bind(this);
dialog = new Dialog(this);
intent = getIntent();
getDataFromIntent();
}
public void getDataFromIntent(){
String id = intent.getStringExtra("post_ID");
String title = intent.getStringExtra("post_Title");
String description = intent.getStringExtra("post_Desc");
String image = intent.getStringExtra("post_Image");
String dateTime = intent.getStringExtra("post_DateTime");
String price = intent.getStringExtra("post_Price");
String currency = intent.getStringExtra("post_Currency");
String UserName = intent.getStringExtra("post_UserName");
String UserProfilePic = intent.getStringExtra("post_UserProfilePicture");
GlideApp.with(this)
.load(image)
.into(PostImage);
GlideApp.with(this)
.load(UserProfilePic)
.into(UserProfilePicture);
PostTitle.setText(title);
UserProfileName.setText(UserName);
PostDescription.setText(description);
RealPrice.setText(price + " : " + currency);
PostDateTime.setText(dateTime);
}
public void ShowCommentDialog() {
// final AlertDialog.Builder alert = new AlertDialog.Builder(this);
// View view = getLayoutInflater().inflate(R.layout.create_comment,null);
// alert.setCancelable(false);
dialog.setContentView(R.layout.create_comment);
final EditText txtSuggestprice = (EditText) dialog.findViewById(R.id.priceSuggested);
final EditText txtNotes = (EditText)dialog.findViewById(R.id.txtnotes);
final Button btnDone = (Button)dialog.findViewById(R.id.btnCommentDone);
final Button btnClose = (Button) dialog.findViewById(R.id.btnClose);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String category = intent.getStringExtra("category");
// String Notes = txtNotes.getText().toString();
// String SuggestedPrice =
//
txtSuggestprice.getText().toString();
// String UserID = mAuth.getUid().toString();
// String UserProfilePic = mAuth.getPhotoUrl().toString();
// String UserName = mAuth.getDisplayName().toString();
//
// CommentsList commentsList = new CommentsList();
// commentsList.setUserID(UserID);
// commentsList.setUserProfilePicture(UserProfilePic);
// commentsList.setCommentDescription(Notes);
// commentsList.setCommentSuggestPrice(SuggestedPrice);
// commentsList.setCommentDate("date");
//
dbRef = FirebaseDatabase.getInstance().getReference("Posts");
Toast.makeText(ShowThePost.this, dbRef.child(category).push().getKey().toString(), Toast.LENGTH_SHORT).show();
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toasty.info(ShowThePost.this, "Canceled", Toast.LENGTH_SHORT).show();
}
});
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
#OnClick(R.id.fabComment)
public void OpenDialog(){
ShowCommentDialog();
}
}
and this is the Adapter used to send the data to the Recyclerview and Get the putExtra
public class BooksAdapter extends RecyclerView.Adapter<BooksAdapter.BooksItemsHolder> {
public BooksAdapter(List<BooksLists> listy, Context mContext) {
this.listy = listy;
this.mContext = mContext;
}
public List<BooksLists> listy ;
Context mContext;
#NonNull
#Override
public BooksItemsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
BooksItemsHolder holder = new BooksItemsHolder(v);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final BooksItemsHolder holder, int position) {
final BooksLists list = listy.get(position);
holder.PostTitle.setText(list.getPost_title());
holder.PostDate.setText(list.getPost_datetime());
GlideApp.with(mContext)
.load(list.getPost_image())
.into(holder.imgPostCover);
holder.UserProfileName.setText(list.getUser_name());
GlideApp.with(mContext)
.load(list.getUser_pp())
.placeholder(R.drawable.user)
.into(holder.TheUserProfilePic);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext,ShowThePost.class);
intent.putExtra("post_ID",list.getPost_id());
intent.putExtra("post_Title",list.getPost_title());
intent.putExtra("post_Desc",list.getPost_description());
intent.putExtra("post_Image",list.getPost_image());
intent.putExtra("post_DateTime",list.getPost_datetime());
intent.putExtra("post_Price",list.getPost_real_price());
intent.putExtra("post_Currency",list.getCurrency());
intent.putExtra("post_UserName",list.getUser_name());
intent.putExtra("post_UserProfilePicture",list.getUser_pp());
intent.putExtra("category",list.getCategory());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listy.size();
}
public class BooksItemsHolder extends RecyclerView.ViewHolder {
#BindView(R.id.TheuserProfilePicture)
CircularImageView TheUserProfilePic;
#BindView(R.id.userName) TextView UserProfileName;
#BindView(R.id.imgPostShow) ImageView imgPostCover;
#BindView(R.id.postTitle) TextView PostTitle;
#BindView(R.id.txt_Post_Date) TextView PostDate;
#BindView(R.id.GotoPostItem)
CardView linearLayout;
public BooksItemsHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
}
List of the Comments.class
public class CommentsList {
public CommentsList() {
}
String userID;
String userName;
String userProfilePicture;
String commentDate;
String commentSuggestPrice;
String CommentDescription;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserProfilePicture() {
return userProfilePicture;
}
public void setUserProfilePicture(String userProfilePicture) {
this.userProfilePicture = userProfilePicture;
}
public String getCommentDate() {
return commentDate;
}
public void setCommentDate(String commentDate) {
this.commentDate = commentDate;
}
public String getCommentSuggestPrice() {
return commentSuggestPrice;
}
public void setCommentSuggestPrice(String commentSuggestPrice) {
this.commentSuggestPrice = commentSuggestPrice;
}
public String getCommentDescription() {
return CommentDescription;
}
public void setCommentDescription(String commentDescription) {
CommentDescription = commentDescription;
}
public CommentsList(String userID, String userName, String userProfilePicture, String commentDate, String commentSuggestPrice, String commentDescription) {
this.userID = userID;
this.userName = userName;
this.userProfilePicture = userProfilePicture;
this.commentDate = commentDate;
this.commentSuggestPrice = commentSuggestPrice;
CommentDescription = commentDescription;
}
}
You can try this
mDatabase.child("Posts").child("Books").addValueEventListener(new ValueEventListener() {
final ArrayList<String> keysArray= new ArrayList<String>(); // if you want to store all the keys
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()){
String key = data.getKey(); //Here you can get all your keys from Books
keysArray.add(key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(view.getContext(),"database error",
Toast.LENGTH_SHORT).show();
}
});
Main activity.java
public class activity_3 extends AppCompatActivity {
TextView question,option_1,option_2,option_3,description,winnner;
NumberProgressBar option_progress1, option_progress2,option_progress3;
int val_1;
int val_2;
int val_3;
DatabaseReference Polldata_3;
String optionOne;
String optionTwo;
String optionThree;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
final String que = getIntent().getExtras().getString("que");
final String des = getIntent().getExtras().getString("des");
optionOne = getIntent().getExtras().getString("option1");
optionTwo = getIntent().getExtras().getString("option2");
optionThree = getIntent().getExtras().getString("option3");
final String id_user = getIntent().getExtras().getString("id");
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_2 = getIntent().getExtras().getInt("val3");
option_progress1 = (NumberProgressBar) findViewById(R.id.option1_progressbar);
option_progress2 = (NumberProgressBar) findViewById(R.id.option2_progressbar);
option_progress3 = (NumberProgressBar) findViewById(R.id.option3_progressbar);
Polldata_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
final DatabaseReference answsersave = Polldata_3.child(id_user);
question = (TextView) findViewById(R.id.question_showpoll);
option_1 = (TextView) findViewById(R.id.option_1);
option_2 = (TextView) findViewById(R.id.option_2);
option_3 = (TextView) findViewById(R.id.option_3);
description = (TextView) findViewById(R.id.description_user_3);
winnner = (TextView) findViewById(R.id.winner);
option_1.setText(optionOne);
option_2.setText(optionTwo);
option_3.setText(optionThree);
question.setText(que);
description.setText(des);
option_progress1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress1.setProgress(val_1+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_1++;
answsersave.child("option_1_value").setValue(val_1);
//winnerdeclare();
}
});
option_progress2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress2.setProgress(val_2+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_2++;
answsersave.child("option_2_value").setValue(val_2);
// winnerdeclare();
}
});
option_progress3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress3.setProgress(val_3+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_3++;
// winnerdeclare();
answsersave.child("option_3_value").setValue(val_3);
}
});
}
}
ADAPTER CLASS
public class listview_3 extends AppCompatActivity {
ListView listviewpoll3;
private DatabaseReference Poll_data_3;
List<addpoll_3> addpoll_3List;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview_3);
listviewpoll3 = (ListView) findViewById(R.id.poll_listview_3);
Poll_data_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
addpoll_3List = new ArrayList<>();
listviewpoll3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Intent intent = new Intent(listview_3.this, activity_3.class);
addpoll_3 poll = addpoll_3List.get(position);
final String optionone = poll.getOption_1();
final String optiontwo = poll.getOption_2();
final String optionthree = poll.getOption_3();
final String id_user = poll.getId();
final int value_1 = poll.getOption_1_value();
final int value_2 = poll.getOption_2_value();
final int value_3 = poll.getOption_3_value();
final String question = poll.getQuestion();
final String desp = poll.getDescription();
intent.putExtra("option1",optionone);
intent.putExtra("option2",optiontwo);
intent.putExtra("option3",optionthree);
intent.putExtra("id",id_user);
intent.putExtra("val1",value_1);
intent.putExtra("val2",value_2);
intent.putExtra("val3",value_3);
intent.putExtra("que",question);
intent.putExtra("descp",desp);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
Poll_data_3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
addpoll_3List.clear();
for(DataSnapshot pollSnapshot: dataSnapshot.getChildren())
{
addpoll_3 poll = pollSnapshot.getValue(addpoll_3.class);
addpoll_3List.add(poll);
}
poll_list_3 adapter = new poll_list_3(listview_3.this,addpoll_3List);
listviewpoll3.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
list class
public class poll_list_3 extends ArrayAdapter<addpoll_3> {
private Activity context;
private List<addpoll_3> addpoll_3List;
public poll_list_3(Activity context, List<addpoll_3> addpoll_3List) {
super(context, R.layout.list_layout, addpoll_3List);
this.context = context;
this.addpoll_3List = addpoll_3List;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View viewitem = inflater.inflate(R.layout.list_layout,null);
TextView textViewName = (TextView) viewitem.findViewById(R.id.tv);
TextView textViewDesp = (TextView) viewitem.findViewById(R.id.tv1);
final addpoll_3 poll1 = addpoll_3List.get(position);
textViewName.setText(poll1.getQuestion());
textViewDesp.setText(poll1.getDescription());
return viewitem;
}
}
I am making a polling app where user can create a poll which is then stored in the firebase database and retrieved into listview of the app
when the user clicks on the list view he is directed to the the activity where there are number of progressbars
i have added a ON-click listener o the progress bar, So when user clicks on the progressbar the val of that option gets incremented in the database. so when a different user vote on the same poll the value from the database is fetched and value of the current user is added displaying the winner,but problem is the value of the progressbar1 gets the value from the database but the other two keep progress bar values start from 0 every time user clicks on the other two progress bar (ie 2 and 3).
please help
addpoll_3.java
public class addpoll_3 {
String id;
String question;
String description;
String option_1;
String option_2;
String option_3;
int option_1_value;
int option_2_value;
int option_3_value;
public addpoll_3(){}
public addpoll_3(String id, String question, String description, String option_1, String option_2, String option_3, int option_1_value, int option_2_value, int option_3_value) {
this.id = id;
this.question = question;
this.description = description;
this.option_1 = option_1;
this.option_2 = option_2;
this.option_3 = option_3;
this.option_1_value = option_1_value;
this.option_2_value = option_2_value;
this.option_3_value = option_3_value;
}
public String getId() {
return id;
}
public String getQuestion() {
return question;
}
public String getDescription() {
return description;
}
public String getOption_1() {
return option_1;
}
public String getOption_2() {
return option_2;
}
public String getOption_3() {
return option_3;
}
public int getOption_1_value() {
return option_1_value;
}
public int getOption_2_value() {
return option_2_value;
}
public int getOption_3_value() {
return option_3_value;
}
}
code:
Activity_3.java
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_3 = getIntent().getExtras().getInt("val3");
These were changes to be made
//Read from the database
myRef.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});