Storing User Data like name, image To Firestore | Firebase Firestore A complete tutorial || PART 4 ||

Hey, welcome to the 4th part of the series in this part we know how to store image, name and other user data to firebase Firestore.

Here is the video tutorial







In the last part we get the image Uri from choosing an image from the gallery now we have to upload that image to Firebase Storage before that we have to compress the image so when the user clicks on the complete button we have to show a progress Dialog and then we start storing the EditText value to strings.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_user_data);
progressDialog = new ProgressDialog(this);
userImage = findViewById(R.id.user_image);
userName = findViewById(R.id.user_name);
userPhone = findViewById(R.id.user_phone);
userAddress = findViewById(R.id.user_address);
submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog.setMessage("Storing Data...");
progressDialog.show();
final String username = userName.getText().toString();
final String userphone = userPhone.getText().toString();
final String useradress = userAddress.getText().toString();
}
}
}
Now we add firebase references to this project and check if the fields are empty or not and then start uploading the image to storage.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_user_data);
progressDialog = new ProgressDialog(this);
userImage = findViewById(R.id.user_image);
userName = findViewById(R.id.user_name);
userPhone = findViewById(R.id.user_phone);
userAddress = findViewById(R.id.user_address);
submit = findViewById(R.id.submit);
firebaseAuth = FirebaseAuth.getInstance();
user_id = firebaseAuth.getCurrentUser().getUid();
firebaseFirestore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog.setMessage("Storing Data...");
progressDialog.show();
final String username = userName.getText().toString();
final String userphone = userPhone.getText().toString();
final String useradress = userAddress.getText().toString();
if(!TextUtils.isEmpty(username)&&!TextUtils.isEmpty(userphone)&&!TextUtils.isEmpty(useradress)&&imageUri!=null){
File newFile = new File(imageUri.getPath());
try {
compressed = new Compressor(StoreUserData.this)
.setMaxHeight(125)
.setMaxWidth(125)
.setQuality(50)
.compressToBitmap(newFile);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
compressed.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] thumbData = byteArrayOutputStream.toByteArray();
UploadTask image_path = storageReference.child("user_image").child(user_id + ".jpg").putBytes(thumbData);
image_path.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
}
});
}
} }); }
}



Now after successfully uploading the image to storage we send all data to a new method and under that, we will get the download link for the image and then we create a hashmap and using that we store all data to Firestore...

public class StoreUserData extends AppCompatActivity {
private ImageView userImage;
private EditText userName, userPhone, userAddress;
private Button submit;
private ProgressDialog progressDialog;
private Uri imageUri = null;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
private String user_id;
private Bitmap compressed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_user_data);
progressDialog = new ProgressDialog(this);
userImage = findViewById(R.id.user_image);
userName = findViewById(R.id.user_name);
userPhone = findViewById(R.id.user_phone);
userAddress = findViewById(R.id.user_address);
submit = findViewById(R.id.submit);
firebaseAuth = FirebaseAuth.getInstance();
user_id = firebaseAuth.getCurrentUser().getUid();
firebaseFirestore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
userImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(StoreUserData.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(StoreUserData.this, "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(StoreUserData.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
choseImage();
}
} else {
choseImage();
}
}
} );
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog.setMessage("Storing Data...");
progressDialog.show();
final String username = userName.getText().toString();
final String userphone = userPhone.getText().toString();
final String useradress = userAddress.getText().toString();
if(!TextUtils.isEmpty(username)&&!TextUtils.isEmpty(userphone)&&!TextUtils.isEmpty(useradress)&&imageUri!=null){
File newFile = new File(imageUri.getPath());
try {
compressed = new Compressor(StoreUserData.this)
.setMaxHeight(125)
.setMaxWidth(125)
.setQuality(50)
.compressToBitmap(newFile);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
compressed.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] thumbData = byteArrayOutputStream.toByteArray();
UploadTask image_path = storageReference.child("user_image").child(user_id + ".jpg").putBytes(thumbData);
image_path.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
storeData(task,
username,
userphone,
useradress);
} else {
String error = task.getException().getMessage();
Toast.makeText(StoreUserData.this, "(IMAGE Error) : " + error, Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
});
} }
private void storeData(Task<UploadTask.TaskSnapshot> task, String username, String userphone, String useradress) {
Uri download_uri;
if (task != null) {
download_uri = task.getResult().getDownloadUrl();
} else {
download_uri = imageUri;
}
Map<String, String> userData = new HashMap<>();
userData.put("userName",username);
userData.put("userPhone",userphone);
userData.put("userAddress",useradress);
userData.put("userImage",download_uri.toString());
firebaseFirestore.collection("Users").document(user_id).set(userData).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
Toast.makeText(StoreUserData.this, "User Data is Stored Successfully", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(StoreUserData.this, MainActivity.class);
startActivity(mainIntent);
finish();
} else {
String error = task.getException().getMessage();
Toast.makeText(StoreUserData.this, "(FIRESTORE Error) : " + error, Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
}
private void choseImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(StoreUserData.this);
}
@Override
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) {
imageUri = result.getUri();
userImage.setImageURI(imageUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}


That's it now run it and I am 100% sure you get an error because of the permission, so open your firebase console and then open storage and enable it and then open the database and create the cloud database and that's it now you can store user data to Firestore ...

Thanks for your time in the next part we will learn about how to check if a user already has data stored in the database or not.

Here is the video tutorial





Source code Available in GitHub- https://github.com/MonsterTechnoGit/Firebase-Firestore-A-complete-tutorial

You can get all the series Post using this link-> Click Here

Comments