Android studio User registration data NOT get inserted to firebase database - java

My code above is to insert user registration data into the firebase database. but when I build the app and try to insert some demo data into the database to perform a user registration none of them is being inserted to the firebase. can anyone check my code and find out anything that I have done wrong?
public class CreateProfile extends AppCompatActivity {
EditText etName,etBio,etProfession,etEmail,etWeb;
Button button;
ImageView imageView;
ProgressBar progressBar;
Uri imageUri;
UploadTask uploadTask;
StorageReference storageReference;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference;
FirebaseFirestore db = FirebaseFirestore.getInstance() ;
DocumentReference documentReference;
private static final int PICK_IMAGE=1;
All_User_Member member;
String currentUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
member = new All_User_Member();
imageView = findViewById(R.id.iv_cp);
etBio = findViewById(R.id.et_bio_cp);
etEmail = findViewById(R.id.et_email_cp);
etName = findViewById(R.id.et_name_cp);
etProfession = findViewById(R.id.et_profession_cp);
etWeb = findViewById(R.id.et_web_cp);
button = findViewById(R.id.btn_cp);
progressBar = findViewById(R.id.progressbar_cp);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = user.getUid();
//reference
documentReference = db.collection("user").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference("Profile images");
databaseReference = database.getReference("All users");
//button click
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
//ProfileImageSelect
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select image"),PICK_IMAGE);
}
});
}
//LoadingProfileImage
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode==PICK_IMAGE || resultCode== RESULT_OK || data != null || data.getData() !=null){
imageUri = data.getData();
Picasso.get().load(imageUri).into(imageView);
}
}catch (Exception e){
Toast.makeText(this, "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private String getFileExt(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType((contentResolver.getType(uri)));
}
private void uploadData() {
String name = etName.getText().toString();
String bio = etBio.getText().toString();
String web = etWeb.getText().toString();
String prof = etProfession.getText().toString();
String mail = etEmail.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(bio) || TextUtils.isEmpty(web) || TextUtils.isEmpty(prof) ||
TextUtils.isEmpty(mail) || imageUri != null){
progressBar.setVisibility(View.VISIBLE);
final StorageReference reference = storageReference.child(System.currentTimeMillis()+ "."+getFileExt(imageUri));
uploadTask = reference.putFile(imageUri);
Task<Uri> urlTask = uploadTask.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 reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUri = task.getResult();
Map<String, String> profile = new HashMap<>();
profile.put("name", name);
profile.put("prof", prof);
profile.put("url", downloadUri.toString());
profile.put("bio", bio);
profile.put("mail", mail);
profile.put("web", web);
profile.put("privacy", "Public");
member.setName(name);
member.setProf(prof);
member.setUid(currentUserId);
member.setUrl(downloadUri.toString());
databaseReference.child(currentUserId).setValue(member);
documentReference.set(profile).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(CreateProfile.this, "Profile Created", Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateProfile.this,Fragment1.class);
startActivity(intent);
}
},2000);
}
});
}
}
});
}else {
Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
}
}
These are the errors getting in the android studio:

Related

The image I downloaded does not appear on the screen in my app

here is my code:
public class Account_settings extends AppCompatActivity implements View.OnClickListener {
Button cprofile, cstatus, cinfo;
ImageView back;
CircleImageView profile_official;
TextView username, status, info, birth;
FirebaseDatabase database;
DatabaseReference myref;
String uid;
Dialog loading;
private StorageReference imagestorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_settings);
cprofile = findViewById(R.id.change_pic);
cstatus = findViewById(R.id.change_status);
cinfo = findViewById(R.id.change_info);
back = findViewById(R.id.back58);
profile_official=findViewById(R.id.profile_image);
username = findViewById(R.id.display_name);
status = findViewById(R.id.status);
info = findViewById(R.id.about);
birth = findViewById(R.id.birth1);
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
database = FirebaseDatabase.getInstance();
myref = database.getReference("User_details");
imagestorage = FirebaseStorage.getInstance().getReference();
loading = new Dialog(this);
loading.setContentView(R.layout.custom_dialog);
loading.setCancelable(true);
loading.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
loading.show();
myref.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Userdetails userdetails = snapshot.getValue(Userdetails.class);
if (userdetails != null) {
birth.setText(userdetails.getBirth());
username.setText(userdetails.getName());
info.setText(userdetails.getInfo_about_me());
status.setText(userdetails.getStatus());
Picasso.with(Account_settings.this).load(userdetails.getProfile()).into(profile_official);
}
loading.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
cprofile.setOnClickListener(this);
cstatus.setOnClickListener(this);
cinfo.setOnClickListener(this);
back.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == back) {
startActivity(new Intent(getApplicationContext(), Main_page.class));
}
if (v == cstatus) {
String status1 = status.getText().toString();
Intent intent = new Intent(this, Status_Activity.class);
intent.putExtra("status_value", status1);
startActivity(intent);
finish();
}
if (v == cinfo) {
Intent intent1 = new Intent(this, my_info.class);
startActivity(intent1);
finish();
}
if (v == cprofile) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Selecting image"), 1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri).start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
loading.show();
Uri resultUri = result.getUri();
StorageReference file_path = imagestorage.child("profile_images").child(uid + ".jpg");
file_path.putFile(resultUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
final Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl();
Toast.makeText(Account_settings.this, "Uploaded", Toast.LENGTH_SHORT).show();
firebaseUri.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String downloadUrl = uri.toString();
myref.child("profile").setValue(downloadUrl);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loading.dismiss();
Toast.makeText(Account_settings.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, "Error! " + error, Toast.LENGTH_SHORT).show();
}
.
.
.
.
.
.
.
.
.
.
...........................................................................................................................................................................................................................................................................................................................
I have no idea why does it happen,so if someone know please help me.Hope you understand my code.
if you have a video about storage photos and show their on a screen please send me.

