Why counter just increase to 1 in firebase? - java

im trying to increase a visitor counter views when access to read a message, so i made a method called incrementar () and set it where i retrieve info when someone click to open that post. But i dont know why only increase to 1 view in firebase, if i click again it does not increase. should use shared preferences? or there is an other method to increase a counter from firebase?
int views;
int score;
int increment = +1;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
setTitle("Chatroom");
threadNameTV = findViewById(R.id.threadNameTV);
newMessageET = findViewById(R.id.newMessageET);
homeButton = findViewById(R.id.homeButton);
sendButton = findViewById(R.id.sendButton);
messagesLV = findViewById(R.id.messagesLV);
final View messageview = getLayoutInflater().inflate(R.layout.messages_listview, null);
messageTV = messageview.findViewById(R.id.messageTV);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
user = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
firebaseUser = mAuth.getCurrentUser();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");
threadNameTV.setTextColor(Color.parseColor("#000000"));
if (getIntent() != null && getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("messageThreadDetails")) {
messageThread = (MessageThread) getIntent().getSerializableExtra("messageThreadDetails");
threadNameTV.setText(messageThread.title);
getMessages(messageThread.thread_id);
incrementar();
}
} else {
Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
}
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (user != null) {
user = null;
mDatabase = null;
mAuth = null;
Intent intent = new Intent(ChatActivity.this, ThreadsActivity.class);
startActivity(intent);
finish();
} else {
user = null;
mDatabase = null;
mAuth = null;
Toast.makeText(ChatActivity.this, "You need to login", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ChatActivity.this, IniciarSesion.class);
startActivity(intent);
finish();
}
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = newMessageET.getText().toString();
String user_name = user.getDisplayName();
String profileimage = user.getPhotoUrl().toString();
if (message.isEmpty()) {
Toast.makeText(ChatActivity.this, "Enter Message", Toast.LENGTH_SHORT).show();
} else {
addMessage(message, user_name, profileimage, messageThread.thread_id);
}
}
});
}
public void addMessage(String message, String user_name, String profileimage, String thread_id) {
if (user != null) {
mDatabase.child("Normas").child(thread_id).child("messages").push().setValue(new Message(message, user.getUid(), user_name, profileimage, new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.US).format(new Date())));
newMessageET.setText("");
} else {
Toast.makeText(this, "No user logged in", Toast.LENGTH_SHORT).show();
}
}
public void getMessages(String thread_id) {
mDatabase.child("Normas").child(thread_id).child("messages").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
messagesList.clear();
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Message message = messageSnapshot.getValue(Message.class);
if (message != null) {
message.message_id = messageSnapshot.getKey();
Log.d(TAG, "onDataChange: " + message.toString());
}
messagesList.add(message);
}
messagesAdapter = new MessagesAdapter(ChatActivity.this, R.layout.threads_listview, messagesList, ChatActivity.this);
messagesLV.setAdapter(messagesAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ChatActivity.this, "ChatActivity: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void deleteMessage(String message_id) {
mDatabase.child("Normas").child(messageThread.thread_id).child("messages").child(message_id).removeValue();
}
public void setimage() {
UsersRef.child(currentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(ChatActivity.this).load(image).placeholder(R.drawable.profilefoto).into(fotoforos);
}
}
}
#Override
public void onCancelled(#NotNull DatabaseError error) {
}
});
}
public void incrementar() {
FirebaseDatabase.getInstance().getReference().child("Normas").child(messageThread.thread_id).child("views").setValue(increment);
}
}
Thanks so much

You're setting +1 as the value each time you call:
int increment = +1;
FirebaseDatabase.getInstance().getReference().child("Normas")
.child(messageThread.thread_id).child("views").setValue(increment);
What would work is:
FirebaseDatabase.getInstance().getReference().child("Normas")
.child(messageThread.thread_id).child("views").setValue(ServerValue.increment(1));
Instead of sending the literal value 1, this second snippet sends an instruction to increment the current value by 1.

Related

How to add ChipGroup Selected Text to firebase?

