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());
}
});
Related
What I've done alone so far is to bring up a activity (recyclerView of the products) when I click ImageView 1.
When I click on the image of recyclerView, my goal is to load the image I clicked on ImageView 1 and save it in DB.
How can I get an image?
this is my product's adapter
#NonNull
#Override
public HolderProductCody onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.row_product_seller,parent,false);
return new HolderProductCody(view);
}
#Override
public void onBindViewHolder(#NonNull HolderProductCody holder, int position) {
//get data
final ModelProduct modelProduct = productList.get(position);
String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productColor = modelProduct.getProductColor();
String productTpo = modelProduct.getProductTpo();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String SeasonCategory = modelProduct.getProductSeasonCategory();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
//set data
holder.titleTv.setText(title);
holder.SeasonCategoryTv.setText(SeasonCategory);
holder.tpoTv.setText(productTpo);
holder.colorTv.setText(productColor);
holder.originalPriceTv.setText("$"+originalPrice);
if(detailAvailable.equals("true")){
//product is on discount
holder.tpoTv.setVisibility(View.VISIBLE);
holder.colorTv.setVisibility(View.VISIBLE);
}
else{
//product is not on discount
holder.tpoTv.setVisibility(View.GONE);
holder.colorTv.setVisibility(View.GONE);
}
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(holder.productIconIv);
}
catch(Exception e){
holder.productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
Toast.makeText(context, "클릭됨", Toast.LENGTH_SHORT).show();
//addcodylayout(modelProduct);
}
});
}
private void addcodylayout(ModelProduct modelProduct) {
Dialog dialog = new Dialog(context);
View view = LayoutInflater.from(context).inflate(R.layout.activity_cody_product,null);
dialog.setContentView(view);
dialog.show();
//get data
final String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productTpo = modelProduct.getProductTpo();
String productColor = modelProduct.getProductColor();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
final String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(productIconIv);
}
catch(Exception e){
productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
dialog.show();
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public Filter getFilter() {
if(filter==null){
filter = new FilterProduct(this,filterList);
}
return filter;
}
class HolderProductCody extends RecyclerView.ViewHolder{
/*holds views of recyclerview*/
private ImageView productIconIv;
private TextView tpoTv, titleTv, SeasonCategoryTv,colorTv,originalPriceTv;
public HolderProductCody(#NonNull View itemView) {
super(itemView);
productIconIv = itemView.findViewById(R.id.productIconIv);
tpoTv = itemView.findViewById(R.id.tpoTv);
titleTv = itemView.findViewById(R.id.titleTv);
SeasonCategoryTv = itemView.findViewById(R.id.categorySeasonTv);
colorTv = itemView.findViewById(R.id.colorTv);
originalPriceTv = itemView.findViewById(R.id.originalPriceTv);
}
}
}
this is my product's activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cody_product);
filterProductBtn = findViewById(R.id.filterProductBtn);
productsRv = findViewById(R.id.productsRv);
filteredProductsTv = findViewById(R.id.filteredProductsTv);
getSupportActionBar().hide();
firebaseAuth = FirebaseAuth.getInstance();
filterProductBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(CodyProductActivity.this);
builder.setTitle("카테고리 선택").setItems(Constants.productCategories1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//get selected item
String selected = Constants.productCategories1[which];
filteredProductsTv.setText(selected);
if (selected.equals("모든 옷")) {
//load all
loadAllProducts();
} else {
//load filtered
loadFilteredProducts(selected);
}
}
}).show();
}
});
}
private void loadFilteredProducts(String selected) {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for(DataSnapshot ds: dataSnapshot.getChildren()){
String productCategory = ""+ds.child("productCategory").getValue();
//if selected category matches product category then add in list
if(selected.equals(productCategory)){
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this,productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this,3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseerror) {
}
});
}
private void loadAllProducts() {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this, productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this, 3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The ID value of ImageView1 is topImages.
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();
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();
}
});
I am trying to develop an android which is read and display data from Firebase database, unfortunately, I could not able to display any data from the database.There are no error messages or any error issues are noted in Android monitor(I am using Android Studio).The only issue I noticed which is in FriendlyMessage file setText,setName,setPhotoUrl this three methods are never used.
There are three parts of the project, 1)mainactivity,2)MessageAdapter,3)Friendlymessage
1)MaiinActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mFirebaseDatabaseReference;
private ChildEventListener monchildlistner;
private String mUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
mFirebaseDatabase=FirebaseDatabase.getInstance();
mFirebaseDatabaseReference=mFirebaseDatabase.getReference().child("message");
// Initialize references to views
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageListView = (ListView) findViewById(R.id.messageListView);
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mSendButton = (Button) findViewById(R.id.sendButton);
// Initialize message ListView and its adapter
List<FriendlyMessage> friendlyMessage = new ArrayList<>();
mMessageAdapter = new MessageAdapter(this, R.layout.item_message,friendlyMessage);
mMessageListView.setAdapter(mMessageAdapter);
// Initialize progress bar
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO: Fire an intent to show an image picker
}
});
// Enable Send button when there's text to send
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
// Send button sends a message and clears the EditText
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO: Send messages on click
FriendlyMessage friendlyMessage=new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
mFirebaseDatabaseReference.push().setValue(friendlyMessage);
// Clear input box
mMessageEditText.setText("");
}
});
monchildlistner=new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
FriendlyMessage friendlymessage=dataSnapshot.getValue(FriendlyMessage.class);
mMessageAdapter.add(friendlymessage);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
//when a message added on the database at that time addchildeventlistener will fire up and refer us to onchildadded method
mFirebaseDatabaseReference.addChildEventListener(monchildlistner);
}
}
2)MessageAdapter:
public class MessageAdapter extends ArrayAdapter<FriendlyMessage>{
public MessageAdapter(Context context, int resource, List<FriendlyMessage> objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_message, parent, false);
}
ImageView photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
TextView messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
TextView authorTextView = (TextView) convertView.findViewById(R.id.nameTextView);
FriendlyMessage message = getItem(position);
boolean isPhoto = message.getPhotoUrl() != null;
if (isPhoto) {
messageTextView.setVisibility(View.GONE);
photoImageView.setVisibility(View.VISIBLE);
Glide.with(photoImageView.getContext())
.load(message.getPhotoUrl())
.into(photoImageView);
} else {
messageTextView.setVisibility(View.VISIBLE);
photoImageView.setVisibility(View.GONE);
messageTextView.setText(message.getText());
}
authorTextView.setText(message.getName());
return convertView;
}
}
3)FriendlyMessage:
public class FriendlyMessage {
private String text;
private String name;
private String photoUrl;
public FriendlyMessage() {
}
public FriendlyMessage(String text, String name, String photoUrl) {
this.text = text;
this.name = name;
this.photoUrl = photoUrl;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
After you add your message, you are not notifying the adapter to refresh or load the content that is newly added.
adapter.notifyDataSetChanged()
would work
I find out the issue and the problem was solved, I am going to mark this topic as a solved issue.The problem was in my layout file.Unfortunately, I was assigned the list view value '0', after changed the value '0' to match parent it's working fine.Thanks everyone for your support.