firebase / quickstart-android

Firebase Quickstart Samples for Android
https://firebase.google.com
Apache License 2.0
8.85k stars 7.32k forks source link

Firestore cannot store data Error Handler #566

Closed bradridsect closed 6 years ago

bradridsect commented 6 years ago

i got problem in firebase storage. I make a project there is no error with take picture and store it in firestore. The image uploaded but the firestore show error .

Here is my code

package my.wedee.com.wedeeon9bisnis;

                import android.Manifest;
                import android.content.Context;
                import android.content.Intent;
                import android.content.pm.PackageManager;
                import android.net.Uri;
                import android.os.Build;
                import android.support.annotation.NonNull;
                import android.support.v4.app.ActivityCompat;
                import android.support.v4.content.ContextCompat;
                import android.support.v7.app.AppCompatActivity;
                import android.os.Bundle;
                import android.support.v7.widget.Toolbar;
                import android.text.TextUtils;
                import android.view.MenuItem;
                import android.view.MotionEvent;
                import android.view.View;
                import android.view.inputmethod.InputMethodManager;
                import android.widget.Button;
                import android.widget.EditText;
                import android.widget.ProgressBar;
                import android.widget.Toast;

                import com.bumptech.glide.Glide;
                import com.bumptech.glide.request.RequestOptions;
                import com.google.android.gms.tasks.OnCompleteListener;
                import com.google.android.gms.tasks.OnFailureListener;
                import com.google.android.gms.tasks.Task;
                import com.google.firebase.auth.FirebaseAuth;
                import com.google.firebase.firestore.DocumentSnapshot;
                import com.google.firebase.firestore.FirebaseFirestore;
                import com.google.firebase.storage.FirebaseStorage;
                import com.google.firebase.storage.StorageReference;
                import com.theartofdev.edmodo.cropper.CropImage;
                import com.theartofdev.edmodo.cropper.CropImageView;

                import java.util.HashMap;
                import java.util.Map;

                import de.hdodenhof.circleimageview.CircleImageView;

                public class EditProfileActivity extends AppCompatActivity {

                    private EditText fullNameOwner, emailBiz, locationBiz;
                    private CircleImageView profileImage;
                    private Button SaveInformation;
                    private ProgressBar progressBar;

                    private Uri mainImageURI = null;

                    private FirebaseAuth mAuth;
                    private StorageReference storageReference;
                    private FirebaseFirestore mFireStore;

                    private String currentUserId;

                    private Boolean isChanged = false;
                    private Uri download_uri;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_edit_profile);

                        //firebase
                        mAuth = FirebaseAuth.getInstance();
                        mFireStore = FirebaseFirestore.getInstance();
                        storageReference = FirebaseStorage.getInstance().getReference();

                        currentUserId = mAuth.getCurrentUser().getUid();
                        progressBar = findViewById(R.id.progressBarEditProfile);

                        //toolbar
                        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarEditInfo); // get the reference of Toolbar
                        toolbar.setTitle("Account Personal Info"); // set Title for Toolbar
                        setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar

                        // add back arrow to toolbar
                        if (getSupportActionBar() != null) {
                            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                            getSupportActionBar().setDisplayShowHomeEnabled(true);
                        }

                        //findviewbyID
                        fullNameOwner = findViewById(R.id.editTextFullnameBiz);
                        emailBiz = findViewById(R.id.editTextEmailBiz);
                        locationBiz = findViewById(R.id.editTextLocationBiz);
                        profileImage = findViewById(R.id.profile_image_edit);
                        SaveInformation = findViewById(R.id.buttonSaveInfoEdit);

                        progressBar.setVisibility(View.VISIBLE);
                        mFireStore.collection("Profile On9Biz").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

                            @Override
                            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                                if (task.isSuccessful()) {

                                    if (task.getResult().exists()) {

                                        String fullname = task.getResult().getString("fullname");
                                        String email = task.getResult().getString("email");
                                        String location = task.getResult().getString("location");
                                        String image = task.getResult().getString("profile_images");

                                        mainImageURI = Uri.parse(image);

                                        fullNameOwner.setText(fullname);
                                        emailBiz.setText(email);
                                        locationBiz.setText(location);

                                        RequestOptions placeholderRequest = new RequestOptions();
                                        placeholderRequest.placeholder(R.drawable.profile);

                                        Glide.with(EditProfileActivity.this).setDefaultRequestOptions(placeholderRequest).load(image).into(profileImage);

                                        progressBar.setVisibility(View.INVISIBLE);

                                    }

                                } else {

                                    String errorMsg = task.getException().getMessage();
                                    Toast.makeText(EditProfileActivity.this, "Firebase Error :" + errorMsg, Toast.LENGTH_LONG).show();
                                }

                            }
                        });

                        SaveInformation.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                progressBar.setVisibility(View.VISIBLE);

                                final String full_nameBiz = fullNameOwner.getText().toString().trim();
                                final String email_Ob = emailBiz.getText().toString().trim();
                                final String location_Ob = locationBiz.getText().toString().trim();

                                if (!TextUtils.isEmpty(full_nameBiz) && !TextUtils.isEmpty(email_Ob) && !TextUtils.isEmpty(location_Ob) && mainImageURI != null) {

                                    StorageReference image_path = storageReference.child("profile_images").child(currentUserId + ".jpg");
                                    image_path.putFile(mainImageURI);
                                    storageReference.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Uri> task) {
                                            if (task.isSuccessful()) {

                                                download_uri = task.getResult();

                                                StoreFireStore(task,full_nameBiz,email_Ob,location_Ob);

                                            } else {

                                                String errorMsg = task.getException().getMessage();
                                                Toast.makeText(EditProfileActivity.this, "Internet Connection Error :" + errorMsg, Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    }).addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {

                                            Toast.makeText(EditProfileActivity.this, "Failed", Toast.LENGTH_SHORT).show();

                                        }
                                    });
                                    progressBar.setVisibility(View.INVISIBLE);

                                }

                            }
                        });

                        profileImage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                                    if (ContextCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                                        Toast.makeText(EditProfileActivity.this, "Permission Denied...", Toast.LENGTH_SHORT).show();
                                        ActivityCompat.requestPermissions(EditProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

                                    } else {

                                        BringImagePicker();

                                    }

                                } else {

                                    BringImagePicker();

                                }

                            }
                        });

                    }

                    private void StoreFireStore(@NonNull Task<Uri> task, String full_nameBiz, String email_Ob, String location_Ob) {

                        Map<String, String> userMap = new HashMap<>();
                        userMap.put("fullname", full_nameBiz);
                        userMap.put("email", email_Ob);
                        userMap.put("location", location_Ob);
                        userMap.put("profile_images", download_uri.toString());

                        mFireStore.collection("Profile On9Biz").document(currentUserId).set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                                if (task.isSuccessful()) {

                                    Toast.makeText(EditProfileActivity.this, "Data Has Been Stored..", Toast.LENGTH_LONG).show();

                                    SentToProfile();

                                } else {

                                    String errorMsg = task.getException().getMessage();
                                    Toast.makeText(EditProfileActivity.this, "Firebase Error :" + errorMsg, Toast.LENGTH_LONG).show();

                                }

                                progressBar.setVisibility(View.VISIBLE);

                            }

                        });

                    }

                    private void SentToProfile() {

                        Intent nextIntent = new Intent(EditProfileActivity.this, ProfileActivity.class);
                        nextIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(nextIntent);
                    }

                    @Override
                    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                        super.onActivityResult(requestCode, resultCode, data);

                        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                            CropImage.ActivityResult result = CropImage.getActivityResult(data);
                            if (resultCode == RESULT_OK) {

                                mainImageURI = result.getUri();
                                profileImage.setImageURI(mainImageURI);

                            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                                Exception error = result.getError();
                                Toast.makeText(this, "Error :" + error, Toast.LENGTH_SHORT).show();

                            }
                        }

                    }

                    //hidekeyboard
                    @Override
                    public boolean onTouchEvent(MotionEvent event) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                        return true;
                    }

                    //backButton
                    @Override
                    public boolean onOptionsItemSelected(MenuItem item) {
                        // handle arrow click here
                        if (item.getItemId() == android.R.id.home) {
                            SentToProfile(); // close this activity and return to preview activity (if there is any)
                        }

                        return super.onOptionsItemSelected(item);
                    }

                    private void BringImagePicker() {

                        CropImage.activity()
                                .setGuidelines(CropImageView.Guidelines.ON)
                                .setAspectRatio(1, 1)
                                .start(EditProfileActivity.this);

                    }
                }