Profile image not showing after saving it, it just shows a white blank screen

After I save my profile image it says image updated but when I open settings again it does not show any image; instead, a white screen. It shows the status though.
Here is my code:
private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference Rootref;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
Rootref = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef= FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
});
}
private void InitializeFields() {
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status );
userProfileImage= (CircleImageView) findViewById(R.id.set_profile_image );
loadingBar = new ProgressDialog(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode== GalleryPick && resultCode== RESULT_OK && data!= null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
loadingBar.setTitle("set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this," Profile Image Uploded succesfully...", Toast.LENGTH_SHORT).show();
final String downloadedUrl = task.getResult().getStorage().getDownloadUrl().toString();
Rootref.child("Users").child(currentUserID).child("image")
.setValue(downloadedUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this,"Image saved in database Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this,"", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this,"Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if(TextUtils.isEmpty(setUserName)){
Toast.makeText(this,"Please write your username first..", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(setStatus)){
Toast.makeText(this,"Please write your Status first..", 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(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Succesfully...", Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo()
{
Rootref.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") ) &&(dataSnapshot.hasChild("image")))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrievesStatus = dataSnapshot.child("Status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
{
String retrieveUserName = Objects.requireNonNull(dataSnapshot.child("name").getValue()).toString();
String retrievesStatus = Objects.requireNonNull(dataSnapshot.child("Status").getValue()).toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
}
else{
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please set & update your profile information...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
My logcat does not show any error, please help me.

How to retrieve latest entry from the firebase realtime database?

I am trying to take inputs from one user and send the same data to another user. I am not sure what to put as an argument in child so that it refers to the same data and I can retrieve and show the data to another user for approval. I am able to send the image but for the data fields like visitor,mobile and flat not sure what to do.
My code is as follows.
Data entry File Code
public class Main4Activity extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button btn;
ImageView imageView;
static Uri image_uri;
ImageView mImageView;
TextView mCaptureBtn;
Button uploadbtn;
static String downloadurl;
public static String Dvisitor;
public static String Dmobile;
static DatabaseReference reff;
//for upload
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
FirebaseStorage storage;
StorageReference storageReference;
//for upload
static String URL;
//Data store of Visitor
static EditText visitor;
static EditText mbnumber;
EditText bnmbr;
static EditText fnmbr;
EditText emal;
EditText pswrd;
HashMap<String,Object> map = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
//for upload
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
//for upload
mImageView = (ImageView) findViewById(R.id.imageView2);
mCaptureBtn = (TextView) findViewById(R.id.textView4);
//Data for Visitor
visitor = (EditText) findViewById(R.id.vname);
mbnumber = (EditText) findViewById(R.id.mnumber);
bnmbr = (EditText) findViewById(R.id.blknmbr);
fnmbr = (EditText) findViewById(R.id.fltnmbr);
emal = (EditText) findViewById(R.id.emailId);
pswrd = (EditText) findViewById(R.id.passwordfield2);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
upload();
FirebaseDatabase.getInstance().getReference().child("Image").push().setValue(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
map.put("visitor",visitor.getText().toString());
map.put("mobile",mbnumber.getText().toString());
map.put("block",bnmbr.getText().toString());
map.put("flat",fnmbr.getText().toString());
map.put("email",emal.getText().toString());
map.put("password",pswrd.getText().toString());
Toast.makeText(Main4Activity.this, "Successful data registration", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main4Activity.this, "Failed data registration", Toast.LENGTH_SHORT).show();
}
});
}
});
//Camera functionality click and upload starts
mCaptureBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, PERMISSION_CODE);
} else {
openCamera();
}
} else {
openCamera();
}
}
});
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main4Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
{
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
mImageView.setImageURI(image_uri);
}
}
private void upload(){
if(image_uri != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image").push();
//HashMap<String, String> hasmap = new HashMap<>();
URL = uri.toString();
map.put("imgurl",URL);
//map.put("imageurl", String.valueOf(uri));
imagestore.setValue(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent= new Intent(Main4Activity.this,Main5Activity.class);
startActivity(intent);
}
});
//This is your image url do whatever you want with it.
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Failed "+e.getMessage(), 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 + "%");
}
});
}
}
}
//Camera functionality click and upload starts
Code for another user to Approve
public class Main5Activity extends AppCompatActivity {
Button btnAllow, btnProhibit;
private String Dvisitor;
private String Dmobile;
private String Dflat;
DatabaseReference reff;
ImageView img;
private DatabaseReference Post;
static TextView textView;
String roadies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnAllow = (Button) findViewById(R.id.button);
btnProhibit = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView5);
img = (ImageView) findViewById(R.id.imageView3);
imageshow();
init();
readonetime();
}
private void readonetime() {
Query query = Post.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void init() {
Post = FirebaseDatabase.getInstance().getReference().child("Image");
}
private void imageshow() {
reff = FirebaseDatabase.getInstance().getReference().child("Image");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.get().load(Main4Activity.URL).fit().into(img);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Main5Activity.this, "OoooooLalalala", Toast.LENGTH_SHORT).show();
}
});
btnAllow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main8Activity.class);
startActivity(intent);
}
});
btnProhibit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main9Activity.class);
startActivity(intent);
}
});
}
}
In your Main5Activity, I think:
This:
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
Must be like this:
for(DataSnapshot ds: dataSnapshot.getChildren()) {
String post = ds.child("visitor").getValue(String.class);
String post1 = ds.child("mobile").getValue(String.class);
String post2 = ds.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}

