can not retrieve data from realtime data base into a recyclerView - java

i am working on a freelancing app called frelance. the idea of the app is to connect freelancers with clients that need their services.
and I am trying to retrieve data from the realtime database but it's not working.
ShowActivity Xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ShowActivity">
<androidx.appcompat.widget.SearchView
android:id="#+id/Search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#color/black"
android:layout_marginBottom="5dp"
android:hint="Search"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ShowActivity Java
Package com.example.frelance0;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Map;
public class ShowActivity extends AppCompatActivity {
private RecyclerView recyclerView;
SearchView searchView;
FirebaseAuth mAuth=FirebaseAuth.getInstance();
FirebaseAuth.AuthStateListener firebaseAuthListener;
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference F_Database= FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference Current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Freelancers");
private MyAdapter adapter;
private ArrayList<Model> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new MyAdapter(this, list);
recyclerView.setAdapter(adapter);
searchView = findViewById(R.id.Search);
//Log.d("user id", user_id);
//Log.d("database",F_Database.toString());
F_Database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Log.d("OUTSIDE LOOP", snapshot.getChildren().toString());
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Log.d("INSIDE LOOP", "MESSAGE");
Model model = dataSnapshot.getValue(Model.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
if(searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str){
ArrayList<Model> mylist = new ArrayList<>();
for(Model object: list){
if(object.getEmail().toLowerCase().contains(str.toLowerCase())){
mylist.add(object);
}
}
MyAdapter newAdapter = new MyAdapter(mylist);
recyclerView.setAdapter(newAdapter);
}
}
Adapter Code
package com.example.frelance0;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.frelance0.R;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
ArrayList<Model> mlist;
Context context;
public MyAdapter(Context context, ArrayList<Model> mlist){
this.mlist = mlist;
this.context = context;
}
public MyAdapter(ArrayList<Model> mylist) {
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Model model = mlist.get(position);
holder.Name.setText(model.getName());
holder.Email.setText(model.getEmail());
holder.JobTitle.setText(model.getJobTitle());
}
#Override
public int getItemCount() {
return mlist.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Name , Email , JobTitle;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Name= itemView.findViewById(R.id.Name);
Email= itemView.findViewById(R.id.Email);
JobTitle= itemView.findViewById(R.id.Job);
}
}
}
Model Class
package com.example.frelance0;
public class Model {
String Name , JobTitle , Email;
public void setName(String name) {
Name = name;
}
public void setJobTitle(String jobTitle) {
JobTitle = jobTitle;
}
public void setEmail(String email) {
Email = email;
}
public String getName() {
return Name;
}
public String getJobTitle() {
return JobTitle;
}
public String getEmail() {
return Email;
}
}
and Here is a screenshot of my Realtime Database:
Realtime Database
Realtime Database
Realtime Database
as you can see its nested and i don't know why.
app error recyclerview screenshot
I will also attach the Sign up Code in Case You need it Because i Have a nested database problem:
package com.example.frelance0;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.frelance0.C_Sign_in;
import com.example.frelance0.Client_Profile;
import com.example.frelance0.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class F_Sign_Up extends AppCompatActivity {
EditText mFirstName , mLastName , mEmail , mPassword , mphone;
EditText insta , behance , website ;
EditText Skill1 , Skill2 , Skill3 , Skill4 , Brief , jobTitle , Software1 , Software2 , Software3 , Software4;
ImageView ProfileImg;
Button register;
TextView mlogin;
ProgressBar progressBar;
String ProfileimgUrl;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener firebaseAuthListener;
DatabaseReference F_Database;
Uri resultUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__sign__up);
//connect Xml
mFirstName= (EditText) findViewById(R.id.FirstName);
mLastName= (EditText) findViewById(R.id.LastName);
mEmail= (EditText) findViewById(R.id.email);
mPassword= (EditText) findViewById(R.id.password);
mphone= (EditText) findViewById(R.id.phone);
register= (Button) findViewById(R.id.signUp);
mlogin = (TextView) findViewById(R.id.logIn);
progressBar= (ProgressBar) findViewById(R.id.progressBar);
Skill1 = (EditText) findViewById(R.id.skill1);
Skill2 = (EditText) findViewById(R.id.skill2);
Skill3 = (EditText) findViewById(R.id.skill3);
Skill4 = (EditText) findViewById(R.id.skill4);
Software1 = (EditText) findViewById(R.id.software1);
Software2 = (EditText) findViewById(R.id.software2);
Software3 = (EditText) findViewById(R.id.software3);
Software4 =(EditText) findViewById(R.id.software4);
jobTitle = (EditText) findViewById(R.id.JobTiTleHint);
Brief = (EditText) findViewById(R.id.Brief);
insta = (EditText) findViewById(R.id.insta);
behance = (EditText) findViewById(R.id.Behance);
website = (EditText) findViewById(R.id.Website);
ProfileImg = findViewById(R.id.ProfilePic);
String img = ProfileImg.toString();
ProfileImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent , 1);
}
});
mAuth =FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
Intent intent = new Intent(com.example.frelance0.F_Sign_Up.this, Freelancer_Profile.class);
String P = mphone.getText().toString();
intent.putExtra("Phone",P);
startActivity(intent);
return;
}
}
};
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
mAuth =FirebaseAuth.getInstance();
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(Email,Password).addOnCompleteListener(com.example.frelance0.F_Sign_Up.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// if (task.isSuccessful()){
//Toast.makeText(F_Sign_Up.this, "Sign Up Error", Toast.LENGTH_SHORT).show();
if(TextUtils.isEmpty(Email)){
mEmail.setError("E-mail is Required");
return;
}
if(TextUtils.isEmpty(Password)){
mPassword.setError("Password is Required");
return;
}
if(Password.length() < 6){
mPassword.setError("Password Must Be More Than 6 Char ");
return;
}
if(mAuth.getCurrentUser() != null) {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference Current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Freelancers").child(user_id);
Current_user_db.setValue(true);
F_Database =FirebaseDatabase.getInstance().getReference().child("Users").child("Freelancers").child(user_id);
Getinfo();
Saveinfo();
Intent intent = new Intent(com.example.frelance0.F_Sign_Up.this, loading.class);
//Phone Intent
String P = mphone.getText().toString();
intent.putExtra("Phone",P);
startActivity(intent);
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
String FirstName = mFirstName.getText().toString();
String LastName = mLastName.getText().toString();
String FullName = mFirstName.getText().toString() + " " + mLastName.getText().toString();
String PhoneNum= mphone.getText().toString();
String Fsoftware= Software1.getText().toString();
String ssoftware= Software2.getText().toString();
String tsoftware= Software3.getText().toString();
String Ffsoftware= Software4.getText().toString();
String Fskill= Skill1.getText().toString();
String sskill= Skill2.getText().toString();
String tskill= Skill3.getText().toString();
String Ffskill= Skill4.getText().toString();
String JB= jobTitle.getText().toString();
String B= Brief.getText().toString();
String Be = behance.getText().toString();
String instag = insta.getText().toString();
String web = website.getText().toString();
Users user = new Users(FullName,FirstName,LastName,Email,Fskill,sskill,tskill,Ffskill,Fsoftware,ssoftware,tsoftware,Ffsoftware,web,instag,Be,JB,Integer.parseInt(PhoneNum));
F_Database.child("Users").child("Freelancers").push().setValue(user);
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
public void Saveinfo(){
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
String FirstName = mFirstName.getText().toString();
String LastName = mLastName.getText().toString();
String FullName = mFirstName.getText().toString() + " " + mLastName.getText().toString();
String PhoneNum= mphone.getText().toString();
String Fsoftware= Software1.getText().toString();
String ssoftware= Software2.getText().toString();
String tsoftware= Software3.getText().toString();
String Ffsoftware= Software4.getText().toString();
String Fskill= Skill1.getText().toString();
String sskill= Skill2.getText().toString();
String tskill= Skill3.getText().toString();
String Ffskill= Skill4.getText().toString();
String JB= jobTitle.getText().toString();
String B= Brief.getText().toString();
String Be = behance.getText().toString();
String instag = insta.getText().toString();
String web = website.getText().toString();
Map<String,Object> Map = new HashMap<>();
Map userinfo = new HashMap();
userinfo.put("First Name",FirstName);
userinfo.put("Last Name",LastName);
userinfo.put("Full Name",FullName);
userinfo.put("Email",Email);
userinfo.put("Phone Number" , PhoneNum);
//Skills
userinfo.put("Skill 1",Fskill);
userinfo.put("Skill 2",sskill);
userinfo.put("Skill 3",tskill);
userinfo.put("Skill 4",Ffskill);
//Softwares
userinfo.put("Software 1",Fsoftware);
userinfo.put("Software 2",ssoftware);
userinfo.put("Software 3",tsoftware);
userinfo.put("Software 4",Ffsoftware);
//other
userinfo.put("Brief",B);
userinfo.put("Job Title",JB);
userinfo.put("Website",web);
userinfo.put("Instagram",instag);
userinfo.put("Behance",Be);
String user_id = mAuth.getCurrentUser().getUid();
F_Database.updateChildren(userinfo);
if(resultUri!= null){
StorageReference FilePath = FirebaseStorage.getInstance().getReference().child("Profile images").child(user_id);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,20,baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = FilePath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl();
Map newImg = new HashMap();
newImg.put("ProfileImageUrl", downloadUrl.toString());
F_Database.updateChildren(newImg);
finish();
return;
}
});
}else {
finish();
}
}
public void Getinfo(){
F_Database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot datasnapshot) {
if(datasnapshot.exists() && datasnapshot.getChildrenCount()>0){
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
String FirstName = mFirstName.getText().toString();
String LastName = mLastName.getText().toString();
// String FullName = mFirstName.getText().toString() + " " + mLastName.getText().toString();
String PhoneNum= mphone.getText().toString();
String Fsoftware= Software1.getText().toString();
String ssoftware= Software2.getText().toString();
String tsoftware= Software3.getText().toString();
String Ffsoftware= Software4.getText().toString();
String Fskill= Skill1.getText().toString();
String sskill= Skill2.getText().toString();
String tskill= Skill3.getText().toString();
String Ffskill= Skill4.getText().toString();
String JB= jobTitle.getText().toString();
String B= Brief.getText().toString();
String Be = behance.getText().toString();
String instag = insta.getText().toString();
String web = website.getText().toString();
Map<String,Object> Map = new HashMap<>();
if(Map.get("First Name")!=null){
FirstName = Map.get("First Name").toString();
mFirstName.setText(FirstName);
}
if(Map.get("Email")!=null){
Email = Map.get("Email").toString();
mEmail.setText(Email);
}
if(Map.get("Password")!=null){
Password = Map.get("Password").toString();
mPassword.setText(Password);
}
if(Map.get("LastName")!=null){
LastName = Map.get("LastName").toString();
mLastName.setText(LastName);
}
if(Map.get("PhoneNum")!=null){
PhoneNum = Map.get("PhoneNum").toString();
mphone.setText(PhoneNum);
}
if(Map.get("Fsoftware")!=null){
Fsoftware = Map.get("Fsoftware").toString();
Software1.setText(Fsoftware);
}
if(Map.get("ssoftware")!=null){
ssoftware = Map.get("ssoftware").toString();
Software2.setText(ssoftware);
}
if(Map.get("tsoftware")!=null){
tsoftware= Map.get("ssoftware").toString();
Software3.setText(tsoftware);
}
if(Map.get("Ffsoftware")!=null){
Ffsoftware = Map.get("Ffsoftware").toString();
Software4.setText(Ffsoftware);
}
if(Map.get("Fskill")!=null){
Fskill = Map.get("First Name").toString();
Skill1.setText(Fskill);
}
if(Map.get("sskill")!=null){
sskill = Map.get("First Name").toString();
Skill2.setText(sskill);
}
if(Map.get("tskill")!=null){
tskill = Map.get("tskill").toString();
Skill3.setText(tskill);
}
if(Map.get("Ffskill")!=null){
Ffskill= Map.get("Ffskill").toString();
Skill4.setText(Ffskill);
}
if(Map.get("JB")!=null){
JB = Map.get("JB").toString();
jobTitle.setText(JB);
}
if(Map.get("B")!=null){
B = Map.get("B").toString();
Brief.setText(B);
}
if(Map.get("Be")!=null){
Be = Map.get("Be").toString();
behance.setText(Be);
}
if(Map.get("instag")!=null){
instag = Map.get("instag").toString();
insta.setText(instag);
}
if(Map.get("web")!=null){
web = Map.get("web").toString();
website.setText(web);
}
if(Map.get("ProfileImageUrl")!=null){
ProfileimgUrl = Map.get("ProfileImageUrl").toString();
Glide.with(getApplication()).load(ProfileimgUrl).into(ProfileImg);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void onClick(View view){
Intent intent = new Intent(com.example.frelance0.F_Sign_Up.this, Freelancer_Log_in.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 1 && requestCode == Activity.RESULT_OK);
final Uri imgUri = data.getData();
resultUri = imgUri;
ProfileImg.setImageURI(imgUri);
}
}

Related

update one or more fields inside of a document, without updating all the fields

I have a feature in my program where I have to enter the user's details such as the user's age, height, and weight. This data will be stored in Firestore.
this is how the user will input their details
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.button.MaterialButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class account_information extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_create;
FirebaseFirestore db;
FirebaseAuth mAuth;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_information);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_create = findViewById(R.id.btn_create);
btn_create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
if(age.isEmpty()){
et_age.setError("Age is mandatory");
et_age.requestFocus();
return;
}
if(height.isEmpty()){
et_height.setError("Height is mandatory");
et_height.requestFocus();
return;
}
if(weight.isEmpty()){
et_weight.setError("Weight is mandatory");
et_weight.requestFocus();
return;
}
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = db.collection("userDetail").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("Age",age);
user.put("Height",height);
user.put("Weight",weight);
user.put("UserId", userID);
documentReference.set(user)
.addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(account_information.this, MainActivity.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}
}
And this is how it will store in firebase
https://imgur.com/a/wtCJt8X
However, when the user decides to update their profile (for example his weight) the rest of the input will pass an empty string at the firebase
like this:
https://imgur.com/oskucbl
And this is how the user can update their details
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
public class UpdateProfile extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_update;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_update = findViewById(R.id.btn_update);
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
documentReference
.update("Age",age, "Height",height, "Weight",weight)
.addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(UpdateProfile.this, MainActivity.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}}
Update: I've tried the method of #zen_of_kermit but I got the same problem, maybe there's something in the code that I've missed
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class UpdateProfile extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_update;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_update = findViewById(R.id.btn_update);
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
Map<String, Object> dataToUpdateMap = new HashMap<>();
if (isValidAndChanged(documentReference, "Age", age)) {
dataToUpdateMap.put("Age", age);
}
if (isValidAndChanged(documentReference, "Height", height)) {
dataToUpdateMap.put("Height", height);
}
if (isValidAndChanged(documentReference, "Weight", weight)) {
dataToUpdateMap.put("Weight", weight);
}
documentReference.update(dataToUpdateMap).addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(UpdateProfile.this, readProfileData.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}
boolean isValidAndChanged(DocumentReference docRef, String key, Object value) {
return true;
}
}
You are passing all three fields (age, height, weight) without checking if they are valid or contain changes to the existing data. You should make those checks before calling update, similar to how you did in the create function.
For example, create a function to check if new data is valid and different than old data:
boolean isValidAndChanged(DocumentReference docRef, String key, String value) {
// TODO get snapshot of data and compare to new value
}
And then use that to update (passing a Map to update instead of var-args):
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
Map<String, String> dataToUpdateMap = new HashMap<>();
if (isValidAndChanged(documentReference, "Age", age)) {
dataToUpdateMap.put("Age", age);
}
if (isValidAndChanged(documentReference, "Height", height)) {
dataToUpdateMap.put("Height", height);
}
if (isValidAndChanged(documentReference, "Weight", weight)) {
dataToUpdateMap.put("Weight", weight);
}
documentReference.update(dataToUpdateMap)
// ...
Also, best practice is to use constants instead of passing magic strings around all over your code (e.g. "Age" becomes AGE.)
You're getting all the data overwritten because you're passing empty strings to the update() method. Firestore can indeed hold null values, but the values of Age and Height after the update are not null, but empty strings.
If you want to update a single field and leave the other ones untouched, then you should simply pass to the update() method only values for the fields you need to update. In code, it should look like this:
documentReference.update("Weight", weight).addOnSuccessListener(/* ... /*);

How to use snapshot result, in a firebase transaction

0
I have a Scores node in my database. At the moment, I can update the score after a game. For the purposes of creating a leaderboard, I want to add the users username to the node as well. I have tried to use Transactions that take a snapshot, to get the current logged in username, that when the score is updated, the name will also be added to the Scores node.
I can retrieve the username using my transaction, but cant figure out how to pass this value, to the Scores node.
This is what I have so far, this code allows me to update the "Points" in the scores node, and allows me to retrieve the name of the logged in user, but not set this value in the Scores node of the database:
package com.example.securityapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
public class industry_standards_questions extends AppCompatActivity {
DatabaseReference databaseUsers, databaseUsername;
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseAuth mAuth;
TextView stmnt;
ImageView image_true, image_false;
Button points, finished;
Statements tfStatements;
int statementsLength;
ArrayList<Item> statementList;
int currentStatement = 0;
int grade = 0;
String name;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_industry_standards_questions);
databaseUsers = database.getReference("Scores");
databaseUsername = database.getReference("Users");
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
stmnt = (TextView) findViewById(R.id.statement_TV);
image_true = (ImageView) findViewById(R.id.trueImage);
image_true.setFocusable(false);
image_false = (ImageView) findViewById(R.id.falseImage);
image_false.setFocusable(false);
tfStatements = new Statements();
statementsLength = tfStatements.tfStatements.length;
statementList = new ArrayList<>();
finished = (Button) findViewById(R.id.finish);
points = (Button) findViewById(R.id.final_score);
for (int i = 0; i < statementsLength; i++)
{
statementList.add(new Item(tfStatements.getStatement(i), tfStatements.getAnswer(i)));
}
Collections.shuffle(statementList);
setStmnt(currentStatement);
}
// show Statement
private void setStmnt(int number) {
stmnt.setText(statementList.get(number).getStatement());
}
//check is answer is right
private boolean checkAnswer(int number) {
String answer = statementList.get(number).getAnswer();
return answer.equals("true");
}
public void trueClicked(View view) {
if (checkAnswer(currentStatement)) {
grade++;
}
currentStatement++;
if (currentStatement >= statementsLength) {
score();
return;
}
if (currentStatement <= statementsLength )
setStmnt(currentStatement);
}
public void falseClicked(View view) {
if (!checkAnswer(currentStatement)) {
grade++;
}
currentStatement++;
if (currentStatement >= statementsLength) {
score();
return;
}
if (currentStatement <= statementsLength )
setStmnt(currentStatement);
}
public void score() {
String id = mAuth.getCurrentUser().getUid();
DatabaseReference score = databaseUsers.child(id).child("Points");
DatabaseReference set_username = databaseUsers.child(id).child("Username");
final DatabaseReference get_user_name = databaseUsername.child(id).child("username");
final int pointsEarned = grade;
score.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
System.out.println("You scored: " + pointsEarned);
System.out.println("The current score is: " + mutableData.getValue(Integer.class));
mutableData.setValue((mutableData.getValue() == null ? 0 : mutableData.getValue(Integer.class)) + pointsEarned);
System.out.println("The new score is: " + mutableData.getValue(Integer.class));
return Transaction.success(mutableData);
}
#Override
public void onComplete(#Nullable DatabaseError databaseError, boolean b, #Nullable DataSnapshot dataSnapshot) {
}
}
);
get_user_name.runTransaction(new Transaction.Handler() {
#NonNull
#Override
public Transaction.Result doTransaction(#NonNull MutableData mutableData) {
String name = mutableData.getValue(String.class);
return Transaction.success(mutableData);
}
#Override
public void onComplete(#Nullable DatabaseError databaseError, boolean b, #Nullable DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue().toString();
}
});
set_username.runTransaction(new Transaction.Handler() {
#NonNull
#Override
public Transaction.Result doTransaction(#NonNull MutableData mutableData) {
mutableData.setValue(name);
return Transaction.success(mutableData);
}
#Override
public void onComplete(#Nullable DatabaseError databaseError, boolean b, #Nullable DataSnapshot dataSnapshot) {
}
});
Toast.makeText(this, "You scored " + grade + " points!", Toast.LENGTH_LONG).show();
grade = 0;
}
public void FinishedOnClick (View view)
{
Intent intent_finished = new Intent(industry_standards_questions.this, industry_standards_rating_screen.class);
startActivity(intent_finished);
finish();
}
}

How to read and display user's rank which is set as default in the beginning

I added a new column COL_5 to my SQLite database and it's called "rank". Every user registered starts with rank set as "Australopithecus afarensis" which should be displayed in UserPanelActivity.java. What I did is I managed to display nickname of user (SignInActivity) but I have trouble with checking current rank and then display it on the screen.
Code looks like this:
DatabaseHelper:
package com.pracainzynierska.inzynierka;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="register.db";
public static final String TABLE_NAME="registeruser";
public static final String COL_1 ="ID";
public static final String COL_2 ="username";
public static final String COL_3 ="mail_address";
public static final String COL_4 ="password";
public static final String COL_5 = "rank";
//public static final String COL_6 = "dailytip";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME,null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT, mail_address TEXT, password TEXT, rank TEXT DEFAULT 'Australopithecus afarensis')");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addUser(String user, String password, String mail_address) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", user);
contentValues.put("password", password);
contentValues.put("mail_address", mail_address);
long res = db.insert("registeruser", null, contentValues);
db.close();
return res;
}
public boolean checkUser(String username, String password)
{
String[] columns = {COL_1};
SQLiteDatabase db = getReadableDatabase();
String selection = COL_2 + "=?" + " and " + COL_4 + "=?";
String[] selectionArgs = {username, password};
Cursor cursor = db.query(TABLE_NAME, columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if(count>0)
return true;
else
return false;
}
}
SignInActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
public class SignInActivity extends AppCompatActivity {
private TextView register_text;
public static CallbackManager callbackManager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
db = new DatabaseHelper(this);
callbackManager = CallbackManager.Factory.create();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
usernameEditText.requestFocus();
register_text = findViewById(R.id.register_text);
register_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(SignInActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = usernameEditText.getText().toString().trim();
String pwd = passwordEditText.getText().toString().trim();
Boolean res = db.checkUser(user,pwd);
if(res == true)
{
Intent intent = new Intent(SignInActivity.this,UserPanelActivity.class);
Intent intentPopUp = new Intent(SignInActivity.this, PopUpActivity.class);
intent.putExtra("username",user);
startActivity(intent);
startActivity(intentPopUp);
Toast.makeText(SignInActivity.this,"Welcome " + user + "!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this,"There is a problem with singing in!", Toast.LENGTH_SHORT).show();
usernameEditText.setText("");
passwordEditText.setText("");
usernameEditText.requestFocus();
}
}
});
}
}
UserPanelActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserPanelActivity extends AppCompatActivity {
private Button settings_btn, progress_btn, dailychallenge_btn, premium_btn, logout_btn, training_btn;
private TextView NickNameText, rankText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_panel);
String username = getIntent().getStringExtra("username");
//String rank = getIntent().getStringExtra("rank");
NickNameText = findViewById(R.id.nickname);
NickNameText.setText(username);
//here I'd like to display rank
rankText = findViewById(R.id.rank);
rankText.setText(rank);
settings_btn = findViewById(R.id.settings_user_panel_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Settings();
}
});
progress_btn = findViewById(R.id.progress_button);
progress_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyProgress();
}
});
dailychallenge_btn = findViewById(R.id.challenge_button);
dailychallenge_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DailyChallenge();
}
});
premium_btn = findViewById(R.id.premium_button);
premium_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Premium();
}
});
logout_btn = findViewById(R.id.logout_button);
logout_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackToMenu();
finish();
}
});
training_btn = findViewById(R.id.start_freetraining_button);
training_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Training();
}
});
}
private void Training() {
Intent intent = new Intent(this, FillTheTextActivity.class);
startActivity(intent);
}
private void BackToMenu() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void Premium() {
Intent intent = new Intent(this,PremiumActivity.class);
startActivity(intent);
}
private void DailyChallenge() {
Intent intent = new Intent(this,DailyChallengeActivity.class);
startActivity(intent);
}
private void MyProgress() {
Intent intent = new Intent(this,MyProgressActivity.class);
startActivity(intent);
}
private void Settings() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
Every help is kindly seen, thanks in advance :)
Create a method like this in your DatabaseHelper class:
public String getRank(int id) {
String query = "SELECT rank from " + TABLE_NAME + " where ID = " + id;
SQLiteDatabase db = getReadableDatabase();
try {
return db.rawQuery(query, null).getString(cursor.getColumnIndex(rank));
} catch (Exception e) {
return "";
}
}
Source

I want to add country code from dropdown

How can I do this, I searched on StackOverflow, but solution is for iphone, not android.
Here is my chat app: https://play.google.com/store/apps/details?id=com.jimmytrivedi.lapitchat
package com.jimmytrivedi.lapitchat;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneAuthActivity extends AppCompatActivity {
private LinearLayout DialLayout, LockLayout;
private EditText PhoneNumber, code;
private ProgressBar PhoneProgress, CodeProgress;
private Button sendVerification;
private Toolbar PhoneToolbar;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String number;
private FirebaseAnalytics mFirebaseAnalytics;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private FirebaseAuth mAuth;
private TextView ErrorView;
private int Verify = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_auth);
DialLayout = findViewById(R.id.DialLayout);
LockLayout = findViewById(R.id.LockLayout);
PhoneNumber = findViewById(R.id.PhoneNumber);
code = findViewById(R.id.code);
PhoneProgress = findViewById(R.id.PhoneProgress);
CodeProgress = findViewById(R.id.CodeProgress);
sendVerification = findViewById(R.id.sendVerification);
PhoneToolbar = findViewById(R.id.PhoneToolbar);
ErrorView = findViewById(R.id.ErrorView);
PhoneProgress.setVisibility(View.INVISIBLE);
CodeProgress.setVisibility(View.INVISIBLE);
sendVerification.setEnabled(false);
LockLayout.setVisibility(View.INVISIBLE);
setSupportActionBar(PhoneToolbar);
getSupportActionBar().setTitle("Welcome to Phone Verification");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mAuth = FirebaseAuth.getInstance();
PhoneNumber.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) {
String text = charSequence.toString();
if (!text.isEmpty()) {
sendVerification.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
sendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Verify == 0) {
if (!PhoneNumber.getText().toString().isEmpty()) {
number = PhoneNumber.getText().toString();
PhoneNumber.setEnabled(false);
sendVerification.setEnabled(false);
PhoneProgress.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
PhoneAuthActivity.this,
mCallbacks
);
}
} else {
String VerificationCode = code.getText().toString();
sendVerification.setEnabled(false);
CodeProgress.setVisibility(View.VISIBLE);
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(
mVerificationId,VerificationCode);
signInWithPhoneAuthCredential(credential);
}
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
PhoneProgress.setVisibility(View.INVISIBLE);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
ErrorView.setText("There was some error in verification");
ErrorView.setVisibility(View.VISIBLE);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Log.d("wihddiewd", "FirebaseAuthInvalidCredentialsException: " + e);
} else if (e instanceof FirebaseTooManyRequestsException) {
Log.d("wihddiewd", "FirebaseTooManyRequestsException: " + e);
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Log.d("wihddiewd", "onCodeSent:" + verificationId);
mVerificationId = verificationId;
mResendToken = token;
Verify=1;
PhoneProgress.setVisibility(View.INVISIBLE);
LockLayout.setVisibility(View.VISIBLE);
sendVerification.setEnabled(true);
sendVerification.setText("Verify code");
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(PhoneAuthActivity.this, MainActivity.class));
finish();
} else {
ErrorView.setText("There was some error in logging in");
ErrorView.setVisibility(View.VISIBLE);
Log.w("wihddiewd", "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
}
I don't know what type of code is necessary and where should I add?
Try this lib:
CountryCodePicker
dependencies {
implementation 'com.hbb20:ccp:2.2.2'
}
In XML
<com.hbb20.CountryCodePicker
android:id="#+id/country_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center|center_vertical"
android:includeFontPadding="false"
android:textColor="#color/text_black"
app:ccp_showNameCode="false"
app:ccp_textSize="#dimen/small_text_size" />
In Activity
CountryCodePicker country_picker = findViewById(R.id.country_picker);
String country_code = country_picker.getSelectedCountryCode();

Android cart button not working with database

I really need help while whenever I press cart button to add food to basket app stop working and can't submit my assignment when cart button doesn't work. I use Firebase which is working and DB browser for SQLite. I triple - quatrocheck the names in databases with the names in code and still I don't know why it doesn't work. Would appreciate any help.
error in picture (LogCat): https://ibb.co/n4bMWb
Code of Databases.
package com.example.onix.AndroEat.Database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
import java.util.ArrayList;
import java.util.List;
import com.example.onix.AndroEat.Model.Order;
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="Eat.db";
private static final int DB_VER=1;
public Database(Context context) {
super(context, DB_NAME,null, DB_VER);
}
public List<Order> getCarts()
{
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect={"ID","ProductName","ProductId","Quantity","Price",};
String sqlTable="OrderDetail";
qb.setTables(sqlTable);
Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);
final List<Order> result = new ArrayList<>();
if(c.moveToFirst())
{
do{
result.add(new Order(
c.getInt(c.getColumnIndex("ID")),
c.getString(c.getColumnIndex("ProductId")),
c.getString(c.getColumnIndex("ProductName")),
c.getString(c.getColumnIndex("Quantity")),
c.getString(c.getColumnIndex("Price"))
));
}while (c.moveToNext());
}
return result;
}
public void addToCart(Order order) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,)VALUES('%s','%s','%s','%s');",
order.getProductId(),
order.getProductName(),
order.getQuantity(),
order.getPrice());
db.execSQL(query);
}
public void cleanCart()
{
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM OrderDetail");
db.execSQL(query);
}
public int getCountCart() {
int count=0;
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT COUNT(*) FROM OrderDetail");
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst())
{
do{
count = cursor.getInt(0);
}while (cursor.moveToNext());
}
return count;
}
public void updateCart(Order order) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("UPDATE OrderDetail SET Quantity= %s WHERE ID = %d",order.getQuantity(),order.getID());
db.execSQL(query);
}
}
Code of FoodDetail:
package com.example.onix.AndroEat;
import android.content.Context;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.andremion.counterfab.CounterFab;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.example.onix.AndroEat.Common.Common;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.stepstone.apprating.AppRatingDialog;
import com.stepstone.apprating.listener.RatingDialogListener;
import java.util.Arrays;
import com.example.onix.AndroEat.Model.Food;
import com.example.onix.AndroEat.Model.Order;
import com.example.onix.AndroEat.Model.Rating;
import com.example.onix.AndroEat.Database.Database;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class FoodDetail extends AppCompatActivity implements RatingDialogListener {
TextView food_name,food_price,food_description;
ImageView food_image;
CollapsingToolbarLayout collapsingToolbarLayout;
FloatingActionButton btnRating;
CounterFab btnCart;
ElegantNumberButton numberButton;
RatingBar ratingBar;
String foodId="";
FirebaseDatabase database;
DatabaseReference foods;
DatabaseReference ratingTbl;
Food currentFood;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/restaurant_font.otf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_food_detail);
//Firebase
database = FirebaseDatabase.getInstance();
foods = database.getReference("Foods");
ratingTbl = database.getReference("Rating");
//Init view
numberButton = (ElegantNumberButton)findViewById(R.id.number_button);
btnCart = (CounterFab) findViewById(R.id.btnCart);
btnRating = (FloatingActionButton)findViewById(R.id.btn_rating);
ratingBar = (RatingBar)findViewById(R.id.ratingBar);
btnRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRatingDialog();
}
});
btnCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Database(getBaseContext()).addToCart(new Order(
foodId,
currentFood.getName(),
numberButton.getNumber(),
currentFood.getPrice()
));
Toast.makeText(FoodDetail.this, "Added to Cart", Toast.LENGTH_SHORT).show();
}
});
btnCart.setCount(new Database(this).getCountCart());
food_description = (TextView)findViewById(R.id.food_description);
food_name = (TextView)findViewById(R.id.food_name);
food_price = (TextView)findViewById(R.id.food_price);
food_image = (ImageView)findViewById(R.id.img_food);
collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppbar);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppbar);
//Get Food Id from Intent
if(getIntent() != null)
foodId = getIntent().getStringExtra("FoodId");
if(!foodId.isEmpty())
{
if(Common.isConnectedToInterner(getBaseContext()))
{
getDetailFood(foodId);
getRatingFood(foodId);
}
else
{
Toast.makeText(FoodDetail.this, "Please check your connection !!", Toast.LENGTH_SHORT).show();
return;
}
}
}
private void getRatingFood(String foodId) {
com.google.firebase.database.Query foodRating = ratingTbl.orderByChild("foodId").equalTo(foodId);
foodRating.addValueEventListener(new ValueEventListener() {
int count=0,sum=0;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Rating item = postSnapshot.getValue(Rating.class);
sum+=Integer.parseInt(item.getRateValue());
count++;
}
if(count != 0)
{
float average = sum/count;
ratingBar.setRating(average);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showRatingDialog() {
new AppRatingDialog.Builder()
.setPositiveButtonText("Submit")
.setNegativeButtonText("Cancel")
.setNoteDescriptions(Arrays.asList("Very Bad","Not Good","Quite Ok","Very Good","Excellent"))
.setDefaultRating(1)
.setTitle("Rate this food")
.setDescription("Please select some stars and give your feedback")
.setTitleTextColor(R.color.colorPrimary)
.setDescriptionTextColor(R.color.colorPrimary)
.setHint("Please write your comment here...")
.setHintTextColor(R.color.colorAccent)
.setCommentTextColor(android.R.color.white)
.setCommentBackgroundColor(R.color.colorPrimaryDark)
.setWindowAnimation(R.style.RatingDialogFadeAnim)
.create(FoodDetail.this)
.show();
}
private void getDetailFood(String foodId) {
foods.child(foodId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentFood = dataSnapshot.getValue(Food.class);
//Set Image
Picasso.with(getBaseContext()).load(currentFood.getImage())
.into(food_image);
collapsingToolbarLayout.setTitle(currentFood.getName());
food_price.setText(currentFood.getPrice());
food_name.setText(currentFood.getName());
food_description.setText(currentFood.getDescription());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onPositiveButtonClicked(int value, String comments) {
//Get Rating and upload to firebase
final Rating rating = new Rating(Common.currentUser.getPhone(),
foodId,
String.valueOf(value),
comments);
ratingTbl.child(Common.currentUser.getPhone()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(Common.currentUser.getPhone()).exists())
{
//Remove old value (you can delete or let it be - useless function :D)
ratingTbl.child(Common.currentUser.getPhone()).removeValue();
//Update new value
ratingTbl.child(Common.currentUser.getPhone()).setValue(rating);
}
else
{
//Update new value
ratingTbl.child(Common.currentUser.getPhone()).setValue(rating);
}
Toast.makeText(FoodDetail.this, "Thank you for submit rating !!!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onNegativeButtonClicked() {
}
}
Will post more code IF needed.
Thank you very much.
"," should be removed after price in the above code. Below is the rite code
String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price)VALUES('%s','%s','%s','%s');",
order.getProductId(),
order.getProductName(),
order.getQuantity(),
order.getPrice());
Also remove "," from below code above
String[] sqlSelect={"ID","ProductName","ProductId","Quantity","Price"};

Categories

Resources