Before this .. the firestore can store it but after i fix the image getdownloadUrl(), the image didnt uploaded into storage. After i fix it , the image can upload then firestore show the error handler. I hope somebody can help me.

samtstern commented 6 years ago

@bradridsect it's not clear what your issue is. What is the error you are seeing and what did you expect to happen?

bradridsect commented 6 years ago

The thing is i can store the image lnto storage. But when im try to open the link in firestore.. its show an error

samtstern commented 6 years ago

@bradridsect I'm sorry I still don't understand. Which line of code produces the error, what did you expect it to do?

bradridsect commented 6 years ago
 `package my.wedee.com.wedeeon9bisnis;

        import android.Manifest;
        import android.content.Context;
        import android.content.Intent;
        import android.content.pm.PackageManager;
        import android.net.Uri;
        import android.os.Build;
        import android.support.annotation.NonNull;
        import android.support.v4.app.ActivityCompat;
        import android.support.v4.content.ContextCompat;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.support.v7.widget.Toolbar;
        import android.text.TextUtils;
        import android.util.Log;
        import android.view.MenuItem;
        import android.view.MotionEvent;
        import android.view.View;
        import android.view.inputmethod.InputMethodManager;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ProgressBar;
        import android.widget.Toast;

        import com.bumptech.glide.Glide;
        import com.bumptech.glide.request.RequestOptions;
        import com.google.android.gms.tasks.OnCompleteListener;
        import com.google.android.gms.tasks.OnFailureListener;
        import com.google.android.gms.tasks.OnSuccessListener;
        import com.google.android.gms.tasks.Task;
        import com.google.firebase.auth.FirebaseAuth;
        import com.google.firebase.firestore.DocumentReference;
        import com.google.firebase.firestore.DocumentSnapshot;
        import com.google.firebase.firestore.FirebaseFirestore;
        import com.google.firebase.storage.FirebaseStorage;
        import com.google.firebase.storage.StorageReference;
        import com.google.firebase.storage.UploadTask;
        import com.theartofdev.edmodo.cropper.CropImage;
        import com.theartofdev.edmodo.cropper.CropImageView;

        import java.util.HashMap;
        import java.util.Map;

        import de.hdodenhof.circleimageview.CircleImageView;

        public class EditProfileActivity extends AppCompatActivity {

            private static final String TAG = "FireLog";
            private EditText fullNameOwner, emailBiz, locationBiz;
            private CircleImageView profileImage;
            private Button SaveInformation;
            private ProgressBar progressBar;

            private Uri mainImageURI = null;

            private FirebaseAuth mAuth;
            private StorageReference storageReference;
            private FirebaseFirestore mFireStore;

            private String currentUserId;

            private Boolean isChanged = false;
            private Uri download_uri;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_edit_profile);

                //firebase
                mAuth = FirebaseAuth.getInstance();
                mFireStore = FirebaseFirestore.getInstance();
                storageReference = FirebaseStorage.getInstance().getReference();

                currentUserId = mAuth.getCurrentUser().getUid();
                progressBar = findViewById(R.id.progressBarEditProfile);

                //toolbar
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarEditInfo); // get the reference of Toolbar
                toolbar.setTitle("Account Personal Info"); // set Title for Toolbar
                setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar

                // add back arrow to toolbar
                if (getSupportActionBar() != null) {
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setDisplayShowHomeEnabled(true);
                }

                //findviewbyID
                fullNameOwner = findViewById(R.id.editTextFullnameBiz);
                emailBiz = findViewById(R.id.editTextEmailBiz);
                locationBiz = findViewById(R.id.editTextLocationBiz);
                profileImage = findViewById(R.id.profile_image_edit);
                SaveInformation = findViewById(R.id.buttonSaveInfoEdit);

                progressBar.setVisibility(View.VISIBLE);
                mFireStore.collection("Profile On9Biz").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                        if (task.isSuccessful()) {

                            if (task.getResult().exists()) {

                                String fullname = task.getResult().getString("fullname");
                                String email = task.getResult().getString("email");
                                String location = task.getResult().getString("location");
                                String image = task.getResult().getString("profile_images");

                                mainImageURI = Uri.parse(image);

                                fullNameOwner.setText(fullname);
                                emailBiz.setText(email);
                                locationBiz.setText(location);

                                RequestOptions placeholderRequest = new RequestOptions();
                                placeholderRequest.placeholder(R.drawable.profile);

                                Glide.with(EditProfileActivity.this).setDefaultRequestOptions(placeholderRequest).load(image).into(profileImage);

                                progressBar.setVisibility(View.INVISIBLE);

                            }

                        } else {

                            String errorMsg = task.getException().getMessage();
                            Toast.makeText(EditProfileActivity.this, "Firebase Error :" + errorMsg, Toast.LENGTH_LONG).show();
                        }

                    }
                });

                SaveInformation.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        progressBar.setVisibility(View.VISIBLE);

                        final String full_nameBiz = fullNameOwner.getText().toString().trim();
                        final String email_Ob = emailBiz.getText().toString().trim();
                        final String location_Ob = locationBiz.getText().toString().trim();

                        if (!TextUtils.isEmpty(full_nameBiz) && !TextUtils.isEmpty(email_Ob) && !TextUtils.isEmpty(location_Ob) && mainImageURI != null) {

                            if (isChanged) {

                                StorageReference image_path = storageReference.child("profile_images").child(currentUserId + ".jpg");
                                image_path.putFile(mainImageURI);
                                image_path.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Uri> task) {
                                        if (task.isSuccessful()) {

                                            download_uri = task.getResult();

                                            Storefirestore(task, full_nameBiz, email_Ob, location_Ob);
                                        }
                                    }
                                });
                            } else {

                                Storefirestore(null, full_nameBiz, email_Ob, location_Ob);
                            }

                        } else {

                            Toast.makeText(EditProfileActivity.this, "Failed La BABI", Toast.LENGTH_SHORT).show();
                        }
                        progressBar.setVisibility(View.INVISIBLE);

                    }
                });

                profileImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                            if (ContextCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                                Toast.makeText(EditProfileActivity.this, "Permission Denied...", Toast.LENGTH_SHORT).show();
                                ActivityCompat.requestPermissions(EditProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

                            } else {

                                BringImagePicker();

                            }

                        } else {

                            BringImagePicker();

                        }

                    }
                });

            }

            private void Storefirestore(@NonNull final Task<Uri> task, String full_nameBiz, String email_Ob, String location_Ob) {

                Map<String, String> userMap = new HashMap<>();
                userMap.put("fullname", full_nameBiz);
                userMap.put("email", email_Ob);
                userMap.put("location", location_Ob);
                userMap.put("profile_images", download_uri.toString());

                mFireStore.collection("Profile On9Biz").document(currentUserId).set(userMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        if (task.isSuccessful()) {
                            Log.d(TAG, "DocumentSnapshot successfully written!");

                            Toast.makeText(EditProfileActivity.this, "Profile Has Been Stored at firebase", Toast.LENGTH_SHORT).show();
                            SentToProfile();

                        } else {

                            String errorMsg = task.getException().getMessage();
                            Toast.makeText(EditProfileActivity.this, "Firebase Error :" + errorMsg, Toast.LENGTH_LONG).show();

                        }

                    }
                });
            }

            private void SentToProfile() {

                Intent nextIntent = new Intent(EditProfileActivity.this, ProfileActivity.class);
                nextIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(nextIntent);
            }

            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);

                if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                    CropImage.ActivityResult result = CropImage.getActivityResult(data);
                    if (resultCode == RESULT_OK) {

                        mainImageURI = result.getUri();
                        profileImage.setImageURI(mainImageURI);

                    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                        Exception error = result.getError();
                        Toast.makeText(this, "Error :" + error, Toast.LENGTH_SHORT).show();

                    }
                }

            }

            //hidekeyboard
            @Override
            public boolean onTouchEvent(MotionEvent event) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                return true;
            }

            //backButton
            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                // handle arrow click here
                if (item.getItemId() == android.R.id.home) {
                    SentToProfile(); // close this activity and return to preview activity (if there is any)
                }

                return super.onOptionsItemSelected(item);
            }

            private void BringImagePicker() {

                CropImage.activity()
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAspectRatio(1, 1)
                        .start(EditProfileActivity.this);

            }
        }

` here is my new code that i already fix the error . Its successful upload the picture into storage and i got the link store into firestore. But when i trying to open the picture link is show like this

