Link two tables in firebase using Id in android studio using Java - java

have a problem, I'm working on a university project, I have two tables in firebase, the gallery table that contains the photos of the itinerary and the itinerary table that contains the various itineraries of the users now I have to make sure that the id of the itinerary and the ID of the image so as to have a photo corresponding to each itinerary ì, also created by the same user. I did so:
public void addImageItinerary() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
if (images != null) {
StorageReference itineraryRef = storageReference.child("itinerary_image/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + ".jpg");
itineraryRef.putFile(images).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
itineraryRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String itineraryId = referenceDb.child("Itinerary").push().getKey();
Log.i("itineraryId", itineraryId);
HashMap<String, Object> map = new HashMap<>();
map.put("image", uri.toString());
referenceDb.child("Gallery").child(FirebaseAuth.getInstance().getCurrentUser().getUid()+ "/" + itineraryId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// APRO SCHERMATA MAPPA
// openMapFragment();
Toast.makeText(insertImage_fragment.getActivity(), "ok", Toast.LENGTH_SHORT).show();
} else {
//ERRORE
Toast.makeText(insertImage_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertImage_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else{
Toast.makeText(insertImage_fragment.getActivity(),"Please add image", Toast.LENGTH_SHORT).show();
}
}
enter image description here

Related

Storing personal details of users in Android Studio using Firebase

I'm trying to store details of user like name, email,age etc using Firebase in Android Studio, but it seems only the email and pasword is getting stored. Here's my code, where have I done mistakes? Only the real time database part of Firebase isn't somehow working here. Also, I couldn't post full code here because of "most of it is code add some more details" error.
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Email,Password etc are variables
final String Email= email.getText().toString().trim();
final String Password= password.getText().toString().trim();
final String FullName= fullName.getText().toString().trim();
final String Phone= phone.getText().toString().trim();
final String Gender= gender.getText().toString().trim();
final String Age= age.getText().toString().trim();
if (TextUtils.isEmpty(Email)){
email.setError("Email is required!");
return;
}
else{
loader.setMessage("Registration in process....");
loader.setCanceledOnTouchOutside(false);
loader.show();
mAuth.createUserWithEmailAndPassword(Email,Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
String error =task.getException().toString();
Toast.makeText(SelectRegistrationActivity.this,
"Error occurred:" + error,Toast.LENGTH_SHORT).show();
}
else{
String currentUserId = mAuth.getCurrentUser().getUid();
userDatabaseRef= FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
HashMap userInfo=new HashMap();
userInfo.put("Name",fullName);
userInfo.put("Email",email);
userInfo.put("Age",age);
userInfo.put("Gender",gender);
userInfo.put("Phone",phone);
userInfo.put("Type","Patient");
userDatabaseRef.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(SelectRegistrationActivity.this, "Details set Successful", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(SelectRegistrationActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
finish();
loader.dismiss();
}
});
}
}
});

Why i can't get profile image in 'SettingActivity'?

