I'm making setup_profile activity. Users can change information.
When users do not change the image, it is good. But when the user change image errors come.
I add 'null checker' like
if (uri!=null) But I don know why it is.
Here are the errors.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
at com.razberrylovers.mbting.SetUpActivity.saveToFireStore(SetUpActivity.java:291)
at com.razberrylovers.mbting.SetUpActivity.access$700(SetUpActivity.java:40)
at com.razberrylovers.mbting.SetUpActivity$10.onComplete(SetUpActivity.java:217)
Here is my code.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up);
Toolbar setUpToolbar = findViewById(R.id.setup_toolbar);
setSupportActionBar(setUpToolbar);
getSupportActionBar().setTitle("Profile");
storageReference = FirebaseStorage.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
Uid = auth.getCurrentUser().getUid();
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.INVISIBLE);
circleImageView = findViewById(R.id.circleImageView);
mProfileName = findViewById(R.id.profile_name);
mSaveBtn = findViewById(R.id.save_btn);
mProfileSchool = findViewById(R.id.profile_school);
mconcreteregion = findViewById(R.id.profile_concreteregion);
// setting dialog
textView_age=findViewById(R.id.age_dialog);
textView_age.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new FragmentDialogBox().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_job=findViewById(R.id.job_dialog);
textView_job.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_job().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_region = findViewById(R.id.region_dialog);
textView_region.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_region().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_height = findViewById(R.id.height_dialog);
textView_height.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_height().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_religion = findViewById(R.id.religion_dialog);
textView_religion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_religion().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_drink = findViewById(R.id.drink_dialog);
textView_drink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_drink().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_smoke = findViewById(R.id.smoke_dialog);
textView_smoke.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_smoke().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_mbti = findViewById(R.id.mbti_dialog);
textView_mbti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_mbti().show(getSupportFragmentManager(),"fragmentDialog");
}
});
and load data from firestore + mSaveBtn click listener(including the case of not changing the picture)
firestore.collection("Users").document(Uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
if (task.getResult().exists()){
String name = task.getResult().getString("name");
String age = task.getResult().getString("age");
String job = task.getResult().getString("job");
String imageUrl = task.getResult().getString("image");
String school = task.getResult().getString("school");
String region = task.getResult().getString("region");
String concrete_region = task.getResult().getString("concrete_region");
String height = task.getResult().getString("height");
String religion = task.getResult().getString("religion");
String drink = task.getResult().getString("drink");
String smoke = task.getResult().getString("smoke");
String mbti = task.getResult().getString("mbti");
mProfileName.setText(name);
textView_age.setText(age);
textView_job.setText(job);
mProfileSchool.setText(school);
textView_region.setText(region);
mconcreteregion.setText(concrete_region);
textView_height.setText(height);
textView_religion.setText(religion);
mImageUri = Uri.parse(imageUrl);
textView_drink.setText(drink);
textView_smoke.setText(smoke);
textView_mbti.setText(mbti);
Glide.with(SetUpActivity.this).load(imageUrl).into(circleImageView);
}
}
}
});
//
mSaveBtn.setOnClickListener(v -> {
progressBar.setVisibility(View.VISIBLE);
String name = mProfileName.getText().toString();
String age = textView_age.getText().toString();
String job = textView_job.getText().toString();
String school = mProfileSchool.getText().toString();
String region = textView_region.getText().toString();
String concrete_region = mconcreteregion.getText().toString();
String height = textView_height.getText().toString();
String religion = textView_religion.getText().toString();
String drink = textView_drink.getText().toString();
String smoke = textView_smoke.getText().toString();
String mbti = textView_mbti.getText().toString();
StorageReference imageRef = storageReference.child("Profile_pics").child(Uid+".jpg");
//프로필 수정시 사진을 바꾸지 않았을 경우를 해결
if(isPhotoSelected)
{
if (!name.isEmpty() && mImageUri != null) {
imageRef.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
saveToFireStore(task, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "등록을 하지 않은 것이 있습니다.", Toast.LENGTH_SHORT).show();
}
}
else{
saveToFireStore(null, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
}
});
--> also code
Next code
There is a section that allows permission, and there is a saveToFireStore() method.-> when the task is null, the photo is not changed and when the task is not null photo will be changed.
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(SetUpActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(SetUpActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
else{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(SetUpActivity.this);
}
}
}
});
}
private void saveToFireStore(Task<UploadTask.TaskSnapshot> task, String name,
String age, String job, String school, String region,
String concrete_region, String height, String religion,
String drink, String smoke, String mbti,
StorageReference imageRef) {
if(task != null){
imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
downloadUri = uri;
}
});
}
else{
downloadUri = mImageUri;
}
HashMap<String , Object> map = new HashMap<>();
map.put("name", name);
map.put("age", age);
map.put("job", job);
map.put("school", school);
map.put("region", region);
map.put("concrete_region", concrete_region);
map.put("height", height);
map.put("religion", religion);
map.put("drink", drink);
map.put("smoke", smoke);
map.put("mbti", mbti);
map.put("image",downloadUri.toString());
firestore.collection("Users").document(Uid).set(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "프로필이 등록되었습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SetUpActivity.this, MainActivity.class));
finish();
}
else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this,task.getException().toString(),Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable 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){
mImageUri = result.getUri();
circleImageView.setImageURI(mImageUri);
isPhotoSelected = true;
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Toast.makeText(this,result.getError().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
The part of the error that logcat showed
imageRef.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
saveToFireStore(task, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
and
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "프로필이 등록되었습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SetUpActivity.this, MainActivity.class));
finish();
}
else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this,task.getException().toString(),Toast.LENGTH_SHORT).show();
}
}
Related
I have using Firebase Phone Auth in my project. But the firebase only sending otp for testing phone numbers.
I have added SHA1 and SHA256 in firebase project and enable Android DeviceCheck API. But all time i didn't get otp from Firebase.
When I cheking with testing phone number the otp popup screen is showing up and i am entered otp which i was created verification code ie 123456, 111111, 222222 etc. But otherwise i dont getting otp from firebase.
This is my code
username = findViewById(R.id.username);
fullname = findViewById(R.id.fullname);
mTelephoneNumber = findViewById(R.id.telephonenumberregister);
continueregister = findViewById(R.id.continueregister);
back = findViewById(R.id.back);
txt_login = findViewById(R.id.btnSign);
countryCodePicker = findViewById(R.id.countrycodepicker);
pd = new ProgressDialog(RegisterActivity.this);
pd.setCancelable(false);
auth = FirebaseAuth.getInstance();
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, StartActivity.class));
}
});
txt_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
continueregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd.setMessage("Loading");
pd.show();
mFullTelephoneNumber = countryCodePicker.getSelectedCountryCodeWithPlus() + mTelephoneNumber.getText().toString();
FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("telephoneno").equalTo(mFullTelephoneNumber)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
pd.dismiss();
Toast.makeText(RegisterActivity.this, "There is a user who has this phone number", Toast.LENGTH_SHORT).show();
}
else {
pd.dismiss();
phoneVerification();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
private void phoneVerification(){
pd.setMessage("Sending");
pd.show();
AlertDialog dialog;
View verficationView = LayoutInflater.from(RegisterActivity.this).inflate(R.layout.verificationdialoglayout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setView(verficationView);
builder.setCancelable(false);
dialog = builder.create();
final EditText input_verificationCode = verficationView.findViewById(R.id.mverificationcode);
Button submit = verficationView.findViewById(R.id.submit);
Button resend = verficationView.findViewById(R.id.resend);
TextView countDownView = verficationView.findViewById(R.id.countdown);
ImageButton closeVerification = verficationView.findViewById(R.id.closeverification);
Log.d("a", mFullTelephoneNumber);
CountDownTimer countDownTimer = countDownTimer(countDownView, dialog);
closeVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
countDownTimer.onFinish();
}
});
callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Log.d("error", e.getMessage());
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Log.d("verificationcode", s);
mVerificationId = s;
resendingToken = forceResendingToken;
pd.dismiss();
dialog.show();
countDownTimer.start();
}
};
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(mFullTelephoneNumber)
.setCallbacks(callbacks)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(RegisterActivity.this)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd.setMessage("Please Wait...");
pd.show();
String str_verificationCode = input_verificationCode.getText().toString();
if (!TextUtils.isEmpty(str_verificationCode) && str_verificationCode.length() == 6){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, input_verificationCode.getText().toString());
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String userID = task.getResult().getUser().getUid();
String a = "0";
DatabaseReference pref = FirebaseDatabase.getInstance().getReference().child("wallet").child(userID);
HashMap<String, Object> point = new HashMap<>();
point.put("balance", a);
pref.setValue(point);
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
HashMap<String, Object> map = new HashMap<>();
map.put("id", userID);
map.put("telephoneno", mFullTelephoneNumber);
map.put("username", username.getText().toString().toLowerCase());
map.put("fullname", fullname.getText().toString());
map.put("imageurl", "https://firebasestorage.googleapis.com/v0/b/instagramtest-fcbef.appspot.com/o/placeholder.png?alt=media&token=b09b809d-a5f8-499b-9563-5252262e9a49");
map.put("bio", "");
reference.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
pd.dismiss();
countDownTimer.onFinish();
}
else {
Toast.makeText(RegisterActivity.this, "error", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
pd.dismiss();
dialog.dismiss();
Toast.makeText(RegisterActivity.this, "Wrong code is entered.", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "Please enter the code!", Toast.LENGTH_SHORT).show();
}
}
});
resend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
pd.setMessage("Resending");
pd.show();
countDownTimer.onFinish();
countDownTimer.start();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(mFullTelephoneNumber)
.setCallbacks(callbacks)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(RegisterActivity.this)
.setForceResendingToken(resendingToken)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
});
}
private CountDownTimer countDownTimer(TextView countDownView, AlertDialog dialog){
return new CountDownTimer(61000, 1000){
#SuppressLint("SetTextI18n")
#Override
public void onTick(long l) {
countDownView.setVisibility(View.VISIBLE);
countDownView.setText("" + l / 1000);
}
#Override
public void onFinish() {
countDownView.setVisibility(View.GONE);
dialog.dismiss();
}
};
}
}
Please give me a solution.
If anyone is facing this problem, Try to Add SHA fingerprint to your firebase to receive SMS
I have successfully uploaded the media in the firebase but i'm unable to retrieve it. apparently it shows that the media_problem is pointing to a null object. below is my code.
This is my code to retrieve:
this.view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "TOO FAST! TRY AGAIN", Toast.LENGTH_LONG);
try {
Dash_agri.this.firestore.collection("problems").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete( Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
Dash_agri.this.records.clear();
Iterator it = ((QuerySnapshot) task.getResult()).iterator();
while (it.hasNext()) {
QueryDocumentSnapshot document = (QueryDocumentSnapshot) it.next();
Dash_agri.this.single_ID = document.getId();
Dash_agri.this.single_name = (String) document.get("NAME_problems");
Dash_agri.this.single_phone = (String) document.get("PHONE_problems");
Dash_agri.this.single_description = (String) document.get("DESCRIPTION_problems");
Dash_agri.this.single_URL = (String) document.get("MEDIA_problems");
String view_media = "Touch to view media";
new SpannableString(view_media).setSpan(new ClickableSpan() {
public void onClick(View widget) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
}
}, 0, 9, 33);
Dash_agri.this.record_id.add(Dash_agri.this.single_ID);
ArrayList<String> arrayList = Dash_agri.this.records;
StringBuilder sb = new StringBuilder();
sb.append("QUERY#");
sb.append(Dash_agri.this.single_ID);
sb.append(" by ");
sb.append(Dash_agri.this.single_name);
sb.append("\n");
sb.append(Dash_agri.this.single_description);
sb.append("\n\n");
sb.append(view_media);
arrayList.add(sb.toString());
}
}
}
});
} catch (Exception e) {
Toast.makeText(Dash_agri.this.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
}
Dash_agri.this.listView.setAdapter(new ArrayAdapter<>(Dash_agri.this.getApplicationContext(), R.layout.simple_list_item_1, Dash_agri.this.records));
}
});
This is my code to upload:
public class Upload extends AppCompatActivity {
private static final int PICK_MEDIA_REQUEST = 1;
String MEDIA_url;
String NAME;
String PHONE;
long TIME_ID = System.currentTimeMillis();
String USER_ID;
TextView file;
FirebaseAuth firebaseAuth;
FirebaseFirestore firestore;
Button img;
EditText prob;
ProgressBar progressBar;
StorageReference storageReference;
Button upld;
/* access modifiers changed from: private */
public Uri uri;
Button vid;
/* access modifiers changed from: protected */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == -1 && data != null && data.getData() != null) {
this.uri = data.getData();
this.file.setText(this.uri.getPath());
}
}
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_upload);
this.firebaseAuth = FirebaseAuth.getInstance();
this.firestore = FirebaseFirestore.getInstance();
this.storageReference = FirebaseStorage.getInstance().getReference();
this.prob = (EditText) findViewById(R.id.editTextProblem_upload);
this.file = (TextView) findViewById(R.id.textViewFile_upload);
this.img = (Button) findViewById(R.id.buttonImage_upload);
this.vid = (Button) findViewById(R.id.buttonVideo_Upload);
this.upld = (Button) findViewById(R.id.buttonUpload_upload);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar_upload);
this.progressBar.setVisibility(View.VISIBLE);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction("android.intent.action.GET_CONTENT");
Upload.this.startActivityForResult(intent, 1);
}
});
this.vid.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction("android.intent.action.GET_CONTENT");
startActivityForResult(intent, 1);
}
});
try {
this.upld.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (prob.getText().toString().isEmpty() || file.getText().toString().equals("No file selected")) {
Toast.makeText(getApplicationContext(), "Please write your problem and upload a file!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
upload_file_also(uri);
USER_ID = firebaseAuth.getCurrentUser().getUid();
TIME_ID = System.currentTimeMillis();
firestore.collection("users").document(USER_ID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
NAME = documentSnapshot.getString("NAME_");
PHONE = documentSnapshot.getString("PHONE_");
}
});
NAME = NAME == null ? "null" : NAME;
PHONE = PHONE == null ? "null" : PHONE;
if (!NAME.equals("null") && !PHONE.equals("null")) {
CollectionReference collection = firestore.collection("problems");
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(TIME_ID);
DocumentReference documentReference = collection.document(String.valueOf(sb.toString()));
Map<String, Object> user_problems = new HashMap<>();
user_problems.put("DESCRIPTION_problems", prob.getText().toString());
user_problems.put("NAME_problems", NAME);
user_problems.put("PHONE_problems", PHONE);
user_problems.put("MEDIA_problems", Upload.this.MEDIA_url);
documentReference.set(user_problems).addOnSuccessListener(new OnSuccessListener<Void>() {
public void onSuccess(Void aVoid) {
Toast.makeText(Upload.this.getApplicationContext(), "Successfully uploaded", Toast.LENGTH_SHORT).show();
Upload.this.startActivity(new Intent(Upload.this.getApplicationContext(), Dash_farmer.class));
Upload.this.finish();
}
});
}
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
/* access modifiers changed from: private */
public void upload_file_also(Uri fileUri) {
StorageReference storageReference2 = this.storageReference;
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(this.TIME_ID);
final StorageReference sr = storageReference2.child(String.valueOf(sb.toString()));
sr.putFile(fileUri).addOnSuccessListener((OnSuccessListener<TaskSnapshot>) new OnSuccessListener<TaskSnapshot>() {
public void onSuccess(TaskSnapshot taskSnapshot) {
sr.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
public void onSuccess(Uri uri) {
Upload.this.MEDIA_url = uri.toString();
Upload.this.progressBar.setVisibility(View.VISIBLE);
Upload.this.upld.setText("TAP AGAIN TO UPLOAD MEDIA");
}
});
}
});
}
}
I'm unable to find why this isn't working. Please put a light on where this is going wrong.
I'm trying to show the image which has been sucessfully uploaded in firebase storage and whose unique id is also updated in Firebase Database under "pics" in my Imageview but I did tried multiple time but am unable to show the image or retrive images .
Below is my Firebase Database Structure.
and my Imageview is
Where image should be displayed in place of Bookshelf which is default pic but unable to do so.
Below is my upload Activity
public class UploadBook extends AppCompatActivity {
FirebaseDatabase database;
EditText etAuthor, etbookDesc, etbookTitle, etName, etEmail, etMobile, etUniversity, etbookPrice;
ImageView iv1;
Button b1;
AlertDialog.Builder builder1;
DatabaseReference dbreference;
String item = "start"; // for spinner
FirebaseStorage storage;
private static final int CAMERA_REQUEST_CODE = 1;
StorageReference mStorageRef;
FirebaseAuth fauth;
int count = 0;
Uri filePath = null;
public Books b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.nepalpolice.bookbazaar.R.layout.activity_upload_book);
getSupportActionBar().setTitle("Upload book");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
ActivityCompat.requestPermissions(UploadBook.this, new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 11);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference();
fauth = FirebaseAuth.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference();
iv1 = (ImageView) findViewById(com.nepalpolice.bookbazaar.R.id.itemImage1);
etAuthor = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText1);
etbookDesc = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText2);
etbookTitle = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText3);
etName = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText4);
etEmail = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText5);
etMobile = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText6);
etUniversity = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText7);
etbookPrice = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText8);
b1 = (Button) findViewById(com.nepalpolice.bookbazaar.R.id.buttonPost);
t3 t = new t3();
t.execute();
Spinner spinner = (Spinner) findViewById(com.nepalpolice.bookbazaar.R.id.spinner1);
final String[] items = new String[]{"Select your category :", "Computer Science", "Electronics", "Mechanical", "Civil", "Electrical", "Mechatronics", "Software", "Others"};
ArrayAdapter<String> spinneradapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
spinner.setAdapter(spinneradapter);
spinner.setActivated(false);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
item = adapterView.getItemAtPosition(position).toString();
count = position;
if (position == 0)
return;
Toast.makeText(adapterView.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
imageButtonclick();
postButtonClick();
builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Discard this item !");
builder1.setCancelable(true);
builder1.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent in = new Intent(UploadBook.this, BooksPage.class);
startActivity(in);
finish();
dialog.cancel();
}
});
}
void imageButtonclick() {
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity(filePath).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(UploadBook.this);
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//intent.putExtra(MediaStore.EXTRA_OUTPUT,imageuri);
//startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
void postButtonClick() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (count == 0) {
Toast.makeText(UploadBook.this, "Please select a valid category", Toast.LENGTH_SHORT).show();
return;
}
if (!TextUtils.isDigitsOnly(etMobile.getText()) || etMobile.getText().toString().trim().length() != 10) {
Toast.makeText(UploadBook.this, "Please check number format !", Toast.LENGTH_SHORT).show();
return;
}
if (etAuthor.getText().toString().trim().length() > 0 && etbookDesc.getText().toString().trim().length() > 0
&& etbookTitle.getText().toString().trim().length() > 0 && etName.getText().toString().trim().length() > 0
&& etEmail.getText().toString().trim().length() > 0 && etMobile.getText().toString().trim().length() > 0
&& etUniversity.getText().toString().trim().length() > 0 && etbookPrice.getText().toString().trim().length() > 0
&& filePath!=null) {
String bauthor = etAuthor.getText().toString();
String bdesc = etbookDesc.getText().toString();
String btitle = etbookTitle.getText().toString();
String sellername = etName.getText().toString();
String selleremail = etEmail.getText().toString();
Long sellermobile = Long.parseLong(etMobile.getText().toString());
String selleruniversity = etUniversity.getText().toString();
Double bprice = Double.parseDouble(etbookPrice.getText().toString());
Toast.makeText(getApplicationContext(), "Your book will be uploaded shortly !", Toast.LENGTH_SHORT).show();
b = new Books(btitle, bauthor, bdesc, sellername, selleremail, sellermobile, item, selleruniversity, bprice);
String bookid = dbreference.child("books").child(item).push().getKey();
dbreference.child("books").child(item).child(bookid).setValue(b);
t2 t2 = new t2();
t2.execute(bookid);
Intent in = new Intent(UploadBook.this, BooksPage.class);
startActivity(in);
finish();
} else {
Toast.makeText(UploadBook.this, "Please enter your complete details !", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
/*AlertDialog alert2 = builder1.create();
alert2.show();*/
CustomDialogClass cdd = new CustomDialogClass(UploadBook.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
filePath = data.getData();
iv1.setImageURI(filePath);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
iv1.setImageURI(resultUri);
filePath = resultUri;
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
class t2 extends AsyncTask<String,Integer,Boolean> {
#Override
protected Boolean doInBackground(final String... bookid) {
if(filePath != null) {
mStorageRef.child(bookid[0]).putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Toast.makeText(UploadBook.this, "Upload successful", Toast.LENGTH_SHORT).show();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadBook.this, "Upload Failed : " + e, Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
}
class t3 extends AsyncTask<String,Integer,Boolean>{
#Override
protected Boolean doInBackground(String... strings) {
publishProgress();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
etName.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("name","Delault name"));
etEmail.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("email","Default email"));
etUniversity.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("university","Default university"));
etMobile.setText(String.valueOf(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("phone","Default phone")));
}
}
and my Adapter class is
public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
ArrayList<Books> bookslist;
CardView cv;
FirebaseAuth fauth;
FirebaseDatabase database;
DatabaseReference dbreference;
Books b;
public SubjectBooksAdapter(ArrayList<Books> bookslist){
this.bookslist = bookslist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bookName,bookAuthor,bookDesc,bookPrice,bookCall;
ImageView iv;
MyViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.my_card_view);
iv = (ImageView) itemView.findViewById(R.id.imageView);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
bookName = (TextView) itemView.findViewById(R.id.bookName);
bookAuthor = (TextView) itemView.findViewById(R.id.bookAuthor);
bookDesc = (TextView) itemView.findViewById(R.id.bookDesc);
bookPrice = (TextView) itemView.findViewById(R.id.bookPrice);
bookCall = (TextView) itemView.findViewById(R.id.bookCall);
fauth = FirebaseAuth.getInstance();
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
b = bookslist.get(position);
holder.bookName.setText(b.getBname());
holder.bookAuthor.setText(b.getBauthor());
holder.bookDesc.setText(b.getBdesc());
holder.bookPrice.setText("Rs. "+b.getPrice());
holder.bookCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Log.e("Current user is ", fauth.getCurrentUser().getEmail());
b = bookslist.get(position);
String[] arr = {b.getSelleremail(),b.getSellername(),b.getBname(),b.getBauthor()};
//Log.e("Seller is ",b.getSellername());
Intent in = new Intent(v.getContext(),Chat.class);
in.putExtra("seller",arr);
v.getContext().startActivity(in);
}
});
Glide.with(cv.getContext()).load(Uri.parse(b.getPics())).placeholder(R.drawable.bshelf).error(R.drawable.bshelf).into(holder.iv);
}
#Override
public int getItemCount() {
return bookslist.size();
}
}
Please help.
Here is my whole project
https://github.com/BlueYeti1881/Pustak
Thanks in advance.
In UploadBook class change this
if(filePath != null) {
mStorageRef.child(bookid[0]).putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Toast.makeText(UploadBook.this, "Upload successful", Toast.LENGTH_SHORT).show();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
To This-
final StorageReference ref = mStorageRef.child(bookid[0]);
UploadTask uploadTask = ref.putFile(file);
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 ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUri.toString());
} else {
// Handle failures
}
}
});
i am working on the a social app where the user can upload their image on their feeds but when the user is picking up the image ,the image less than 2 mb are getting picked up and are successfully uploaded to the firebase but when the user uploads the image more than 2mb the app crashes. what can be done to compress the image ..
postactivity.java
private Toolbar mToolbar;
private ImageButton SelectPostImage;
private Button UpdatePostButton;
private ProgressDialog loadingBar;
private EditText PostDescription;
private static final int Gallery_pick = 1;
private Uri ImageUri;
private String Description;
private StorageReference PostsImagesReference;
private DatabaseReference usersRef, PostsRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, saveCurrentTime,current_user_id, postRandomName, downloadUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
PostsImagesReference = FirebaseStorage.getInstance().getReference();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
SelectPostImage = (ImageButton)findViewById(R.id.select_post_image);
UpdatePostButton = (Button) findViewById(R.id.update_post_button);
PostDescription = (EditText)findViewById(R.id.post_description);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update Post");
SelectPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
UpdatePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ValidatePostInfo();
}
});
}
private void ValidatePostInfo() {
Description = PostDescription.getText().toString();
if (ImageUri == null){
Toast.makeText(this, "Please select the image", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(Description)){
Toast.makeText(this,"Please write something here",Toast.LENGTH_SHORT).show();
}else {
loadingBar.setTitle(" Add New Post");
loadingBar.setMessage("Please wait, while we updating your new post");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH: mm");
saveCurrentTime = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTime;
StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
downloadUrl = task.getResult().getDownloadUrl().toString();
Toast.makeText(PostActivity.this,"Image is sucessfully uploaded to storage",Toast.LENGTH_LONG).show();
SavingPostInformationToDatabase();
}else{
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this,"Error Occured:" + message,Toast.LENGTH_SHORT).show();
}
}
});
}
private void SavingPostInformationToDatabase() {
usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String userfullname = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
HashMap postsMap = new HashMap();
postsMap.put("uid",current_user_id);
postsMap.put("date",saveCurrentDate);
postsMap.put("time",saveCurrentTime);
postsMap.put("description",Description);
postsMap.put("postimage",downloadUrl);
postsMap.put("profileimage",userProfileImage);
postsMap.put("fullname",userfullname);
PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(PostActivity.this,"Your New Post is Updated Sucessfully",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}else{
Toast.makeText(PostActivity.this,"Error Occured while updating your post .please try again ",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_pick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_pick && resultCode == RESULT_OK && data != null){
ImageUri = data.getData();
SelectPostImage.setImageURI(ImageUri);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity() {
Intent mainintent = new Intent(PostActivity.this,MainActivity.class);
startActivity(mainintent);
}
}
byte[] thumb_byte_data;
Uri resultUri = ImageUri;
//getting imageUri and store in file. and compress to bitmap
File file_path = new File(resultUri.getPath());
try {
Bitmap thumb_bitmap = new Compressor(this)
.setMaxHeight(200)
.setMaxWidth(200)
.setQuality(75)
.compressToBitmap(file_path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
thumb_byte_data = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
You can then upload to firebase with the this code:
final UploadTask uploadTask = bytepath.putBytes(thumb_byte_data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
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();
}
// Continue with the task to get the download URL
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
You can create bitmap with captured image as below:
Bitmap bitmap = Bitmap.createScaledBitmap(yourimageuri, width, height, true);// the uri you got from onactivityresults
You can also view this thirdparty lib to compress your image Click Here
//declear local variable first
Bitmap bitmap;
Uri imageUri;
//button action to call Image picker method
companyImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Pick Comapany Image"),GALLERY_REQ_CODE);
}
});
//get bitmap from onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageURI(imageUri);
}
}
//compress image first then upload to firebase
public void postImage() {
StorageReference storageReference = mStorageRef.child("Images/" + //imageName);
databaseReference =
FirebaseDatabase.getInstance().getReference().child("Jobs").child(//imageName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(SaveJobActivity.this.getContentResolver(),bitmap,//imageName,null);
Uri uri = Uri.parse(path);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
final String downloadUrl = task.getResult().toString();
if (task.isSuccessful()){
Map<String, Object> update_hashMap = new HashMap<>();
//assign download url in hashmap to upadate database reference
update_hashMap.put("Image",downloadUrl);
//update database children here
databaseReference.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
//do what you want
}else {
//show exception
}
}
});
}else{
//show exception
}
}
});
}
});
}
I am trying to get the current logged in user from the google firestore database
and i saw this same problem in stackoverflow of a user and i used that same method but showing blank in place user details.
Please help me Thanks.
I am earlier using querysnapshot as it gives all the users.
image description here
the image for database is
enter image description here
The code is:
public class UserProfile extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int GALLERY_INTENT = 2;
private static final String TAG = "UserProfile";
String UserId;
FirebaseAuth auth;
ImageButton Photo;
ImageView photoview;
TextView name, email, password, phone;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
if(getSupportActionBar()!=null ){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DatabaseReference Database = FirebaseDatabase.getInstance().getReference("users");
DatabaseReference DBRef = Database.child("users");
auth = FirebaseAuth.getInstance();
UserId = auth.getCurrentUser().getUid();
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
StorageReference mStorage = FirebaseStorage.getInstance().getReference();
FirebaseStorage storage = FirebaseStorage.getInstance();
photoview = (ImageView)findViewById(R.id.photoview);
Photo = (ImageButton)findViewById(R.id.Photoedit);
name = (TextView)findViewById(R.id.username);
email = (TextView)findViewById(R.id.useremail);
password = (TextView)findViewById(R.id.password1);
phone = (TextView)findViewById(R.id.userPhone);
mFirestore.collection("users").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String Name = documentSnapshot.getString("Name");
String Email = documentSnapshot.getString("Email");
String Password = documentSnapshot.getString("Password");
String Phone = documentSnapshot.getString("Phone Number");
name.setText(Name);
email.setText(Email);
password.setText(Password);
phone.setText(Phone);
}
});
Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_INTENT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
photoview.setImageBitmap(photo);
} else if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
photoview.setImageBitmap(thumbnail);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent i = new Intent(UserProfile.this,category.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
My database structure is
Ramiki(my app name)
So here it is
Ramiki --> users(collection)--> SiQEIDaQJfUBqZBBt1eo(document uid)----> fields(Email, Name, Password, Phone Number).
Well sorry i am not able to give screenshort because i am not allowed by stack overflow 10 points needed.
And my code for writing data in firestore is
public class LoginActivity extends AppCompatActivity implements View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LoginActivity";
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private TextInputEditText textInputEditTextPhone;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private FirebaseAuth auth;
private ProgressBar progressBar;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private SignInButton btnSignIn;
private FirebaseFirestore mFirebaseFirestore;
private FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
mFirebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build();
mFirebaseFirestore.setFirestoreSettings(settings);
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
}
};
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignIn.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
appCompatTextViewLoginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, account.class);
startActivity(i);
finish();
}
});
//if the user is already logged in we will directly start the category activity
if (SavesharedPreferences.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, category.class));
finish();
return;
}
findViewById(R.id.appCompatButtonRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("Name", Name);
user.put("Email", Email);
user.put("Password", Password);
user.put("Phone Number", Phone_Number);
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if(Password.length() < 7){
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!textInputEditTextPassword.getText().toString().equals(textInputEditTextConfirmPassword.getText().toString())) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else {
// Add a new document with a generated ID
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
registerUser();
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
}
});
initViews();
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
}
}
private void registerUser() {
final String Name = textInputEditTextName.getText().toString().trim();
final String Email = textInputEditTextEmail.getText().toString().trim();
final String Password = textInputEditTextPassword.getText().toString().trim();
final String Phone_Number = textInputEditTextPhone.getText().toString().trim();
final String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
return;
}
if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
return;
}
if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
return;
}
if(Password.length() < 7 ) {
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
return;
}
if (TextUtils.isEmpty(ConfirmPassword)) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this, "Register Successful " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
sendEmailVerification();
}
// 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.
else if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Nothing Happens", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Please Check Your Email For Verification",Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(LoginActivity.this, account.class));
finish();
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private void initViews() {
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextPhone = (TextInputEditText) findViewById(R.id.textInputEditTextPhone);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this, "You Got an Error",Toast.LENGTH_LONG).show();
}
protected void onStart(){
super.onStart();
auth.addAuthStateListener(authListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
This unique id SiQEIDaQJfUBqZBBt1eo is generated when you are adding the user as a Map or when you are using a call to document() method without passing an argument.
In order to solve this, there are two ways. One would be to create a model class (UserModel), then create an object of that class and in the end get the uid of the user once it authenticated and add the object to the database like this:
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
UserModel userModel = new UserModel(Name, Email, Password, Phone_Number, ConfirmPassword);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(userModel);
See, I have passed the uid as argument to the document() method.
The second approach would be to pass no argument to the document() method but to store that key into a variable like this:
String key = usersRef.document().getKey();
usersRef.document(key).set(userModel);
Edit:
There also another method, which I recommend you use it. Instead of using this line of code:
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(/* ... */)
Use the following line of code:
mFirebaseFirestore.collection("users")
.document(uid)
.set(user)
.addOnSuccessListener(/* ... */)
Remove the old data, add fresh one and your problem will be solved.