I am new to android and working on an app where I need to take data from users from the chip Groups, and I want to save that data to firestore but I m facing a problem, I created a method addDataToFirebase but I have no idea how to get the chip text from chip groups and pass them to my method. Please help me
this is my XML design image
Below is the code
public class UserDetailsToFirebase extends AppCompatActivity {
FirebaseFirestore db;
Chip chip, chip1, chip2;
ActivityUserDetailsToFirebaseBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityUserDetailsToFirebaseBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
db = FirebaseFirestore.getInstance();
//Toolbar Process
setSupportActionBar(binding.rentsellToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("");
binding.nextButton.setEnabled(false);
//Chip Group Type
binding.chipGroupType.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(ChipGroup group, int checkedId) {
chip = group.findViewById(checkedId);
String chipType = (String) chip.getText();
if (chip != null) {
Toast.makeText(UserDetailsToFirebase.this, "Selected " + chipType, Toast.LENGTH_SHORT).show();
if (chip1 != null && chip2 != null)
{
binding.nextButton.setEnabled(true);
}
}
}
});
//Chip Group Preferred Tenanst
binding.chipGroupTenants.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(ChipGroup group, int checkedId) {
chip1 = group.findViewById(checkedId);
String chipTenants = (String) chip1.getText();
if (chip1 != null) {
Toast.makeText(UserDetailsToFirebase.this, "Selected " + chipTenants, Toast.LENGTH_SHORT).show();
if (chip != null && chip2 != null)
{
binding.nextButton.setEnabled(true);
}
}
}
});
//Chip Group Parking
binding.chipGroupParking.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(ChipGroup group, int checkedId) {
chip2 = group.findViewById(checkedId);
String chipParking = (String) chip2.getText();
if (chip2 != null) {
Toast.makeText(UserDetailsToFirebase.this, "Selected " + chipParking, Toast.LENGTH_SHORT).show();
if (chip != null && chip1 != null )
{
binding.nextButton.setEnabled(true);
}
}
}
});
binding.nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Here i m getting the error
// i m not able to access the arguments in this method
addDatatoFirebase(chipType, chipTenants, chipParking);
}
});
}
private void addDatatoFirebase(String type_room)
{
CollectionReference dbUserList = db.collection("ListingDetails");
RoomlistingDetails userDetails = new RoomlistingDetails(type_room);
dbUserList.add(userDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Intent intent = new Intent(UserDetailsToFirebase.this, WelcomeActivity.class);
startActivity(intent);
Toast.makeText(UserDetailsToFirebase.this, "User Listing Data has been added to Firebase Firestore", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserDetailsToFirebase.this, "Fail to add course \n" + e, Toast.LENGTH_SHORT).show();
}
});
}}

Sub total of recycler view nodes keeps increasing in android app

