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();
}
}
Related
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);
}
}
I am a beginner at coding in Java. I am creating a notes app with lots of other features. And one of the features are, storing the user's bank card details in a RecyclerView. I did this by making an SQLite CRUD. All of the Create, Read, Update and Delete works. And I protected this page with a Pattern lock.
And when we are in the Input Pattern page, we can see a clickable text called Click HERE if you forgot your pattern, That works. And when you click on that clickable text, the app shows an Alert Dialog, titled are you sure? and the message is If you change your pattern, all your data will be deleted then there are two buttons Yes and No. No does nothing, it just cancel the forgot pattern thing. But the problem is with the Yes button.
When we click it, It should delete all bank cards or delete all data. Please suggest a way to delete all data from the SQLite Database. I tried lots of ways to do this.
HERE IS MY INPUT PATTERN ACTIVITY
package com.ixidev.simplenotepad;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ixidev.simplenotepad.model.Note;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ProgramActivity extends AppCompatActivity {
FloatingActionButton fab, fabChangePattern, fabexit;
RecyclerView mRecyclerViewBC;
CardsDatabaseHelper cardsDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
mRecyclerViewBC = findViewById(R.id.recyclerViewBC);
cardsDatabaseHelper = new CardsDatabaseHelper(this);
showRecord();
fabexit = findViewById(R.id.exitProgram);
fab = findViewById(R.id.addFabButtonBC);
fabChangePattern = findViewById(R.id.ChangePattern);
fabexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, MainActivity.class);
startActivity(intent);
}
});
fabChangePattern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, CreatePasswordActivity.class);
startActivity(intent);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, AddBankCardActivity.class);
intent.putExtra("BCeditMode", false);
startActivity(intent);
}
});
}
private void showRecord() {
CardAdapter cardAdapter = new CardAdapter(ProgramActivity.this, cardsDatabaseHelper.getAllBCdata(ConstantsCard.BC_C_ADD_TIMESTAMP + " DESC"));
mRecyclerViewBC.setAdapter(cardAdapter);
}
#Override
protected void onResume() {
super.onResume();
showRecord();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
}
HERE IS MY DATABASE HELPER CLASS
package com.ixidev.simplenotepad;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class CardsDatabaseHelper extends SQLiteOpenHelper {
public CardsDatabaseHelper(#Nullable Context context) {
super(context, ConstantsCard.BC_DB_NAME, null, ConstantsCard.BC_DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ConstantsCard.BC_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ConstantsCard.BC_TABLE_NAME);
onCreate(db);
}
public long insertInfo(String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
long id = db.insert(ConstantsCard.BC_TABLE_NAME, null, values);
db.close();
return id;
}
public void updateInfo(String BCid, String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
db.update(ConstantsCard.BC_TABLE_NAME, values, ConstantsCard.BC_C_ID + " = ?", new String[]{BCid});
db.close();
}
public void deleteInfo(String BCid) {
SQLiteDatabase db = getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME, ConstantsCard.BC_C_ID + " = ? ", new String[]{BCid});
db.close();
}
public void testDelete() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME,null,null);
db.execSQL("delete from "+ ConstantsCard.BC_TABLE_NAME);
db.execSQL("TRUNCATE table " + ConstantsCard.BC_TABLE_NAME);
db.close();
}
public void delete(String BCid)
{
String[] args={BCid};
getWritableDatabase().delete("texts", "_ID=?", args);
}
public ArrayList<CardModel> getAllBCdata(String orderByBC) {
ArrayList<CardModel> ArrayListCard = new ArrayList<>();
String selectQuery = "SELECT * FROM " + ConstantsCard.BC_TABLE_NAME + " ORDER BY " + orderByBC;
SQLiteDatabase BCdb = this.getWritableDatabase();
Cursor CardCursor = BCdb.rawQuery(selectQuery, null);
if (CardCursor.moveToNext()) {
do {
CardModel cardModel = new CardModel(
""+CardCursor.getInt(CardCursor.getColumnIndex(ConstantsCard.BC_C_ID)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_IMAGE)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_NUMBER)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_CVV)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_EXPIRY)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_ADD_TIMESTAMP)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_UPDATE_TIMESTAMP))
);
ArrayListCard.add(cardModel);
} while (CardCursor.moveToNext());
}
BCdb.close();
return ArrayListCard;
}
}
HERE IS MY ADAPTER CLASS
package com.ixidev.simplenotepad;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.arch.core.executor.TaskExecutor;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.Holder> {
private Context CardContext;
private ArrayList<CardModel> CardArrayList;
CardsDatabaseHelper cardsDatabaseHelper;
public CardAdapter(Context cardContext, ArrayList<CardModel> cardArrayList) {
CardContext = cardContext;
CardArrayList = cardArrayList;
cardsDatabaseHelper = new CardsDatabaseHelper(CardContext);
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View viewBC = LayoutInflater.from(CardContext).inflate(R.layout.bc_row, parent, false);
return new Holder(viewBC);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
CardModel cardModel = CardArrayList.get(position);
final String BCid = cardModel.getBCid();
final String BCimage = cardModel.getImageBC();
final String BCnumber = cardModel.getNumber();
final String BCcvv = cardModel.getCvv();
final String BCexpiry = cardModel.getExpiryBC();
final String addTimeStampBC = cardModel.getAddTimeStampBC();
final String updateTimeStampBC = cardModel.getUpdateTimeStampBC();
holder.profileIvBC.setImageURI(Uri.parse(BCimage));
holder.number.setText(BCnumber);
holder.cvv.setText(BCcvv);
holder.expiryBC.setText(BCexpiry);
holder.editButtonBC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editDialog(
""+position,
""+BCid,
""+BCnumber,
""+BCcvv,
""+BCexpiry,
""+BCimage,
""+addTimeStampBC,
""+updateTimeStampBC
);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
deleteDialog(
""+BCid
);
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CardContext, "Clicked", Toast.LENGTH_SHORT).show();
cardsDatabaseHelper.testDelete();
cardsDatabaseHelper.delete(BCid);
}
});
}
private void deleteDialog(final String BCid) {
AlertDialog.Builder builderBC = new AlertDialog.Builder(CardContext);
builderBC.setTitle("Delete?");
builderBC.setMessage("Are you sure you want to delete this document?");
builderBC.setCancelable(false);
builderBC.setIcon(R.drawable.ic_action_delete);
builderBC.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
cardsDatabaseHelper.deleteInfo(BCid);
((ProgramActivity)CardContext).onResume();
Toast.makeText(CardContext, "Successfully deleted!", Toast.LENGTH_SHORT).show();
}
});
builderBC.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderBC.create().show();
}
private void editDialog(String position, String BCid, String BCnumber, String BCcvv, String BCexpiry, String BCimage, String addTimeStampBC, String updateTimeStampBC) {
AlertDialog.Builder BCbuilder = new AlertDialog.Builder(CardContext);
BCbuilder.setTitle("Edit?");
BCbuilder.setMessage("Are you sure you want to edit this Bank Card?");
BCbuilder.setCancelable(false);
BCbuilder.setIcon(R.drawable.ic_action_edit);
BCbuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(CardContext, EditBankCardActivity.class);
intent.putExtra("BCID", BCid);
intent.putExtra("NUMBER", BCnumber);
intent.putExtra("CVV", BCcvv);
intent.putExtra("EXPIRYBC", BCexpiry);
intent.putExtra("IMAGE", BCimage);
intent.putExtra("BC_ADD_TIMESTAMP", addTimeStampBC);
intent.putExtra("BC_UPDATE_TIMESTAMP", updateTimeStampBC);
intent.putExtra("BCeditMode", true);
CardContext.startActivity(intent);
}
});
BCbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
BCbuilder.create().show();
}
#Override
public int getItemCount() {
return CardArrayList.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView profileIvBC;
TextView number, cvv, expiryBC;
ImageButton editButtonBC;
public Holder(#NonNull View itemView) {
super(itemView);
profileIvBC = itemView.findViewById(R.id.profileIvBC);
number = itemView.findViewById(R.id.number);
cvv = itemView.findViewById(R.id.cvv);
expiryBC = itemView.findViewById(R.id.expiry);
editButtonBC = itemView.findViewById(R.id.editBtnBC);
}
}
}
HERE IS MY MODEL CLASS
package com.ixidev.simplenotepad;
public class CardModel {
String BCid, imageBC, number, cvv, expiryBC, addTimeStampBC, updateTimeStampBC;
public CardModel(String BCid, String imageBC, String number, String cvv, String expiryBC, String addTimeStampBC, String updateTimeStampBC) {
this.BCid = BCid;
this.imageBC = imageBC;
this.number = number;
this.cvv = cvv;
this.expiryBC = expiryBC;
this.addTimeStampBC = addTimeStampBC;
this.updateTimeStampBC = updateTimeStampBC;
}
public String getBCid() {
return BCid;
}
public void setBCid(String BCid) {
this.BCid = BCid;
}
public String getImageBC() {
return imageBC;
}
public void setImageBC(String imageBC) {
this.imageBC = imageBC;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getExpiryBC() {
return expiryBC;
}
public void setExpiryBC(String expiryBC) {
this.expiryBC = expiryBC;
}
public String getAddTimeStampBC() {
return addTimeStampBC;
}
public void setAddTimeStampBC(String addTimeStampBC) {
this.addTimeStampBC = addTimeStampBC;
}
public String getUpdateTimeStampBC() {
return updateTimeStampBC;
}
public void setUpdateTimeStampBC(String updateTimeStampBC) {
this.updateTimeStampBC = updateTimeStampBC;
}
}
And here is my CONSTANTS class
package com.ixidev.simplenotepad;
public class ConstantsCard {
public static final String BC_DB_NAME = "MY_BANK_CARDS";
public static final int BC_DB_VERSION = 1;
public static final String BC_TABLE_NAME = "MY_BANK_CARDS_TABLE";
public static final String BC_C_ID = "BC_ID";
public static final String BC_C_NUMBER = "BC_NUMBER";
public static final String BC_C_CVV = "BC_CVV";
public static final String BC_C_EXPIRY = "BC_EXPIRY";
public static final String BC_C_IMAGE = "BC_IMAGE";
public static final String BC_C_ADD_TIMESTAMP = "BC_ADD_TIMESTAMP";
public static final String BC_C_UPDATE_TIMESTAMP = "BC_UPDATE_TIMESTAMP";
public static final String BC_CREATE_TABLE = "CREATE TABLE " + BC_TABLE_NAME + "("
+ BC_C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BC_C_NUMBER + " TEXT,"
+ BC_C_CVV + " TEXT,"
+ BC_C_EXPIRY + " TEXT,"
+ BC_C_IMAGE + " TEXT,"
+ BC_C_ADD_TIMESTAMP + " TEXT,"
+ BC_C_UPDATE_TIMESTAMP + " TEXT"
+ ");";
}
Could someone help me with a query I'm trying? I have put some test data to Firestore to test my app. I want to query the data of the current users signed in and then get only the data that was saved to the database today. I want to get the highest and lowest temperature of the current day and also the same for a pulse. At the moment my code gets all of those, but when I try to compare the current date to the one in the database, so I can retrieve only the data from today, I only get the newest one. So example if I have to documents from to day, I only get the latest one.
My code looks like this at the moment:
package com.example.wht;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.wht.model.WhtItem;
import com.example.wht.ui.WhtRecyclerAdapter;
import com.example.wht.util.WhtApi;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MainPageActivity extends AppCompatActivity implements View.OnClickListener {
private TextView highestPulse, lowestPulse;
private TextView highestTemp, lowestTemp;
private TextView time;
private ImageButton tempButton;
private CardView pulseCardView, tempCardView;
private Toolbar toolbar;
private List<Integer> tempItemList;
private List<Integer> pulseItemList;
private List<WhtItem> itemList;
private String htemp;
private int minTemp ;
private String ltemp;
private int maxPulse;
private String hpulse;
private int minPulse;
private String lpulse;
private int maxTemp;
private String dateAdded;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
//Firestore conneection
private CollectionReference collectionReference = db.collection("whtitem");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
highestPulse = findViewById(R.id.highest_pulse_mainpage);
lowestPulse = findViewById(R.id.lowest_pulse_mainpage);
highestTemp = findViewById(R.id.highest_temperature_text);
lowestTemp = findViewById(R.id.lowest_temp_text);
time = findViewById(R.id.time_mainpage); //TARKISTA
tempButton = findViewById(R.id.imageButton);
pulseCardView = findViewById(R.id.pulse_cardView);
tempCardView = findViewById(R.id.body_heat_cardview);
tempItemList = new ArrayList<>();
pulseItemList = new ArrayList<>();
itemList = new ArrayList<>();
tempButton.setOnClickListener(this);
pulseCardView.setOnClickListener(this);
tempCardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imageButton:
//TODO go to temp_history_activity
break;
case R.id.pulse_cardView:
//TODO go to pulse_history_activity
break;
case R.id.body_heat_cardview:
startActivity(new Intent(MainPageActivity.this, TimeTempActivity.class));
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.profile:
//add take users to add journal
if (user != null && firebaseAuth!=null){
startActivity(new Intent(MainPageActivity.this, ProfileActivity.class));
//finish();
}
break;
case R.id.temp_history:
/*if (user != null && firebaseAuth!=null) {
startActivity(new Intent(MainPageActivity.this, TempHistoryActivity.class));
//finish();
}
break;*/
case R.id.pulse_history:
/*if (user != null && firebaseAuth!=null) {
startActivity(new Intent(MainPageActivity.this, PulseHistoryActivity.class));
//finish();
}
break;*/
case R.id.time_in_temp_history:
if (user != null && firebaseAuth!=null) {
startActivity(new Intent(MainPageActivity.this, TimeTempActivity.class));
//finish();
}
break;
case R.id.action_signout:
//signout
if (user != null && firebaseAuth!=null){
firebaseAuth.signOut();
startActivity(new Intent(MainPageActivity.this, MainActivity.class));
//finish();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
final Timestamp ts = new Timestamp(System.currentTimeMillis());
final Date cDate = new Date(ts.getTime());
final String currentDate = DateFormat.format("dd/MM/yyyy", cDate).toString();
collectionReference.whereEqualTo("userId", WhtApi.getInstance()
.getUserId())
.whereEqualTo("date", cDate)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()){
for (QueryDocumentSnapshot whtitems : queryDocumentSnapshots) {
WhtItem whtItem = whtitems.toObject(WhtItem.class);
itemList.add(whtItem);
Date dAdded = whtItem.getDate();
dateAdded = DateFormat.format("dd/MM/yyyy", dAdded).toString();
tempItemList.add(whtItem.getTemperature());
pulseItemList.add(whtItem.getPulse());
maxTemp = Collections.max(tempItemList);
htemp = "Korkein: " + maxTemp + " astetta";
minTemp = Collections.min(tempItemList);
ltemp = "Matalin: " + minTemp + " astetta";
maxPulse = Collections.max(pulseItemList);
hpulse = "Korkein: " + maxPulse + " bpm";
minPulse = Collections.min(pulseItemList);
lpulse = "Matalin: " + minPulse + " bpm";
}
if (currentDate.equals(dateAdded)) {
highestTemp.setText(htemp);
lowestTemp.setText(ltemp);
highestPulse.setText(hpulse);
lowestPulse.setText(lpulse);
}else {
Toast.makeText(MainPageActivity.this, "Ei dataa tältä päivältä", Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(MainPageActivity.this, "Virhe dataa haettaessa", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainPageActivity.this, "Ei dataa näytettäväksi", Toast.LENGTH_SHORT).show();
}
});
}
}
And here is my POJO:
package com.example.wht.model;
import com.google.firebase.firestore.ServerTimestamp;
import java.util.Date;
public class WhtItem {
private String nameUser, userId;
private String password;
private int temperature, pulse;
private #ServerTimestamp java.util.Date date;
private int duration;
public WhtItem() {
}
public WhtItem(String nameUser, String userId, String password, int temperature, int pulse, java.util.Date date, int duration) {
this.nameUser = nameUser;
this.userId = userId;
this.password = password;
this.temperature = temperature;
this.pulse = pulse;
this.date = date;
this.duration = duration;
}
public String getNameUser() {
return nameUser;
}
public void setNameUser(String nameUser) {
this.nameUser = nameUser;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public int getPulse() {
return pulse;
}
public void setPulse(int pulse) {
this.pulse = pulse;
}
public java.util.Date getDate() {
return date;
}
public void setDate(Date dateAdded) {
this.date = dateAdded;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}
My Firestore documents are in the following form:
Firestore database
Can someone tell where am I going wrong with this? I tried to google and search but no luck.
the query for filter document data of FirebaseStore :
Query query = FirebaseFirestore.getInstance().collection(TABLE_KEY_COMMENT)
.whereEqualTo("disucssionId",discussionID)
.orderBy("date", Query.Direction.DESCENDING);
try to use like this query and pass correct param
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();
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"};