I try to upload my profile picture, also I get the message of the profile picture is been successfully upload but not able to see it in setting activity
I tried to change the firebase account but not able to work.
when I select photo it takes me to my internal storage, when I select the image it again takes me to choose section of photo uploading ways such as album, google photos internal storage, download etc. when the photo is been uploaded it is been showing in the firebase storage section but it is not showing in the app.
here is the code link
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Check The Details Again.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this, "UserName is Empty.", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)) {
Toast.makeText(this, "Status is Empty.", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).setValue(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updates. Thank You!!!", Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}```
I think you missed to send image from your app.
In UpdateSettings() method you have to send image to firebase.
In below HashMap add image and send to firebase,
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
profileMap.put("image", [YOUR_IMAGE_STRING]);

How to save data to same table from different activities?

Below is the code for both of my activities. By coding like this, the data get stored like this in firebase. This is a snapshot of the stored data:
This is what I get:
What I want is this
I know that this happens because I have two class for the database but I have tried to put in one class but it didn't work. I think it is because of my codes
Below are my codes:
Registration ACtivity`public class RegisterActivityUser extends AppCompatActivity {
ImageView ImgUserPhoto;
static int PReqCode=1;
static int REQUESTCODE=1;
Uri pickedImgUri;
//*************** Firebase User Auth **********//
private EditText userEmail, userPassword, userPassword2, userName, userWeight, userHeight;
private ProgressBar loadingProgress;
private Button regBtn;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
//*************** Login Account User *************//
//Ini Views
userEmail=findViewById(R.id.redMail);
userPassword=findViewById(R.id.regPassword);
userPassword2=findViewById(R.id.regPassword2);
userName=findViewById(R.id.regName);
loadingProgress=findViewById(R.id.progressBar);
regBtn = findViewById(R.id.regBtn);
loadingProgress.setVisibility(View.INVISIBLE);
userWeight=findViewById(R.id.userWeight);
userHeight=findViewById(R.id.userHeight);
mAuth= FirebaseAuth.getInstance();
regBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email=userEmail.getText().toString().trim();
final String password=userPassword.getText().toString();
final String password2=userPassword2.getText().toString();
final String name=userName.getText().toString().trim();
if (email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2)){
//something goes wrong, all fields must be filled
//we need to display error message
showMessage("Please Fill All Details Above");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else {
//everything is okay
//Create New User Account
CreateUserAccount(email,name,password);
}
}
}) ;
ImgUserPhoto = findViewById(R.id.editUserPhoto) ;
ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT>=23){
checkAndRequestForPermission();
}
else {
openGallery();
}
}
});
}
// ************* Create User Account *************//
private void CreateUserAccount(final String email, final String name, String password) {
//this method to create user account with specific email and password;
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//user account created successfully
User user = new User(
name,
email
);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
//acc successfully registered
showMessage("Account Created");
//after we created account, we need to update the user profile picture
updateUserInfo (name ,pickedImgUri,mAuth.getCurrentUser());
}
else{
showMessage("User Already Have Account" + task.getException().getMessage());
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
}
});
}
else {
// user account failed
}
}
});
}
// ************* update user name and photo ************* //
private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser) {
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("users_photos");
final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image Uploaded Successfully
//now we can get our image URL
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//uri contain user image URL
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
// User Profile has updated successfully
showMessage("Register Complete");
updateUI();
}
}
});
}
});
}
});
}
private void updateUI() {
Intent editProfileActivity = new Intent(RegisterActivityUser.this,EditProfileActivity.class);
startActivity(editProfileActivity);
finish();
}
// ************* simple method to toast message *************//
private void showMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
// ************* Upload Picture *************//
private void openGallery() {
//TODO: open gallery intent and wait user to pick an image!
Intent galleryIntent=new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUESTCODE);
}
private void checkAndRequestForPermission() {
if (ContextCompat.checkSelfPermission(RegisterActivityUser.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivityUser.this,Manifest.permission.READ_EXTERNAL_STORAGE)){
Toast.makeText(RegisterActivityUser.this, "Please accept for required Permission",Toast.LENGTH_SHORT).show();
}
else
{
ActivityCompat.requestPermissions(RegisterActivityUser.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
PReqCode);
}
}
else
{
openGallery();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK && requestCode == REQUESTCODE && data !=null){
//the user has success picked an image
//we need to save its as reference to a Uri Variable
pickedImgUri=data.getData();
ImgUserPhoto.setImageURI(pickedImgUri);
}
}
}
`
This one edit profile activity: `private void updateUserInfo(final String weight, final String height, final FirebaseUser currentUser) {
/*Glide.with(this).load(currentUser.getPhotoUrl()).into(userImage);*/
mAuth.updateCurrentUser(currentUser).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
UserProfile user = new UserProfile (
weight,
height
);
FirebaseDatabase.getInstance().getReference("Users Profile")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
//acc successfully registered
showMessage("Account Updated");}
else{
}
}
});
}
}
});
Replace this:
UserProfile user = new UserProfile (
weight,
height
);
FirebaseDatabase.getInstance().getReference("Users Profile")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
With:
Map<String, Object> values = new HashMap<>();
values.put("height", height);
values.put("weight", weight);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.updateChildren(values)
The relevant changes:
Call updateChildren instead of setValue, since setValue replace all data at the location you call it on.
Get a reference to /Users instead of /Users Profile.
Additional hint: consider storing the height and weight as numeric values, instead of strings. Otherwise ordering/filtering on them will become confusing, as Firebase uses lexicographical ordering for strings.

I want to retrieve videos from firebase storage

I am working on simple firebase app in which I upload user info as registration data and uploading videos in storage. Path of videos is also stored in realtime database as nested child of every particular user which is working properly, but I don't know how to retrieve video and set in user profile with other user information. I need code to retrieve video from storage.
case PICK_VIDEO_REQUEST:
if (resultCode == RESULT_OK) {
selectedVideoUri = data.getData();
userUid = FirebaseAuth.getInstance().getCurrentUser().getEmail();
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
filename = data.getData().getLastPathSegment();
tv_file_path.setText(filename);
videoRef = storageRef.child("/videos/" + userUid + "/" + filename);
//TODO: save the video in the db
}
break;
`//Button upload data in firebase
btn_upload_notes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData(selectedVideoUri);
try {
if (FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(value.getT_email())) {
file_name = filename;
notes_Category = text;
lecture_topic = et_topic.getText().toString().trim();
id = mDatabase.push().getKey();
NotesModelClass notesModelClass = new NotesModelClass(id, notes_Category, lecture_topic, file_name);
mDatabase.child(value.getT_id()).child("Video Notes").child(id).setValue(notesModelClass);
return;
}
}
catch (Exception ex){
throw ex;
}
}
});
`
private void uploadData(Uri videoUri) {
if (videoUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
UploadTask uploadTask = videoRef.putFile(videoUri);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful())
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Upload Complete", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
} else {
Toast.makeText(MainActivity.this, "Nothing to upload", Toast.LENGTH_SHORT).show();
}
}
Try this code
Retrive single video.
StorageReference videoRef = storageRef.child("/videos/" + userUid + "/" + filename);
final long ONE_MEGABYTE = 1024 * 1024;
videoRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Transform bytes to a video, play
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
Retrieve multiple video
StorageTask<UploadTask.TakeSnapshot> storageTask;
storageTask = yourStorageRefernce.putFile(videoUri);
storageTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return yourStorageRefernce.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
arrayList.add(downloadUri.toString());
}
}
});
Help me random video in firebase
private void loadVideosFromFirebase() {
videoArrayList=new ArrayList<>();
DatabaseReference reb = FirebaseDatabase.getInstance().getReference().child("Videos");
reb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds:dataSnapshot.getChildren()) {
ModelVideo modelVideo = ds.getValue(ModelVideo.class);
videoArrayList.add(modelVideo);
}
adapterVideo = new AdapterVideo(VideosActivity.this,videoArrayList);
videosRv.setAdapter(adapterVideo);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}

error with updating user information firebase

so i am creating a sign up page and connect that with firebase users
i am recieving error with updating profile
my code goes as follow:
for creating new user i use
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Log.v("SignUp", "222222222222222222222222222");
Toast.makeText(SignUp.this, "SignUp failed",
Toast.LENGTH_SHORT).show();
} else {
Log.v("SignUp", "333333333333333333333333333");
uploadImage();
}
}
});
and the uploadImage() method is
public void uploadImage() {
if (image != null) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference main = storage.getReferenceFromUrl("link to my account");
StorageReference storageReference = main.child("images/" + image.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(image);
//addonFailurelistener too
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.v("SignUp", "777777777777777777777777");
String download = taskSnapshot.getDownloadUrl().toString();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.build();
//i tried here with .setDisplayName(name)
//and with setPhotoUri(Uri.parse(download)
FirebaseAuth.getInstance().getCurrentUser().updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "8888888888888888888888888888");
addDatabase();
} else {
FirebaseAuth.getInstance().getCurrentUser().delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "999999999999999999999999999");
Toast.makeText(SignUp.this, "Error Occuered While setting your account", Toast.LENGTH_LONG);
finish();
startActivity(new Intent(SignUp.this, SignUp.class));
} else {
Log.v("SignUp", "..........................");
Toast.makeText(SignUp.this, "Error Cannot be resolved \n please try with another Email", Toast.LENGTH_LONG);
finish();
}
}
});
}
}
});
}
});
}
and my logcat get output like that
V/SignUp: 333333333333333333333333333
V/SignUp: 777777777777777777777777
V/SignUp: ..........................
i followed the firebase guide but looks like i am doing something wrong
any idea why it doesnt work? thanks
i get it automatically resolved after waiting for 24 hours so i am assuming account get blocked for 24h after some number of logIn in a single day

Categories