MY ORIGINAL QUESTION
I am making an android app with firebase Realtime database. I am getting sum of the firebase nodes in side recycler view. I have a text view out side the recycler view where I am getting the sub total of the values of the recycler view. MY PROBLEM is that I cannot get the actual sum and also the sum keeps increasing when I scroll up and down. Here is my Main activity JAVA code:
public class MainActivity extends AppCompatActivity {
FirebaseDatabase myfire;
DatabaseReference myRef;
private FirebaseRecyclerOptions<entry> options;
int totalEarned = 0;
int totalSpent = 0;
int totalSaved=0;
#Override
public void onBackPressed() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Are you sure to exit?");
dialog.setPositiveButton("Play", (dialog1, which) -> {
});
dialog.setNegativeButton("Exit", (dialog12, which) -> {
FirebaseAuth.getInstance().signOut();
MainActivity.this.finish();
});
dialog.show();
}
private String getUID() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
if (mUser != null) {
String strUID = mUser.getUid();
if (!TextUtils.isEmpty(strUID)) {
return strUID;
}
}
return "";
}
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//==============
final RecyclerView userlist = (RecyclerView) findViewById(R.id.idRecycleView);
myfire = FirebaseDatabase.getInstance();
userlist.setLayoutManager(new LinearLayoutManager(this));
//==================
final TextView tvTotalIncome = findViewById(R.id.idTotalIncome);
final TextView tvTotalExpanse = findViewById(R.id.idTotalExpanse);
final TextView tvTotalSaved = findViewById(R.id.idTotalSaved);
//==================
final FloatingActionButton btnBudget = findViewById(R.id.idCreateBudget);
myfire = FirebaseDatabase.getInstance();
final String strUID = getUID();
if (TextUtils.isEmpty(strUID)) {
//handle case of null UID
}
final Intent i = getIntent();
final String month = Objects.requireNonNull(i.getExtras()).getString("Month");
//-------------------------------
btnBudget.setOnClickListener(v -> {
Intent o;
o = new Intent(MainActivity.this, AddBudgetActivity.class);
o.putExtra("Month",month);
startActivity(o);
finish();
});
if (type.equals("Income")) {
try {
totalEarned = (totalEarned+sum);
} catch (NumberFormatException ex) {
}
tvTotalIncome.setText("-)"+String.valueOf( totalEarned));
holder.btnIcon.setBackgroundResource(R.drawable.circlegreen);
holder.tvEntry.setText("(+)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else if (type.equals("Expanse")) {
try {
totalSpent = (totalSpent+sum);
} catch (NumberFormatException ex) {
}
tvTotalExpanse.setText("-)"+String.valueOf( totalSpent));
holder.btnIcon.setBackgroundResource(R.drawable.circlered);
holder.tvEntry.setText("(-)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
//======================
myRef = myfire.getReference().child("Data").child(strUID).child(month);
//-------------------------
options = new FirebaseRecyclerOptions.Builder<entry>()
.setQuery(myRef, entry.class)
.build();
final FirebaseRecyclerAdapter<entry, holder_menu> adapter = new FirebaseRecyclerAdapter<entry, holder_menu>(options) {
#Override
protected void onBindViewHolder(#NonNull #NotNull holder_menu holder, final int i, #NonNull #NotNull entry model) {
final String title = getRef(i).getKey();
assert title != null;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Budget");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int budget = 0;
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(), "Data Not Available", Toast.LENGTH_LONG).show();
} else {
final String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
final String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
final String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
final String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
entry basic = new entry(stData1, stData2, stData3, stData4);
String first = stData2.substring(0, 1);
holder.btnIcon.setText(first);
holder.tvHead.setText(stData2);
String type;
type=(stData3);
holder.tvBudget.setText("#" + stData4);
int amount = 0;
//important line
try {
amount = (Integer.parseInt(stData4));
} catch (NumberFormatException ex) {
}
//======================
budget = amount;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Entry");
final int finalBudget = budget;
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
//important line
try {
total = (Integer.parseInt(value));
} catch (NumberFormatException ex) {
}
//======================
sum = sum + total;
//==============
//======================
if (section.equals("Saving")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.saving));
}else if (section.equals("Paying")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.paying));
}else if (section.equals("Using")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.using));
}else if (section.equals("Earning")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.earning));
}else if (section.equals("Taking")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.taking));
}else if (section.equals("Drawing")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.drawing));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
}
holder.tvEntry.setText("(+)" + String.valueOf(sum) );
holder.tvBalance.setText("(=)" + String.valueOf(finalBudget - sum) );
//important line
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o;
o = new Intent(MainActivity.this, ViewHistoryActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}
});
holder.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type.equals("Income")) {
Intent o;
o = new Intent(MainActivity.this, EntryIncomeActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}else if (type.equals("Expanse")) {
Intent o;
o = new Intent(MainActivity.this, EntryExpanseActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
}
});
if (type.equals("Income")) {
try {
totalEarned = (totalEarned+sum);
} catch (NumberFormatException ex) {
}
tvTotalIncome.setText("-)"+String.valueOf( totalEarned));
holder.btnIcon.setBackgroundResource(R.drawable.circlegreen);
holder.tvEntry.setText("(+)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else if (type.equals("Expanse")) {
try {
totalSpent = (totalSpent+sum);
} catch (NumberFormatException ex) {
}
tvTotalExpanse.setText("-)"+String.valueOf( totalSpent));
holder.btnIcon.setBackgroundResource(R.drawable.circlered);
holder.tvEntry.setText("(-)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
//======================
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
}
#NonNull
#Override
public holder_menu onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item1, parent, false);
return new holder_menu(v);
}
};
adapter.startListening();
userlist.setAdapter(adapter);
}
}
EDITED QUESTION As per #androidLearner 's suggestion
MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
FirebaseDatabase myfire;
DatabaseReference myRef;
int totalEarned = 0;
int totalSpent = 0;
int totalSaved=0;
madapter adapter;
String iconsData;
String headsData;
int budgetsData=0;
int enteriesData=0;
int balancesData=0;
#Override
public void onBackPressed() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Are you sure to exit?");
dialog.setPositiveButton("Play", (dialog1, which) -> {
});
dialog.setNegativeButton("Exit", (dialog12, which) -> {
FirebaseAuth.getInstance().signOut();
MainActivity.this.finish();
});
dialog.show();
}
private String getUID() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
if (mUser != null) {
String strUID = mUser.getUid();
if (!TextUtils.isEmpty(strUID)) {
return strUID;
}
}
return "";
}
#RequiresApi(api = Build.VERSION_CODES.N)
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//==============
final RecyclerView userlist = (RecyclerView) findViewById(R.id.idRecycleView);
myfire = FirebaseDatabase.getInstance();
userlist.setLayoutManager(new LinearLayoutManager(this));
//==================
final TextView tvTotalIncome = findViewById(R.id.idTotalIncome);
final TextView tvTotalExpanse = findViewById(R.id.idTotalExpanse);
final TextView tvTotalSaved = findViewById(R.id.idTotalSaved);
//==================
final FloatingActionButton btnBudget = findViewById(R.id.idCreateBudget);
myfire = FirebaseDatabase.getInstance();
final String strUID = getUID();
if (TextUtils.isEmpty(strUID)) {
//handle case of null UID
}
final Intent i = getIntent();
final String month = Objects.requireNonNull(i.getExtras()).getString("Month");
//-------------------------------
btnBudget.setOnClickListener(v -> {
Intent o;
o = new Intent(MainActivity.this, AddBudgetActivity.class);
o.putExtra("Month",month);
startActivity(o);
finish();
});
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&---new method
myRef = myfire.getReference().child("Data").child(strUID).child(month);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String title = dataSnapshot.getKey();
assert title != null;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Budget");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(), "Data Not Available", Toast.LENGTH_LONG).show();
} else {
final String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
final String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
final String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
final String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
entry basic = new entry(stData1, stData2, stData3, stData4);
iconsData = stData2.substring(0, 1);
headsData=stData2;
//---------------------------------------------------------------------------entry
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Entry");
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
try {
total=(Integer.parseInt(value));
} catch (NumberFormatException ex) {
}
//==============
sum=sum+total;
}
enteriesData=sum;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&------NewMethod
balancesData=budgetsData-enteriesData;
ArrayList<String> iconList = new ArrayList<>();
iconList.add(iconsData);
ArrayList<String> headList= new ArrayList<>();
headList.add(headsData);
ArrayList<Integer> budgetList = new ArrayList<>();
budgetList.add(budgetsData);
ArrayList<Integer> entryList = new ArrayList<>();
entryList.add(enteriesData);
ArrayList<Integer> balanceList = new ArrayList<>();
balanceList.add(balancesData);
adapter = new madapter ( this, iconList,headList,budgetList,entryList,balanceList);
userlist.setAdapter(adapter);
}
}
RECYCLER VIEW Adapter
public class madapter extends RecyclerView.Adapter<madapter.ViewHolder> {
private List<String> stricon;
private List<String> strhead;
private List<Integer> intbudget;
private List<Integer> intentry;
private List<Integer> intbalance;
//---
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public madapter(MainActivity mainActivity, ArrayList<String> iconList, ArrayList<String> headList, ArrayList<Integer> budgetList, ArrayList<Integer> entryList, ArrayList<Integer> balanceList) {
this.mInflater = LayoutInflater.from(mainActivity);
this.stricon = iconList;
this.strhead = headList;
this.intbudget = budgetList;
this.intentry = entryList;
this.intbalance= balanceList;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.item1, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String icons = stricon.get(position);
String heads = strhead.get(position);
int budgets = intbudget.get(position);
int entries = intentry.get(position);
int balances = intbalance.get(position);
holder.btnIcon.setText(icons);
holder.tvHead.setText(heads);
holder.tvBudget.setText(String.valueOf(budgets));
holder.tvEntry.setText(String.valueOf(entries));
holder.tvBalance.setText(String.valueOf(balances));
}
// total number of rows
#Override
public int getItemCount() {
return stricon.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public Button btnIcon;
public TextView tvHead;
public TextView tvBudget;
public TextView tvEntry;
public TextView tvBalance;
public Button btnView;
public Button btnAdd;
ViewHolder(View itemView) {
super(itemView);
btnIcon= (Button) itemView.findViewById(R.id.idIcon);
tvHead = (TextView) itemView.findViewById(R.id.idHead);
tvBudget = (TextView) itemView.findViewById(R.id.idBudget);
tvEntry = (TextView) itemView.findViewById(R.id.idEntry);
tvBalance = (TextView) itemView.findViewById(R.id.idBalance);
btnView= (Button) itemView.findViewById(R.id.idView);
btnAdd = (Button) itemView.findViewById(R.id.idAdd);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return stricon.get(id);
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
THE NEW PROBLEM AFTER EDITING
I am not able to get any data from firebase to my array list by the method datasnapshot. But yes my recycler view shows data if I add hardcore text or numbers to my list manually.
This is the crash report
2021-05-24 00:07:12.368 19933-19933/com.myappname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myappname, PID: 19933
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.get(ArrayList.java:437)
at com.myappname.model.rvAdapter.onBindViewHolder(mAdapter.java:54)
at com.myappname.model.rvAdapter.onBindViewHolder(mAdapter.java:16)2021-05-24 .......................................
set Adapter after got data from firebase
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
//==============
sum=sum+total;
}
enteriesData=sum;
//Send your data to adapter as per your need from here
adapter = new madapter ( this, iconList,headList,budgetList,entryList,balanceList);
userlist.setAdapter(adapter);
}

how can I get the products of the sellers

I have compared the others questions but they have different problems.
My question is, how can I display (on the user activity) all the products that the sellers have added on the firebase database?
The sellers have their own register and login activity before they add the products, meaning each seller will be having is own name or id.
You can check my database sample on the picture below.
**Sorry guys I have updated the code but now it is crashing the app every time I click the button to go to the add products activity**
public class SellerAddProductActivity extends AppCompatActivity {
private String saveCurrentDate;
private String saveCurrentTime;
private String CategoryName;
private String downloadImageUrl;
private String productRandomKey;
private String Description;
private String Price, Quantity, State;
private String Pname, Store;
private Button AddProductButton;
private EditText InputProductName;
private EditText InputProductPrice, InputStoreName;
private EditText InputProductDescription, InputProductQauntity, InputProductState;
private StorageReference ProductImageRef;
private Uri ImageUri;
private DatabaseReference ProductsRef, ProductsInfo;
private ProgressDialog loadingBar;
private static final int GalleryPick = 1;
private ImageView InputProductImage;
FirebaseUser currentUser;
FirebaseUser mAuth;
String userID = mAuth.getUid(); //--> Store each seller name with this ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_add_product);
ProductImageRef = FirebaseStorage.getInstance().getReference().child("Product Images");
CategoryName = getIntent().getExtras().get("category").toString();
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
ProductsInfo = FirebaseDatabase.getInstance().getReference().child("ProductsInfo");
mAuth = FirebaseAuth.getInstance().getCurrentUser();
AddProductButton = (Button) findViewById(R.id.add_product);
InputProductName = (EditText) findViewById(R.id.product_name);
InputProductImage = (ImageView) findViewById(R.id.product_image_select);
InputProductPrice = (EditText) findViewById(R.id.product_price);
InputProductQauntity = (EditText) findViewById(R.id.product_quantity);
InputProductState = (EditText) findViewById(R.id.product_state);
InputStoreName = (EditText) findViewById(R.id.store_name);
loadingBar = new ProgressDialog(this);
InputProductDescription = (EditText) findViewById(R.id.product_description);
InputProductImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
AddProductButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateProductData();
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
#Override
protected void onActivityResult
(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
ImageUri = data.getData();
InputProductImage.setImageURI(ImageUri);
}
}
private void validateProductData() {
Description = InputProductDescription.getText().toString();
Price = InputProductPrice.getText().toString();
Pname = InputProductName.getText().toString();
Quantity = InputProductQauntity.getText().toString();
State = InputProductState.getText().toString();
Store = InputStoreName.getText().toString();
if (ImageUri == null) {
Toast.makeText(this, "Please Add Product Image!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Description)) {
Toast.makeText(this, "Please Enter the Product Description!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Price)) {
Toast.makeText(this, "Please Enter the Product Price!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Pname)) {
Toast.makeText(this, "Please Enter the Product Name!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Quantity)) {
Toast.makeText(this, "Enter Quantity in Number!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(State)) {
Toast.makeText(this, "Specify the State of your Product!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Store)) {
Toast.makeText(this, "Store Name is Mandatory!", Toast.LENGTH_SHORT).show();
} else {
StoreProductInfo();
}
}
private void StoreProductInfo() {
loadingBar.setTitle("Adding Product");
loadingBar.setMessage("Please wait!");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calendar.getTime());
// Unique Random Key for the Products added by the admin
productRandomKey = saveCurrentDate + saveCurrentTime;
// Unique Random Key to store the image added by the admin
final StorageReference filePath = ProductImageRef.
child(ImageUri.getLastPathSegment() + productRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
//Displaying the Upload Error to the seller
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String message = e.toString();
Toast.makeText(SellerAddProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SellerAddProductActivity.this, "Image Uploaded!", Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadImageUrl = task.getResult().toString();
Toast.makeText(SellerAddProductActivity.this, "Product Image Added",
Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
}
});
}
});
}
private void SaveProductInfoToDatabase() {
HashMap<String, Object> productMap = new HashMap<>();
productMap.put("pid", productRandomKey);
productMap.put("storename", Store);
productMap.put("date", saveCurrentDate);
productMap.put("time", saveCurrentTime);
productMap.put("description", Description);
productMap.put("image", downloadImageUrl);
productMap.put("Category", CategoryName);
productMap.put("state", State);
productMap.put("quantity", Quantity);
productMap.put("price", Price);
productMap.put("pname", Pname);
ProductsRef.child("Products").child(userID).child(productRandomKey);
ProductsInfo.child(productRandomKey).updateChildren(productMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(SellerAddProductActivity.this, SellerAddProductActivity.class);
startActivity(intent);
loadingBar.dismiss();
Toast.makeText(SellerAddProductActivity.this, "Product
Added",Toast.LENGTH_SHORT).show();
} else {
loadingBar.dismiss();
String message = task.getException().toString();
Toast.makeText(SellerAddProductActivity.this,
"Error:"+message,Toast.LENGTH_SHORT).show();
}
}
});
} }
This how I'm displaying the products on the buyer/user activity
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private DatabaseReference productsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
productsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(productsRef, Products.class).build();
FirebaseRecyclerAdapter<Products, ProductsViewHolder> adapter
= new FirebaseRecyclerAdapter<Products, ProductsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductsViewHolder holder,int position,#NonNull final Products model){
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price " + model.getPrice() + "$");
Picasso.get().load(model.getImage()).into(holder.imageView);
//sending the product ID to the ProductDetailsActivity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
});
}
#NonNull
#Override
public ProductsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_products,parent,false);
ProductsViewHolder holder = new ProductsViewHolder(view);
return holder;
}
};
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
adapter.startListening();
recyclerView.setAdapter(adapter);
}
As I understand, you want to bring up all the sellers information to the one logged in in your app.
To do that you can do a for loop inside products to get each seller id, and then querie each user to get the products.
But you will need to change your database structure to make it easier.
I recommend to you to store inside the nested child Products the id of that product to querie in another table. For example
Products
|
--- userID
|
--- Products
|
--- product_key1: true
|
--- product_key2: true
And then in another node have the information of that product
ProductsInfo
|
--- product_key1
| |
| --- productName: "Orange"
| |
| --- productPrice: 1
|
--- product_key2
|
--- productName: "Pineapple"
|
--- productPrice: 3
So now, we will just get each userID and get each user products
First, instead of hardcoded seller names you should use getUid() to get each seller unique UID.
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance().getCurrentUser();
String userID = mAuth.getUid(); //--> Store each seller name with this ID
Now we just loop inside Products to get each user ID
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
Log.d("SellersID", userKey);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now that you have all the sellers key you can loop inside products and get each product key for each seller, and with that you can now get the data from ProductsInfo node
Your problem is at your database reference productsRef
You should add more to your reference, based on what you want to get from your database:
productsRef = FirebaseDatabase.getInstance().getReference().child("Products").child("here you put seller name"); // in your case the seller name is "d"
Hope it helps. For more informations ask me