https://firebasestorage.googleapis.com/v0/b/authwarisan.appspot.com/o/profile_images%2Ftap3U7pG4tdK45fySzkXzvqpOC12.jpg?alt=media&token=e0696700-dcf1-4728-a71c-32e7c7adad05

{ "error": { "code": 403, "message": "Permission denied. Could not perform this operation" } }

samtstern commented 6 years ago

So the issue is that the result of getDownloadUrl still 403s?

bradridsect commented 6 years ago

yes.. that error .. how can i fix it?

bradridsect commented 6 years ago
`service cloud.firestore {
  match /databases/{database}/documents {
     match /{document=**} {
     allow read, write: if request.auth != null;
    }
 }
 }`

this is my rules in firestore

samtstern commented 6 years ago

@bradridsect can you show the rules you're using for Storage? I think those may be what is causing the problem.

bradridsect commented 6 years ago
service firebase.storage {
          match /b/{bucket}/o {
          match /{allPaths=**} {
          allow read, write: if request.auth != null;
           }
        }
     }
samtstern commented 6 years ago

@bradridsect this is very strange, I will have to follow up.

samtstern commented 6 years ago

@bradridsect the URL you posted now works for me, so maybe there is no bug anymore and it was just a problem in your code?

bradridsect commented 6 years ago

i put the permission on storage allow read, write: true; and now im also get see the picture.. btw ,, thanks mate..

samtstern commented 6 years ago

@bradridsect ok so we have determined that it's a rules issue. You should be able to go back to the request.auth != null rules if you can ensure that you're logged in when you try to create / read links.

Since we've narrowed it down to changes you can make in your code I am going to close this issue (it's not an issue with the sample or an SDK bug) but feel free to reply to discuss more.