I managed to create the account and authentication when I click on the register button I redirect to login page after that I create a new activity (rdv_detail) which contains a spinner which recovers the values entered names. the problem it is when I create a new account I click on register normally I have to redirect to login page but I redirect to the page (rdv_detail) the spinner managed to recover the value entered at the beginning in the edit text field but when I reconnect by the same user the spinner is empty and I want the spinner to keep all the values entered (name) at the start by the form is there anyone who can help me because I don't know exactly where the error is but I don't have the result I want (account.java -> login.java-> click on a button-> rdv_detail.java (which contains the spinner)
account.java
public class account extends AppCompatActivity {
private EditText nameDoctor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
registerButton = findViewById(R.id.btt_register);
nameDoctor = findViewById(R.id.name_doc);
}
//code
private void registerDoctor() {
String name = nameDoctor.getText().toString();
//code
final Doctor doctor = new Doctor(name, city, adress, email, tel, speciality, code);
mAuth.createUserWithEmailAndPassword(doctor.email, password).addOnCompleteListener(new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isComplete()) {
Toast.makeText(account.this, "Error ...: " +
task.getException().getMessage(), Toast.LENGTH_LONG).show();
Log.e("doctor", "Error....: " +
task.getException().getMessage());
} else {
Log.e("Adddoctor", "user account created");
new Thread(new Runnable() {
#Override
public void run() {
SaveDoctorData(doctor);
Intent sendNameIntent = new Intent(account.this, rdv_detail.class);
String name=nameDoctor.getText().toString();
sendNameIntent.putExtra("nameDoctor",name);
startActivity(sendNameIntent);
}
}).start();
}
}
});
}
private void SaveDoctorData(Doctor doctor){
db.collection("doctor").add(doctor).addOnCompleteListener(new
OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (!task.isComplete()) {
Toast.makeText(Compte.this, "Error ...: " +
task.getException().getMessage(), Toast.LENGTH_LONG).show();
Log.e("doctor", "Error: " +
task.getException().getMessage());
}else{
Toast.makeText(account.this, " user account created",
Toast.LENGTH_LONG).show();
redirectToLoginPage();
}
}
});
}
private void redirectToLoginPage() {
Intent intent = new Intent(this, login.class);
startActivity(intent);
}
public void cancel(View view) {
redirectToLoginPage();
}
}
rdv_detail.java
//code
public class rdv_detail extends AppCompatActivity implements
DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener,View.OnClickListener{
//code
Spinner spinner_doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rdv_detail);
spinner_doc =findViewById(R.id.spinner_doctor);
String nameExtra = getIntent().getStringExtra("nameDoctor");
if(nameExtra !=null)
{
ArrayList<String> spinnerData = new ArrayList<String>();
spinnerData.add(nameExtra);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(rdv_detail.this,
android.R.layout.simple_spinner_item, spinnerData);
spinner_doc.setAdapter(arrayAdapter);
}
}
}
Related
I created a Login android app, connected to firebase Real time database and works perfectly (Users has been created successfully).
From LoginActivity, users must go to HomeActivity, which has a navigation drawer menu, but does not work.
I tried to change the activity destination, so after login, I tried to open a TrialActivity and works perfectly.
What could be the problem?
LoginActivity
public class LoginActivity extends AppCompatActivity {
private EditText InputNumber, InputPaswd;
private Button LoginBtn;
private ProgressDialog loadingBar;
private String parentDBName = "Users";
private TextView AdminLink, NotAdminLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
InputNumber = (EditText) findViewById(R.id.login_phone_numb_input);
InputPaswd = (EditText) findViewById(R.id.login_Password);
LoginBtn = (Button) findViewById(R.id.login_btn);
loadingBar = new ProgressDialog(this);
AdminLink = (TextView) findViewById(R.id.admin_panel_link);
NotAdminLink = (TextView) findViewById(R.id.not_admin_panel_link);
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginUser();
}
});
AdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginBtn.setText("Login Admin");
AdminLink.setVisibility(View.INVISIBLE);
NotAdminLink.setVisibility(View.VISIBLE);
parentDBName="Admins";
}
});
NotAdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginBtn.setText("Login");
AdminLink.setVisibility(View.VISIBLE);
NotAdminLink.setVisibility(View.INVISIBLE);
parentDBName="Users";
}
});
}
private void LoginUser() {
String phone = InputNumber.getText().toString();
String password = InputPaswd.getText().toString();
// InputNumber.setText("3791881336");
//InputPaswd.setText("1234");
if (TextUtils.isEmpty(phone)) {
Toast.makeText(this,"Please enter your number",Toast.LENGTH_SHORT);
}
else if (TextUtils.isEmpty(password)){
Toast.makeText(this,"Please enter your password",Toast.LENGTH_SHORT);
}
else {
loadingBar.setTitle("Log in");
loadingBar.setMessage("Please wait, loading");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount( phone, password);
}
}
private void AllowAccessToAccount(String phone, String password) {
final DatabaseReference RootRef;
DatabaseReference reference = FirebaseDatabase.getInstance( "https://ecommerce-bdb44-default-rtdb.europe-west1.firebasedatabase.app").getReference();
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(parentDBName).child(phone).exists()){
Users userData = snapshot.child(parentDBName).child(phone).getValue(Users.class);
if (userData.getPhone().equals(phone)){
if (userData.getPassword().equals(password)){
if (parentDBName.equals("Admins")){
Toast.makeText(LoginActivity.this, "Logged in Successfully", Toast.LENGTH_SHORT);
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, AdminActivity.class);
startActivity(intent);
}
else if
(parentDBName.equals("Users")){
Toast.makeText(LoginActivity.this, "Logged in Successfully", Toast.LENGTH_SHORT);
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
}
}
}
}
else {
Toast.makeText(LoginActivity.this, "Account with" + phone + "do not exist",Toast.LENGTH_SHORT);
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "You need to create an account",Toast.LENGTH_SHORT);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this is my code qr code scanner
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
onBackPressed();
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "DATA INSERTED", Toast.LENGTH_SHORT).show();
}
}
});
}
the successful task is working
In your code I see you are using wrong onBackPressed();
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "DATA INSERTED", Toast.LENGTH_SHORT).show();
} else {
// Error handling here
Toast.makeText(getApplicationContext(), "DATA INSERT ERROR", Toast.LENGTH_SHORT).show();
}
onBackPressed(); //This will exit the screen, you should consider whether to use it
}
});
UPDATE:
I have updated the code, the best way to display toast for both Fragment and Activity. And I have added Log.d to check where the program runs and if it's working properly
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class BaseFragment extends Fragment {
private static final int MSG_SHOW_TOAST = 1;
void displayMessage(String message, boolean isLengthLong) {
requireActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
int longShow = isLengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
Toast.makeText(requireActivity(), message, longShow).show();
}
});
}
}
public class Demo extends BaseFragment {
private String TAG = getClass().getSimpleName();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
displayMessage("Ahihi", false);
}
public void yourMethod() {
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is " + task.isSuccessful());
if (task.isSuccessful()) {
displayMessage("DATA INSERTED", true);
} else {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is ERROR ");
displayMessage("DATA INSERT ERROR", true);
}
onBackPressed(); //This will exit the screen, you should consider whether to use it
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
//========================================= below code is for activity
public class BaseActivity extends AppCompatActivity {
void displayMessage(String message, boolean isLengthLong) {
runOnUiThread(new Runnable() {
#Override
public void run() {
int longShow = isLengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
Toast.makeText(getApplicationContext(), message, longShow).show();
}
});
}
}
public class Demo extends BaseActivity {
private String TAG = getClass().getSimpleName();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
displayMessage("Ahihi", false);
}
public void yourMethod() {
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is " + task.isSuccessful());
if (task.isSuccessful()) {
displayMessage("DATA INSERTED", true);
} else {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is ERROR ");
displayMessage("DATA INSERT ERROR", true);
}
onBackPressed(); //This will exit the screen, you should consider whether to use it
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I'm trying to change the user authentication email.
CustomDialogBox
public class ConfirmPasswordDialogBox extends Dialog implements android.view.View.OnClickListener {
private ImageButton cancel, confirm;
private EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
cancel.setOnClickListener(this);
confirm.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
Activity where null pointer exception is thrown
public class EditProfileActivity extends AppCompatActivity {
private EditText descript, firstName, lastName, email;
private Button updatebtn;
private ImageButton back;
private Context mcontext;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseMethods firebaseMethods;
private String userID;
private ProgressDialog pb;
private UserInformation userInformationx;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mcontext = EditProfileActivity.this;
descript = findViewById(R.id.descript);
firstName = findViewById(R.id.firstName);
email = findViewById(R.id.email);
lastName = findViewById(R.id.lastName);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
firebaseMethods = new FirebaseMethods(mcontext);
pb = new ProgressDialog(this);
pb.setMessage("Updaing Profile ...");
pb.setCancelable(true);
pb.setCanceledOnTouchOutside(false);
init();
setupFirebaseAuth();
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}
The EditText widget is already intialized, still email.getText.toString() is throwing null. I'm just passing the string value to a method, which is called when a button is clicked in Dialog box.
I've tried and debug all possible ways I know.
I'm just trying to update the user authentication email in firebase.
The EditText widget is already intialized, still email.getText.toString() is throwing null.
Actually the EditText email is only intialized in the onCreate of the activity, this means that it's only initialized when you open the activity using startActivity(intent).
Edit - Since you're calling the ConfirmPasswordDialogBox from the EditProfileActivity, something along the following lines should work.
public class ConfirmPasswordDialogBox extends Dialog {
private ImageButton cancel, confirm;
public EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
//cancel.setOnClickListener(this);
//confirm.setOnClickListener(this);
}
public void setOnClickListeners(View.OnClickListener listener) {
cancel.setOnClickListener(listener);
confirm.setOnClickListener(listener);
}
/*
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
*/
}
public class EditProfileActivity extends AppCompatActivity implements android.view.View.OnClickListener {
//Other code
//At some point in some method you'll create the dialog
//Say you create the dialog object here. Now set this activity as the onClickListener
dialog.setOnClickListeners(this);
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = dialog.confirm_password.getText().toString();
if(!mpassword.equals("")){
//Now you can directly call the method
updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}
I am having an issue with retrieving data from my Firebase database. Please excuse my lack of technial speech as this is not my strong point.
My application is to create a Vehicle listing which posts to a page with a RecyclerView. A new vehicle is added via the "NewVehicle.class" and saved to Firebase underneath an automatically generated node. The user can select a vehicle from the "VehicleList.class" this re-directs them to the "PasswordProtected.class". The user needs to enter a password to view the data relating to the vehicle. Both the vehicle and the "PasswordProtected.class" are linked, or in other words the code knows which vehicle to look at in the database. The user is redirected to the "DataDisplay.class" where they can choose from the graphs they want to view. The issue i am having now is retrieving the specific "VehiclesData" from one vehicle and displaying them in the graph. i have also added an image of what my database looks like in firebase.
NewVehicle.class
public class NewVehicle extends AppCompatActivity
{
//XML variables
private ImageView newVehicleImage;
private EditText vehicleMake, vehicleModel, vehicleReg, password, con_password, engineSize;
private ProgressDialog progress;
private Uri vehicleImage = null;
private StorageReference storageRef;
private DatabaseReference databaseRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_vehicle);
storageRef = FirebaseStorage.getInstance().getReference();
databaseRef = FirebaseDatabase.getInstance().getReference().child("Vehicles");
newVehicleImage = findViewById(R.id.new_vehicle_image);
vehicleMake = findViewById(R.id.new_vehicle_make);
vehicleModel = findViewById(R.id.new_vehicle_model);
vehicleReg = findViewById(R.id.new_vehicle_reg);
engineSize = findViewById(R.id.new_vehicle_engine);
Button vehicleAdd = findViewById(R.id.save_btn);
password = findViewById(R.id.password);
con_password = findViewById(R.id.con_password);
progress = new ProgressDialog(this);
newVehicleImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setMinCropResultSize(512, 512)
.setAspectRatio(1, 1)
.start(NewVehicle.this);
}
});
//When user selects the 'Add' button
vehicleAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
StartPosting();
}
});
}//End onCreate()
private void StartPosting()
{
progress.setMessage("Posting to Vehicle list");
//The make, model and reg is saved to Strings
final String make = vehicleMake.getText().toString().trim();
final String model = vehicleModel.getText().toString().trim();
final String reg = vehicleReg.getText().toString().trim();
final String pass = password.getText().toString().trim();
final String engine = engineSize.getText().toString().trim();
final String con_pass = con_password.getText().toString().trim();
//If the password length is less than six
if(con_pass.length()<6)
{
con_password.setError(getText(R.string.mini_length));
con_password.requestFocus();
}
if(pass.length()<6)
{
password.setError(getText(R.string.mini_length));
password.requestFocus();
}
if(!TextUtils.isEmpty(make) && !TextUtils.isEmpty(model) && !TextUtils.isEmpty(reg) &&
!TextUtils.isEmpty(engine) && !TextUtils.isEmpty(pass) &&
!TextUtils.isEmpty(con_pass) && vehicleImage != null)
{
if (pass.equals(con_pass))
{
progress.show();
StorageReference filePath = storageRef.child("vehicle_images").child(vehicleImage.getLastPathSegment());
filePath.putFile(vehicleImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newpost = databaseRef.push();
newpost.child("Make").setValue(make);
newpost.child("Model").setValue(model);
newpost.child("Reg").setValue(reg);
newpost.child("Password").setValue(pass);
newpost.child("Engine").setValue(engine);
newpost.child("Confirmed_Password").setValue(con_pass);
newpost.child("Image").setValue(Objects.requireNonNull(downloadUrl).toString());
progress.dismiss();
startActivity(new Intent(NewVehicle.this, VehicleList.class));
}
});
}
if (!pass.equals(con_pass))
{
Toast.makeText(getApplicationContext(), "Passwords must match", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Fields can not be left empty", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
vehicleImage = result.getUri();
newVehicleImage.setImageURI(vehicleImage);
}
//If the resultCode has an error
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
Toast.makeText(NewVehicle.this, "Application Error", Toast.LENGTH_LONG).show();
}
}
}
}//End NewVehicle()
VehicleList.class
public class VehicleList extends AppCompatActivity
{
//Declaring RecyclerView
private RecyclerView vehicleList;
//Declaring DatabaseReference to FireBase
private DatabaseReference databaseRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets the layout according to the XML file
setContentView(R.layout.activity_vehicle_list);
//Linking to the FireBase Real-time Database
databaseRef = FirebaseDatabase.getInstance().getReference().child("Vehicles");
//XML variable
vehicleList = findViewById(R.id.vehicle_list_view);
vehicleList.setHasFixedSize(true);
vehicleList.setLayoutManager(new LinearLayoutManager(this));
FloatingActionButton addVehicleBtn = findViewById(R.id.add_vehicle_btn);
//If the user taps the addPostBtn
addVehicleBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//They will be redirected to the 'NewPost' class where they can add a new post
Intent intent = new Intent(VehicleList.this, NewVehicle.class);
startActivity(intent);
}//End onClick()
});//End addVehicleBtn()
}//End onCreate()
#Override
protected void onStart()
{
super.onStart();
//Recycler Adapter for Vehicles
FirebaseRecyclerAdapter<VehicleLog, VehicleViewHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<VehicleLog, VehicleViewHolder>(
VehicleLog.class,
R.layout.vehicle_itemlist,
VehicleViewHolder.class,
databaseRef
){
#Override
protected void populateViewHolder(VehicleViewHolder viewHolder, VehicleLog model, int position)
{
//Get the unique identifier for each record in the database
final String vehicle_key = getRef(position).getKey();
//Gathers the data
viewHolder.setMakeText(model.getMake());
viewHolder.setModelText(model.getModel());
viewHolder.setRegText(model.getReg());
viewHolder.setImage(getApplicationContext(), model.getImage());
//If a record is tapped on
viewHolder.mView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Users redirected to the next screen
Intent intent = new Intent(VehicleList.this, PasswordProtected.class);
intent.putExtra("Vehicle_id", vehicle_key);
startActivity(intent);
}//End onClick()
});//End OnClickListener()
}//End populateViewHolder()
};//End FirebaseRecyclerAdapter()
vehicleList.setAdapter(firebaseRecyclerAdapter);
}//End onStart()
public static class VehicleViewHolder extends RecyclerView.ViewHolder
{
View mView;
public VehicleViewHolder(View itemView)
{
super(itemView);
mView = itemView;
}//End VehicleViewHolder()
//Sets the vehicles make on screen
public void setMakeText(String make)
{
TextView vehicle_make = mView.findViewById(R.id.vehicle_make);
vehicle_make.setText(make);
}//End setMakeText()
//Sets the vehicles model on screen
public void setModelText(String model)
{
TextView vehicle_model = mView.findViewById(R.id.vehicle_model);
vehicle_model.setText(model);
}//End setModelText()
//Sets the vehicles reg on screen
public void setRegText(String reg)
{
TextView vehicle_reg = mView.findViewById(R.id.vehicle_reg);
vehicle_reg.setText(reg);
}//End setRegText()
//Sets the vehicles image on screen using Glide
public void setImage(Context ctx, String Image)
{
ImageView vehicle_image = mView.findViewById(R.id.post_image);
Glide.with(ctx).load(Image).into(vehicle_image);
}//End setImage()
}//End VehicleViewHolder()
}
PasswordProtected.class
public class PasswordProtected extends AppCompatActivity
{
//Declaring XML variables
private ImageView imageView;
private TextView vehicle_make, vehicle_model;
private EditText ent_pass;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password_protected);
vehicle_model = findViewById(R.id.model);
vehicle_make = findViewById(R.id.make);
imageView = findViewById(R.id.image);
Button cont = findViewById(R.id.cont);
ent_pass = findViewById(R.id.editTextPassword);
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference().child("Vehicles");
//Gathers the unique key of each record in the database
String vehicle_key =
Objects.requireNonNull(getIntent().getExtras()).getString("Vehicle_id");
databaseRef.child(Objects.requireNonNull(vehicle_key))
.addValueEventListener(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
String model = (String) dataSnapshot.child("Model").getValue();
String make = (String) dataSnapshot.child("Make").getValue();
String image = (String) dataSnapshot.child("Image").getValue();
vehicle_model.setText(model);
vehicle_make.setText(make);
Glide.with(PasswordProtected.this).load(image).into(imageView);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
Toast.makeText(PasswordProtected.this, "Database Error!", Toast.LENGTH_LONG).show();
}
});
cont.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
final String enter_pass = ent_pass.getText().toString().trim();
final DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference().child("Vehicles");
String vehicle_key = Objects.requireNonNull(getIntent().getExtras()).getString("Vehicle_id");
databaseRef.child(Objects.requireNonNull(vehicle_key)).addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot)
{
String pass = (String) dataSnapshot.child("Password").getValue();
Log.v("Firebase:", pass);
if(Objects.equals(pass, enter_pass))
{
Intent intent = new Intent(PasswordProtected.this, DataDisplay.class);
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(),"PASSWORD DONT MATCH", Toast.LENGTH_LONG).show();
}//End else()
}//End onDataChange()
public void onCancelled(DatabaseError databaseError)
{
Toast.makeText(PasswordProtected.this, "Database Error!", Toast.LENGTH_LONG).show();
}
});
if(enter_pass.isEmpty())
{
ent_pass.setError(getText(R.string.pass_empt));
ent_pass.requestFocus();
}
if(enter_pass.length()<6)
{
ent_pass.setError(getText(R.string.mini_length));
ent_pass.requestFocus();
}
}
});
}
}
DisplayData.class
public class DataDisplay extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_display);
//XML variables
Button mass_air = findViewById(R.id.mass_air);
Button engine_load = findViewById(R.id.engine_throttle);
Button engine_RPM = findViewById(R.id.RPM);
Button engine_temps = findViewById(R.id.engine_temps);
mass_air.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(DataDisplay.this, GraphEngineAirflow.class);
startActivity(intent);
}
});
engine_temps.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(DataDisplay.this, GraphTempSpecs.class);
startActivity(intent);
}
});
engine_load.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(DataDisplay.this, GraphEngineSpecs.class);
startActivity(intent);
}
});
engine_RPM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DataDisplay.this, GraphEngineRPM.class);
startActivity(intent);
}
});
}
}
GraphEngineAirflow.class
public class GraphEngineAirflow extends Activity implements
OnChartGestureListener, OnChartValueSelectedListener
{
private static final String TAG = "GraphEngineAirflow";
private LineChart chart;
//Array to hold Mass Airflow data from Firebase
ArrayList<Entry> engineAirflow = new ArrayList<>();
//Variables
LineDataSet set1;
LineData data;
protected void onCreate(Bundle savedInstanceState) {
/*This creates an Alert dialog on this screen, it also sets it so the user can cancel the message
for the Mass Airflow rate information*/
AlertDialog.Builder builder = new AlertDialog.Builder(GraphEngineAirflow.this);
builder.setCancelable(true);
//Setting the title and message from the string.xml
builder.setTitle(GraphEngineAirflow.this.getString(R.string.engine_airflow_title));
builder.setMessage(GraphEngineAirflow.this.getString(R.string.engine_airflow_def));
//When the user selects the Cancel button the page will redirect back to the VehicleSpec page
builder.setNegativeButton(GraphEngineAirflow.this.getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
Intent intent = new Intent(GraphEngineAirflow.this, DataDisplay.class);
startActivity(intent);
}//End onClick()
});//End setNegativeButton()
builder.setPositiveButton(GraphEngineAirflow.this.getString(R.string.Ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
}//End onClick()
});//End setPositiveButton()
builder.show();
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Sets the layout according to the XML file
setContentView(R.layout.activity_graph_engine_airflow);
//XML reference
chart = findViewById(R.id.linechart);
//Listens for on chart taps
chart.setOnChartGestureListener(GraphEngineAirflow.this);
chart.setOnChartValueSelectedListener(GraphEngineAirflow.this);
//Enable touch gestures
chart.setTouchEnabled(true);
//Enable scaling and dragging
chart.setDragEnabled(true);
chart.setScaleEnabled(false);
chart.setDrawGridBackground(false);
//Enable pinch zoom
chart.setPinchZoom(true);
//Background color
chart.setBackgroundColor(Color.LTGRAY);
//Setting YAxis
YAxis left = chart.getAxisLeft();
left.setAxisMinimum(0f);
left.setAxisMaximum(50f);
left.setTextSize(13f);
left.enableGridDashedLine(10f, 10f, 0f);
YAxis left2 = chart.getAxisRight();
left2.setEnabled(false);
chart.getAxisRight().setEnabled(false);
//Value string
String[] vals = new String[] {"0s", "1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "11s"};
//Legend object
Legend i = chart.getLegend();
//Customise legend
i.setTextSize(15f);
i.setForm(Legend.LegendForm.CIRCLE);
i.setTextColor(Color.BLACK);
//Setting XAis
XAxis x = chart.getXAxis();
x.setTextSize(13f);
x.setValueFormatter(new MyXAxisValueFormatter(vals));
x.setGranularity(1);
x.setPosition(XAxis.XAxisPosition.BOTTOM);
//Adding value to array as system will crash without
engineAirflow.add(new Entry(0, 0));
engineAirflow.add(new Entry(1, 0));
//Setting the line
set1 = new LineDataSet(engineAirflow, "Engine AirFlow ");
set1.setFillAlpha(110);
set1.setColor(Color.RED);
set1.setLineWidth(3f);
set1.setValueTextSize(10f);
set1.setValueTextColor(Color.BLACK);
data = new LineData(set1);
chart.setData(data);
//Calls the downloadDatt()
downloadData();
//Change the chart when a change occurs
chart.notifyDataSetChanged();
//XML button
Button checkD = findViewById(R.id.checkdata);
//If the user taps the button
checkD.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/*This creates an Alert dialog on this screen, it also sets it so the user can cancel the message
for the Mass Airflow rate information retrieved from the database*/
AlertDialog.Builder builder2 = new AlertDialog.Builder(GraphEngineAirflow.this);
builder2.setCancelable(true);
//Setting the title and message from the string.xml
builder2.setTitle(GraphEngineAirflow.this.getString(R.string.IMPORTANT));
builder2.setMessage(GraphEngineAirflow.this.getString(R.string.airflow_info));
//When the user selects the Cancel button the page will redirect back to the VehicleSpec page
builder2.setNegativeButton(GraphEngineAirflow.this.getString(R.string.cancel), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
Intent intent = new Intent(GraphEngineAirflow.this, DataDisplay.class);
startActivity(intent); }//End onClick()
});//End setNegativeButton()
//If the user taps Ok
builder2.setPositiveButton(GraphEngineAirflow.this.getString(R.string.Ok), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}//End onClick()
});//End setPositiveButton()
//Show the Dialogs on screen
builder2.show();
}//End onClick()
});//End OnClickListener()
}//End onCreate
//Downloads Data from FireBase
private void downloadData()
{
//ArrayAdapter
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,R.layout.activity_graph_engine_airflow);
//Connecting into table "VehicleData" on the FireBase database
DatabaseReference database = FirebaseDatabase.getInstance().getReference("Vehicles");
//ChildEventListener allows child events to be listened for
database.addChildEventListener(new ChildEventListener()
{
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey)
{
//Holds the DataSnapshot value of the database as type String
VehicleData vehicleData = dataSnapshot.getValue(VehicleData.class);
//Prints values to console to prove the download is working
System.out.println("getmassAirflowRate: " + Objects.requireNonNull(vehicleData).getMassAirflowRate());
System.out.println("prevChildKey: " + prevChildKey);
System.out.println("data.key" + dataSnapshot.getKey());
//Converting value to integer
setData(Integer.parseInt(dataSnapshot.getKey()), vehicleData);
//Will refresh app when the data changes in the database
arrayAdapter.notifyDataSetChanged();
}//End onChildAdded()
//Will run when data within the database is changed/edited
public void onChildChanged(DataSnapshot dataSnapshot, String s)
{
}//End onChildChanged()
//Will run when data within the database is removed
public void onChildRemoved(DataSnapshot dataSnapshot)
{
}//End onChildRemoved()
//Will run when data within the database is moved to different location
public void onChildMoved(DataSnapshot dataSnapshot, String s)
{
}//End onChildMoved()
//Will run when any sort of error occurs
public void onCancelled(DatabaseError databaseError)
{
}//End onCancelled()
});//End addChildEventListener()
}//End DownloadData()
//Function sets the data on the graph
private void setData(int key, VehicleData vehicleData)
{
//Prints to console first
System.out.println("Using key: " + key);
System.out.println("Setting Mass Intake Airflow Rate: " + vehicleData.getMassAirflowRate());
//Adds new entries to the arrayList and converts the string into a float
engineAirflow.add(new Entry(key + 2, Float.parseFloat(vehicleData.getMassAirflowRate())));
//Change the chart when changes occurs
set1.notifyDataSetChanged();
data.notifyDataChanged();
this.chart.notifyDataSetChanged();
//Redisplay chart
chart.invalidate();
}//End setData()
//Using the String to change the values of the XAis
public class MyXAxisValueFormatter implements IAxisValueFormatter
{
private String[] mVals;
private MyXAxisValueFormatter(String[] vals)
{
this.mVals = vals;
}//End MyXAxisValueFormatter()
#Override
public String getFormattedValue(float value, AxisBase axis)
{
return mVals[(int)value];
}//End getFormattedValue()
}//End MyXAxisValueFormatter()
#Override
//Sends log message if action is performed
public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture)
{
Log.i(TAG, "onChartGestureStart: X:" + me.getX() + "Y:" + me.getY());
}//End()
#Override
//Sends log message if action is performed
public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture)
{
Log.i(TAG, "onChartGestureEnd: " + lastPerformedGesture);
}//End()
#Override
//Sends log message if action is performed
public void onChartLongPressed(MotionEvent me)
{
Log.i(TAG, "onChartLongPressed: ");
}//End()
#Override
//Sends log message if action is performed
public void onChartDoubleTapped(MotionEvent me)
{
Log.i(TAG, "onChartDoubleTapped: ");
}//End()
#Override
//Sends log message if action is performed
public void onChartSingleTapped(MotionEvent me)
{
Log.i(TAG, "onChartSingleTapped: ");
}//End()
#Override
//Sends log message if action is performed
public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY)
{
Log.i(TAG, "onChartFling: veloX: " + velocityX + "veloY" + velocityY);
}//End()
#Override
//Sends log message if action is performed
public void onChartScale(MotionEvent me, float scaleX, float scaleY)
{
Log.i(TAG, "onChartScale: ScaleX: " + scaleX + "ScaleY: " + scaleY);
}//End()
#Override
//Sends log message if action is performed
public void onChartTranslate(MotionEvent me, float dX, float dY)
{
Log.i(TAG, "onChartTranslate: dX" + dX + "dY" + dY);
}//End()
#Override
//Sends log message if action is performed
public void onValueSelected(Entry e, Highlight h) {
Log.i(TAG, "onValueSelected: " + e.toString());
Toast.makeText(this, "onValueSelected: " + e.toString(), Toast.LENGTH_SHORT).show();
}//End()
#Override
//Sends log message if action is performed
public void onNothingSelected() {
Log.i(TAG, "onNothingSelected: ");
}//End()
}//End GraphEngineAirflow()
Change:
DatabaseReference database = FirebaseDatabase.getInstance().getReference("Vehicles").child(vehicle_key).child("Vehicle data");
to,
DatabaseReference database = FirebaseDatabase.getInstance().getReference("Vehicles").child(vehicle_key).child("VehiclesData");
Your code should be fine.
In your First case use reference like this (Not at root directory)
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("VehicleData").child(your id here mean 0 1 2 how you set that simillarly get as it (check if is not null first) );
you are not referencing to the 0 1 2 3 ids thats mean under the root directory of Vehicle Data you get complete child as value which is not a valid class of VehicleData Class. So you need to move to 0 1 2 3 under which you have a complete class of Vehicle Data
My Database in firebase is in this format
I need that if a user login then for that particular UID I need his associated department name. So How to take the department name as a String.I use this code to fetch department name
String u_id=auth.getCurrentUser().getUid();
mdatabase=FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
user=mdatabase.getKey();
By this i don't get the result.Please provide solution
public class LoginPage extends AppCompatActivity {
private Button btnLogin;
private TextView ForgetText;
private EditText userText,PassText;
private String UserEmail,UserPassword;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener mAuthlistener;
private ProgressBar progressBar;
private DatabaseReference mdatabase;
public String departmental;
//private Spinner dropdown;
Variables v=new Variables();
private String username,user;
private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
auth=FirebaseAuth.getInstance();
btnLogin=(Button)findViewById(R.id.btn_login);
ForgetText=(TextView)findViewById(R.id.textView3);
userText=(EditText)findViewById(R.id.email2);
PassText=(EditText)findViewById(R.id.password2);
progressBar=(ProgressBar)findViewById(R.id.progressBar2);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SignIn();
}
});
ForgetText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginPage.this,ForgotPassword.class));
}
});
}
public void SignIn(){
UserEmail=userText.getText().toString().trim();
UserPassword=PassText.getText().toString().trim();
if (UserEmail.isEmpty()){
Toast.makeText(LoginPage.this,"Please Enter the Email
Id",Toast.LENGTH_LONG).show();
}
else if (UserPassword.isEmpty())
{
Toast.makeText(LoginPage.this,"Please enter Valid
Password",Toast.LENGTH_LONG).show();
}
else {
auth.signInWithEmailAndPassword(UserEmail, UserPassword)
.addOnCompleteListener(LoginPage.this, new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If
sign in succeeds
// the auth state listener will be notified and logic
to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// there was an error
Toast.makeText(LoginPage.this,"Error in
logging!!",Toast.LENGTH_LONG).show();
} else
{
if(FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(v.admin))
startActivity(new
Intent(LoginPage.this,AdminUser.class));
else {
String u_id =
auth.getInstance().getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Toast.makeText(LoginPage.this,u_id,Toast.LENGTH_LONG).show();
Toast.makeText(LoginPage.this,departmental,Toast.LENGTH_LONG).show();
/*i = new Intent(LoginPage.this, LoggedIn.class);
i.putExtra("hello_user",department);
startActivity(i);*/
}
Toast.makeText(LoginPage.this, "Logged In", Toast.LENGTH_LONG).show();
}
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
Please use this code:
String u_id = auth.getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
Log.d("TAG", department);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Hope it helps.