My app keeps jumping back to an activity when there is a new node in Firebase and Android

I am new to Android and just published my app, the app is called random chat and its basically a chat application. So in order to record all of the user's names I used firebase real-time database. I have stored all of the User's data in a child in firebase called Usernames, in which the child of each User is stored with the user's UID (Obtained from Firebase Auth) as the main name and it has two children: name (which stores the name of the user) and phone (which stores the phone number of the user).
The problem is that in my app, every time a new user signs up, the app automatically switched from its current activity to a profile activity. I really don't understand why its happening, I thought it might be because the event listener in the other activity is still running but i remove the event listener at the onPause and onStop of every activity and I am using singleEventListeners.
My code is :
Profile Activity
public class ProfileActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private FirebaseDatabase mDatabase;
private DatabaseReference mRef;
TextView UsernameP;
AdView mAdView;
private ValueEventListener eventListener;
private ValueEventListener eventListener1;
ArrayList<String> listOfUsernames = new ArrayList<>();
ArrayList<String> listOfGroups = new ArrayList<>();
ProgressDialog pDialog;
String usernameToBePassed;
String useruuid;
String randomGroupName;
int timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Log.d("TDS","3");
timer = 0;
MobileAds.initialize(this, "my-admob-id");
mAdView = (AdView) findViewById(R.id.adView2);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
showProgress();
UsernameP = (TextView)findViewById(R.id.UsernameP);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference();
checkAndSetUserNameAndGetUsernameList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.log_out:
logOut();
return true;
case R.id.help:
startActivity(new Intent(ProfileActivity.this,HelpActivity.class));
default:
return super.onOptionsItemSelected(item);
}
}
public void logOut(){
mAuth.signOut();
FirebaseUser user = mAuth.getCurrentUser();
if (user == null){
Intent intent = new Intent(ProfileActivity.this,MainActivity.class);
startActivity(intent);
}
}
public void checkAndSetUserNameAndGetUsernameList() {
useruuid = mUser.getUid();
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (timer==0) {
usernameToBePassed = "" + dataSnapshot.getValue(String.class);
UsernameP.setText(usernameToBePassed);
cancleProgress();
timer = 1;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").child(useruuid).child("name").addListenerForSingleValueEvent(eventListener);
/* mRef.child("Usernames").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Dummies.clear();
listOfUsernames.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
String username = "" + user.name;
makeElementsUniqueUsingSet(Dummies,listOfUsernames,username);
if (mUser.getPhoneNumber().equals(user.phone)){
UsernameP.setText(user.name);
usernameToBePassed = user.name;
useruuid = snapshot.getKey();
}
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); */
}
public void makeElementsUniqueUsingSet(Set<String> sEntries,ArrayList<String> Entries,String entry){
sEntries.add(entry);
Entries.add(entry);
if (sEntries.size() != Entries.size()){
Entries.clear();
List<String> checkers = new ArrayList<String>(sEntries);
for (int i=0; i<sEntries.size();i++){
Entries.add(checkers.get(i));
}
checkers.clear();
}
Entries.removeAll(Collections.singleton(null));
}
public void getRandomChildname(){
showProgress();
final Set<String> sEntries = new HashSet<>();
eventListener1 = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String s = snapshot.child("name").getValue(String.class);
if (!snapshot.child("Users").hasChild(usernameToBePassed) && !s.equals(null)){
makeElementsUniqueUsingSet(sEntries,listOfGroups,s);
}
}
if (listOfGroups.size()>0) {
Random random = new Random();
int r = random.nextInt(listOfGroups.size());
randomGroupName = listOfGroups.get(r);
String randomGroupname = randomGroupName;
String uniqueUUID = UUID.randomUUID().toString();
mRef.child("GrouplistA").child(randomGroupname).child("Users").child(usernameToBePassed).child("name").setValue(usernameToBePassed);
mRef.child("GrouplistA").child(randomGroupname).child("Users").child(usernameToBePassed).child("status").setValue("normal");
mRef.child("GrouplistA").child(randomGroupname).child("status").setValue("hold");
mRef.child("GrouplistA").child(randomGroupname).child("ChatBox").child("CC-Randomizer-" + uniqueUUID).child("message").setValue("How's it going, people? Randomizer here letting you know there is a new user so all your names have been switched again.So Enjoy. Mizer out!");
mRef.child("GrouplistA").child(randomGroupname).child("ChatBox").child("CC-Randomizer-" + uniqueUUID).child("date").setValue(getCurrentDateAndTime());
cancleProgress();
Intent intent = new Intent(ProfileActivity.this, ChatActivity.class);
intent.putExtra("un", usernameToBePassed);
intent.putExtra("gr", randomGroupname);
intent.putExtra("gs", "A");
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(),"Sorry but there are no public sessions for you to barge in on",Toast.LENGTH_SHORT).show();
cancleProgress();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("GrouplistA").addListenerForSingleValueEvent(eventListener1);
}
public void showProgress()
{
pDialog = new ProgressDialog(ProfileActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
public void CreateGroup(View v){
Intent intent = new Intent(ProfileActivity.this,CreateGroupActivity.class);
intent.putExtra("un",usernameToBePassed);
intent.putExtra("uk",useruuid);
startActivity(intent);
finish();
}
public void GroupList(View v){
Intent intent = new Intent(ProfileActivity.this,GroupListActvity.class);
intent.putExtra("un",usernameToBePassed);
startActivity(intent);
finish();
}
public void FriendsList(View v){
Intent intent = new Intent(ProfileActivity.this,FriendsListActivity.class);
intent.putExtra("un",usernameToBePassed);
intent.putExtra("uk",useruuid);
startActivity(intent);
finish();
}
public void JoinGroup(View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("This will take you to a random public group. You ready?");
alert.setPositiveButton("Join", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getRandomChildname();
}
});
alert.setNegativeButton("Nevermind",null);
alert.show();
}
public String getCurrentDateAndTime(){
return DateFormat.getDateTimeInstance().format(new Date());
}
#Override
protected void onPause() {
super.onPause();
mRef.removeEventListener(eventListener);
if (eventListener1!=null) {
mRef.removeEventListener(eventListener1);
}
}
#Override
protected void onStop() {
super.onStop();
mRef.removeEventListener(eventListener);
if (eventListener1!=null) {
mRef.removeEventListener(eventListener1);
}
}
}
Sorry about the bad indenting. The profile activity is the activity that the app keeps jumping back to by the way
SignUpActivity : Im using Phone Auth
EditText MobileNumber;
CountryCodePicker ccp;
public ProgressDialog pDialog;
private DatabaseReference mRef;
private FirebaseAuth mAuth;
private PhoneAuthProvider mPhoneAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
String mVerificationId;
ValueEventListener eventListener;
private static final String TAG = "TDS";
ArrayList<String> MNumbers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("TDS","1");
new SimpleEula(this).show();
MobileNumber = (EditText) findViewById(R.id.MobileNumber);
ccp = (CountryCodePicker) findViewById(R.id.ccp);
mRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mPhoneAuth = PhoneAuthProvider.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
MobileNumber.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getApplicationContext(),"Quota exceeded.",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
}
public void Submit(View v){
if (!TextUtils.isEmpty(MobileNumber.getText().toString())) {
showProgress();
startPhoneVerification(ccp.getDefaultCountryCodeWithPlus() + MobileNumber.getText().toString());
} else {
MobileNumber.setError("Please enter your mobile number");
}
}
public void startPhoneVerification(String phoneNumber) {
mPhoneAuth.verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = task.getResult().getUser();
checkUserSignIn();
// ...
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(getApplicationContext(),"Verfication Code Invalid",Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
mPhoneAuth.verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks, // OnVerificationStateChangedCallbacks
token); // ForceResendingToken from callbacks
}
#Override
public void onStart() {
super.onStart();
checkUserSignIn();
}
public void checkUserSignIn() {
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
showProgress();
getandcheckAccount(currentUser);
}
}
public void showProgress()
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
public void getandcheckAccount(final FirebaseUser mUser){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(MainActivity.this,ProfileActivity.class));
} else {
startActivity(new Intent(MainActivity.this,UsernameActivity.class));
cancleProgress();
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
#Override
protected void onPause() {
super.onPause();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
#Override
protected void onStop() {
super.onStop();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}</i>
Im adding the username to the realtime database in a different activity
EditText Username;
TextView TitleTextU;
public ProgressDialog pDialog;
private FirebaseDatabase mDatabase;
private DatabaseReference mRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
ValueEventListener eventListener;
ArrayList<String> Usernames = new ArrayList<>();
ArrayList<String> MNumbers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
showProgress();
Log.d("TDS","2");
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference();
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
getListOfUsernames();
Username = (EditText)findViewById(R.id.Username);
TitleTextU = (TextView)findViewById(R.id.TitleTextU);
TitleTextU.setText("Enter a Username to Continue");
Username.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
//s is the current character in the eddittext after it is changed
if (Usernames.contains(Username.getText().toString())){
Username.setError("This username is taken");
}
}
});
}
public void Select(View v){
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String UID = mUser.getUid();
String MobileNumber = mUser.getPhoneNumber();
User user = new User(Username.getText().toString(),MobileNumber);
if (!TextUtils.isEmpty(Username.getText().toString())){
mRef.child("Usernames").child(UID).setValue(user);
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
} else {
Username.setError("Please enter a username");
}
}
public void getListOfUsernames(){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
Usernames.add("" + user.name);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
public void showProgress()
{
pDialog = new ProgressDialog(UsernameActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
#Override
protected void onPause() {
super.onPause();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
#Override
protected void onStop() {
super.onStop();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
Here is the problematic code:
public void getListOfUsernames(){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
Usernames.add("" + user.name);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
Every user that signs in makes all the users go to profile screen.

Why my getUID always be null?

I made an app that can let user log in and set marker on the google map and the marker connect to a chatroom that belongs to the user who set it.
I use firebase mail authentication ,the problem is that i can't get the uid and it's null,i tried a lot of ways,but it still didn't work.
Actually I can sotre my account data in firebase in createActivity with uid and it work,but when I switch to other activity ,the uid became null,I ask this before and someone told me to use this code:
Intent intent = new Intent(CreateActivity.this, MainActivity.class);
intent.putExtra("uid", currentUid);
startActivity(intent);
But it doesn't work.
can someone please help me find where is the problem ,here is my relative code:
LoginActivity:
public void login(View v){
final EditText edUserid = (EditText) findViewById(R.id.eduser);
final EditText edPass = (EditText) findViewById(R.id.edpass);
final String email = edUserid.getText().toString();
final String password = edPass.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "請輸入電子郵件!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "請輸入密碼", Toast.LENGTH_SHORT).show();
return;
}
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
edUserid.setError("密碼太短,請輸入超過6個字元!");
} else {
Toast.makeText(LoginActivity.this, "登入失敗", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(),"登入成功",Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
intent.putExtra("uid", currentUid);
startActivity(intent);
finish();
}
}
});
}
CreateActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
auth = FirebaseAuth.getInstance();
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void create(View v){
EditText Edcount = (EditText)findViewById(R.id.edcount);
EditText Edpass = (EditText)findViewById(R.id.edpass);
EditText Eduser = (EditText)findViewById(R.id.userid);
EditText Edpassag = (EditText)findViewById(R.id.edpassag);
final String email = Edcount.getText().toString().trim();
final String id = Eduser.getText().toString().trim();
final String password = Edpass.getText().toString().trim();
String password2 = Edpassag.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "請輸入電子郵件!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(id)) {
Toast.makeText(getApplicationContext(), "請輸入用戶名!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "請輸入密碼!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "密碼太短,請輸入超過6個字元!", Toast.LENGTH_SHORT).show();
return;
}
if(!password.equals(password2)){
Toast.makeText(getApplicationContext(), "密碼前後不符!", Toast.LENGTH_SHORT).show();
return;
}
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateActivity.this, new OnCompleteListener<AuthResult>() {
public void onComplete( Task<AuthResult> task) {
Toast.makeText(CreateActivity.this, "創建成功,歡迎使用SeeDate", Toast.LENGTH_SHORT).show();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(CreateActivity.this, "認證失敗或帳號已存在" ,
Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
DatabaseReference myRef = database.getReference("Contacts/" + currentUid);
ContactInfo contact1 = new ContactInfo(email,id,password);
myRef.setValue(contact1);//將會員資料寫入FIREBASE
Intent intent = new Intent(CreateActivity.this, MainActivity.class);
intent.putExtra("uid", currentUid);
startActivity(intent);
finish();
}
}
});
}
}
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance();
//get current user
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
// user auth state is changed - user is null
// launch login activity
userUID = getIntent().getStringExtra("uid");
}
else{
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
MapFragment(store the marker part):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
Intent intent = new Intent(getActivity(),LoginActivity.class);
startActivity(intent);
}
else{
MainActivity a ;
a = (MainActivity)getActivity();
a.userUID = userUID1;
Log.d("TAG", userUID1);
// userUID = (String) getActivity().getIntent().getExtras().get("uid");
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mview = inflater.inflate(R.layout.fragment_map, container, false);
return mview;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView)mview.findViewById(R.id.mapView);
if(mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseRef = mFirebaseDatabase.getReference("Map/" + userUID1);
mFirebaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
LatLng myLatLon = dataSnapshot.getValue(FirebaseMarker.class).toLatLng();
// stash the key in the title, for recall later
Marker myMarker = mgoogleMap.addMarker(new MarkerOptions()
.position(myLatLon).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.seedloc2)).title(dataSnapshot.getKey()));
// cache the marker locally
markers.put(dataSnapshot.getKey(), myMarker);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LatLng myLatLon = dataSnapshot.getValue(FirebaseMarker.class).toLatLng();
// Move markers on the map if changed on Firebase
Marker changedMarker = markers.get(dataSnapshot.getKey());
changedMarker.setPosition(myLatLon);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Marker deadMarker = markers.get(dataSnapshot.getKey());
deadMarker.remove();
markers.remove(dataSnapshot.getKey());
Log.v(TAG, "moved !" + dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.v(TAG, "canceled!" + databaseError.getMessage());
}
});
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mgoogleMap = googleMap;
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
// Remove map markers from Firebase when tapped
FirebaseDatabase.getInstance().getReference();
// String user = ContactInfo.getAccount();
CustomInfoWindowAdapter adapter = new CustomInfoWindowAdapter(MapFragment.this);
googleMap.setInfoWindowAdapter(adapter);
marker.setTitle("的種子");
marker.setSnippet("點選聊天");
marker.showInfoWindow();
// Intent intent = new Intent(getActivity(),ChatActivity.class);
// startActivity(intent);
return true;
}
});
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng latLng) {
// Taps create new markers in Firebase
// This works because jackson can figure out LatLng
mFirebaseRef.push().setValue(new FirebaseMarker(latLng));
}
});
mgoogleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
// not implemented
}
#Override
public void onMarkerDrag(Marker marker) {
// not implemented
}
#Override
public void onMarkerDragEnd(Marker marker) {
mFirebaseRef.child(marker.getTitle()).setValue(new FirebaseMarker(marker.getPosition()));
}
});
}
}
If you need more information,I'll update it.
You need to change this line:
userUID = getIntent().getStringExtra("uid");
with this line:
String userUID = user.getUid();
Log.d("TAG", userUID);
Hope it helps.
If I donot miss understand, the MapFragment is a part of your MainActivity. Your problem comes from this:
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
userUID = getIntent().getStringExtra("uid");
}
else{
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
As I can see, your userUID is null until there's an onAuthStateChanged changed. To sovlve it, I suggest to move this line to the onCreate of MainActiviy as your uid is passed to Intent in previous activity.

Categories

Resources