Upload Images to Firebase Storage and have a link in Firebase Database

I am currently working on an Incident Reporting application which allows users to choose and upload images.
I am already successful in posting images to Firebase Storage but I am wondering if it is possible to have a link/url in Firebase Database from which I can click to redirect me to Firebase Storage to see that image.
I want this function so that along with user inputs such as Title, Date, Remarks, the end-user would be able to see the "image" child with the link along with other inputs
I have tried searching StackOverflow and Youtube for answers but most of them are old and seem outdated. There is a command "getDownloadUrl" but i believe it has been deprecated.
This is the code from my class that uploads my image to Firebase Storage
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Failed"+e.getMessage(), 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+"%");
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
ReportFragment
import static android.app.Activity.RESULT_OK;
import static com.firebase.ui.auth.AuthUI.getApplicationContext;
public class ReportFragment extends Fragment implements
AdapterView.OnItemSelectedListener{
private Button btnChoose,btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private EditText reportedBy;
private TextView date; //upstairs declare alr as mDisplayDate
private Spinner spinner; //downstairs declare alr as spinner3
private EditText location;
private Spinner spinner2; //downstairs declare alr as spinner2
private EditText details;
private Spinner spinner3; //downstairs declare alr as spinner1
private EditText remarks;
private EditText title;
private Button submitIncident;
public static TextView resultTextView3;
Button scan_btn3;
private ImageView imageView2;
private TextView imgUrl1;
DatabaseReference databaseIncidents;
FirebaseStorage storage;
StorageReference storageReference;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_report, container, false);
databaseIncidents =
FirebaseDatabase.getInstance().getReference("Incidents");
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose = (Button) v.findViewById(R.id.btnChoose);
btnUpload = (Button) v.findViewById(R.id.btnUpload);
imageView = (ImageView) v.findViewById(R.id.imgView);
reportedBy = (EditText) v.findViewById(R.id.etreportedby);
// Below have already line 151
// date = (TextView) v.findViewById(R.id.tvdate);
location = (EditText) v.findViewById(R.id.etlocation);
details = (EditText) v.findViewById(R.id.etdetails);
remarks = (EditText) v.findViewById(R.id.etremarks);
title = (EditText) v.findViewById(R.id.ettitle);
submitIncident = (Button) v.findViewById(R.id.btnSubmit);
resultTextView3 = (TextView)v.findViewById(R.id.result_text3);
scan_btn3 = (Button)v.findViewById(R.id.btn_scan3);
imageView2 = (ImageView)v.findViewById(R.id.ivimagescardinput);
imgUrl1 = (TextView)v.findViewById(R.id.tvimagescard);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
// btnUpload.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// uploadImage();
// }
// });
scan_btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new
Intent(getActivity(),ScanCodeActivity.class));
}
});
submitIncident.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incidentSubmit();
uploadImage();
Glide.with(getActivity()).load(URL).into(imageView2);
}
});
return`
}
private void incidentSubmit(){
String reportedname = reportedBy.getText().toString().trim();
String location1 = location.getText().toString();
String details1 = details.getText().toString();
String remarks1 = remarks.getText().toString();
String urgency1 = spinner.getSelectedItem().toString();
String type1 = spinner2.getSelectedItem().toString();
String splocation1 = spinner3.getSelectedItem().toString();
String date1 = mDisplayDate.getText().toString();
String title1 = title.getText().toString();
String qrlocation1 = resultTextView3.getText().toString();
String image1 = imgUrl1.getText().toString();
if(!TextUtils.isEmpty(reportedname)) {
String incidentId = databaseIncidents.push().getKey();
Incident incident = new
Incident(reportedname,location1,details1,remarks1,urgency1,type1,splocation1,date1,title1,qrlocation1,image1);
databaseIncidents.child(incidentId).setValue(incident);
Toast.makeText(getActivity(), "Incident Added", Toast.LENGTH_LONG).show();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new IncmanFragment());
fragmentTransaction.commit();
} else {
Toast.makeText(getActivity(), "All fields must be entered",Toast.LENGTH_LONG).show();
}
}
private void uploadImage() {
if (filePath != null) {
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
databaseIncidents.child("imageId").setValue(URL.toString());
}
});
}
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Any help or tutorials is greatly appreciated!
Database Inputs (not including image)
For storing the images to your Firebase Storage, you first set a correct reference and just store the image there, very similar to Firebase Database data storing.
To have a link in the Firebase Database, you can just use downloadUri you can get from storage and have it stored in the database.
The code for this looks something like this, you can take an inspiration from this and come up with a code that suits you more:
private void uploadFile(Bitmap bitmap) {
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
final UploadTask uploadTask = ImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("whatTheFuck:",exception.toString());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (!task.isSuccessful()) {
Log.i("problem", task.getException().toString());
}
return ImagesRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());
Log.i("seeThisUri", downloadUri.toString());// This is the one you should store
ref.child("imageURL").setValue(downloadUri.toString());
} else {
Log.i("wentWrong","downloadUri failure");
}
}
});
}
});
}
If i understand correctly you can upload images to storage succesfully but you are having trouble when you want to get that image direct url.
Try this code:
StorageReference storageRef=FirebaseStorage.getInstance().getReference().child("images/"+ UUID.randomUUID().toString());
storageRef.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
//This is your image url do whatever you want with it.
}
});
}
}
});

Not able to get firebase datasnapshot value string

This is the structure of my databaseThis is the code to get the user_name from the database
The (dataSnapshot)shows Not Annotated parameter overrides #NonNull parameter
I have added the whole code for the settingsActivity down below i hope this helps
public class SettingsActivity extends AppCompatActivity
{
private CircleImageView settingsDisplayProfileImage;
private TextView settingsDisplayname;
private TextView settingsDisplayStatus;
private TextView settingsDisplayaddress;
private TextView settingsDisplayphone;
private TextView settingsDisplayservice;
private Button settingsChangeProfileImageButton;
private Button settingsUpdateProfileButton;
private final static int Gallery_Pick = 1;
private StorageReference storeProfileImagestorageRef;
private DatabaseReference getUserDataReference;
private FirebaseAuth mAuth;
Bitmap thumb_bitmap = null;
private StorageReference thumbImageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;
private String online_user_id;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
online_user_id = mAuth.getCurrentUser().getUid();
getUserDataReference = FirebaseDatabase.getInstance().getReference().child("Users").child(online_user_id);
getUserDataReference.keepSynced(true);
storeProfileImagestorageRef = FirebaseStorage.getInstance().getReference().child("Profile_Images");
thumbImageRef = FirebaseStorage.getInstance().getReference().child("Thumb_Images");
settingsDisplayProfileImage = (CircleImageView) findViewById(R.id.settings_profile_image);
settingsDisplayname = (TextView) findViewById(R.id.settings_username);
settingsDisplayaddress = (TextView) findViewById(R.id.settings_user_address);
settingsDisplayphone = (TextView)findViewById(R.id.settings_user_phone);
settingsDisplayservice = (TextView) findViewById(R.id.settings_user_service);
settingsDisplayStatus = (TextView) findViewById(R.id.settings_user_status);
settingsChangeProfileImageButton = (Button) findViewById(R.id.settings_change_profile_image_button);
settingsUpdateProfileButton = (Button) findViewById(R.id.settings_update_profile);
loadingBar= new ProgressDialog(this);
getUserDataReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
//error occurs here first line below
String name = dataSnapshot.child("user_name").getValue().toString();
String status = dataSnapshot.child("user_status").getValue().toString();
final String image = dataSnapshot.child("user_image").getValue().toString();
String address = dataSnapshot.child("user_address").getValue().toString();
String phone = dataSnapshot.child("user_phone").getValue().toString();
String service = dataSnapshot.child("user_service").getValue().toString();
String thumb_image = dataSnapshot.child("user_thumb_image").getValue().toString();
settingsDisplayname.setText(name);
settingsDisplayservice.setText(service);
settingsDisplayStatus.setText(status);
settingsDisplayaddress.setText(address);
settingsDisplayphone.setText(phone);
if (!image.equals("default_profile")) {
//
this is the other half of the code but everything from here works fine...
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.default_profile).into(settingsDisplayProfileImage);
Picasso.with(SettingsActivity.this).load(image).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.default_profile).into(settingsDisplayProfileImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(SettingsActivity.this).load(image).fit().centerInside().placeholder(R.drawable.default_profile).into(settingsDisplayProfileImage);
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
settingsChangeProfileImageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
settingsUpdateProfileButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String old_status = settingsDisplayStatus.getText().toString();
String old_address = settingsDisplayaddress.getText().toString();
String old_phone = settingsDisplayphone.getText().toString();
String old_service = settingsDisplayservice.getText().toString();
Intent profileIntent = new Intent(SettingsActivity.this, ProfileActivity.class);
profileIntent.putExtra("user_status", old_status);
profileIntent.putExtra("user_service", old_service);
profileIntent.putExtra("user_phone", old_phone);
profileIntent.putExtra("user_address", old_address);
startActivity(profileIntent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
loadingBar.setTitle("Updating Profile Image");
loadingBar.setMessage("Please wait while profile image is updated");
loadingBar.show();
Uri resultUri = result.getUri();
File thumb_filepathUri = new File(resultUri.getPath());
String user_id = mAuth.getCurrentUser().getUid();
try
{
thumb_bitmap = new Compressor(this)
.setMaxWidth(100)
.setMaxHeight(100)
.setQuality(50)
.compressToBitmap(thumb_filepathUri);
}
catch (IOException e)
{
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
final byte[] thumb_byte = byteArrayOutputStream.toByteArray();
StorageReference filePath = storeProfileImagestorageRef.child(user_id + ".jpg");
final StorageReference thumb_filePath = thumbImageRef.child(user_id + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task)
{
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this,
"Saving profile image...", Toast.LENGTH_LONG).show();
// final String downloadUrl = task.getResult().getDownloadUrl().toString();
downloadImageUrl =thumb_filePath .getDownloadUrl().toString();
UploadTask uploadTask = thumb_filePath.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>()
{
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot>thumb_task)
{
String thumb_downloadUrl = thumb_filePath.getDownloadUrl().toString();
// thumb_downloadImageUrl = filePath.getDownloadUrl().toString();
if (task.isSuccessful())
{
Map update_user_data = new HashMap();
update_user_data.put("user_image", downloadImageUrl);
update_user_data.put("user_thumb_image", thumb_downloadUrl);
getUserDataReference.updateChildren(update_user_data)
.addOnCompleteListener(new OnCompleteListener<Void>()
{
#Override
public void onComplete(#NonNull Task<Void> task)
{
Toast.makeText(SettingsActivity.this,
"Profile Image Updated Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
});
}
}
});
}
else
{
Toast.makeText(SettingsActivity.this, "Error occurred while uploading your profile picture..",
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
this is the logcat below
11-15 03:22:10.646 27837-27837/com.paddi.paddi.paddi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.paddi.paddi.paddi, PID: 27837
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.paddi.paddi.paddi.SettingsActivity$1.onDataChange(SettingsActivity.java:101)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

Categories

Resources