我正在制作一个类似于社交媒体应用程序的android应用程序但是当我尝试从图库或摄像机中放入图像作为配置文件或封面时,会发生此问题。
我希望用户从他的画廊中选择照片或使用相机拍摄新照片,然后将图像上传到Firebase存储。
用户无权使用Firebase存储访问此对象。
有我的权限..
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
我的Java代码:
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
String storagePath = "Uers_Profile_Cover_Imgs/";
ImageView avatartv, coverTv;
TextView nameTv, emailTv, phoneTv;
FloatingActionButton fab;
ProgressDialog pd;
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
String cameraPermissions[];
String storagePermission[];
Uri image_uri;
String profileOrCoverPhoto;
public ProfileFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference = getInstance().getReference();
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
avatartv = view.findViewById(R.id.avatarTv);
coverTv = view.findViewById(R.id.coverTv);
nameTv = view.findViewById(R.id.name);
emailTv = view.findViewById(R.id.category);
phoneTv = view.findViewById(R.id.location);
fab = view.findViewById(R.id.fab);
pd = new ProgressDialog(getActivity());
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = "" + ds.child("name").getValue();
String image = "" + ds.child("image").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String cover = "" + ds.child("cover").getValue();
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
try {
Picasso.get().load(image).into(avatartv);
} catch (Exception e) {
Picasso.get().load(R.drawable.ic_add_a_photo_black_24dp).into(avatartv);
}
try {
Picasso.get().load(cover).into(coverTv);
} catch (Exception e) {
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditProfileDialog();
}
});
return view;
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission() {
requestPermissions(storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
String options[] = {"Edit Profile Picture", "Edit Cover Photo", "Edit Name", "Edit Phone"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Action");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
pd.setMessage("Updating Profile Picture");
profileOrCoverPhoto = "image";
showImagePicDialog();
} else if (which == 1) {
pd.setMessage("Updating Cover Picture");
profileOrCoverPhoto = "cover";
showImagePicDialog();
} else if (which == 2) {
pd.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
} else if (which == 3) {
pd.setMessage("Updating Phone");
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(String Key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Updated " + Key);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10, 10, 10, 10);
EditText editText = new EditText(getActivity());
editText.setHint("Enter " + Key);
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(Key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
private void showImagePicDialog() {
String options[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
} else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickFromCamera();
} else {
Toast.makeText(getActivity(), "Please Enable Camera & Storage Permission", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickFromGallery();
} else {
Toast.makeText(getActivity(), "Please Enable Storage Permission", Toast.LENGTH_SHORT).show();
}break;
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverPhoto(Uri uri) {
String filePathAndName = storagePath + "" + profileOrCoverPhoto + "_" + user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
Uri downloadUri = uriTask.getResult();
if (uriTask.isSuccessful()) {
HashMap<String, Object> results = new HashMap<>();
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Image Updated ...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "Error Updating Image ...", Toast.LENGTH_SHORT).show();
}
});
} else {
pd.dismiss();
Toast.makeText(getActivity(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
XML代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProfileFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/coverTv"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#FFA117">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="90dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/avatarTv"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:background="@color/colorPrimaryDark"
android:scaleType="fitXY"
app:srcCompat="@drawable/face" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#B67310"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="25sp" />
<TextView
android:id="@+id/category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="15dp" />
<TextView
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#fff"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:src="@drawable/editpen"
app:backgroundTint="#FFA117" />
</RelativeLayout>
FIrebase安全规则:
service firebase.storage {
match /b/learno-fc8fc.appspot.com/o {
// Allow access by all users
allow read, write;
}
您能否正确检查存储桶名称?
搜索后,我找到了解决方案..我在Firebase中的规则不正确..
我们应该那样做..
service firebase.storage
{ match /b/learno-fc8fc.appspot.com/o
{ match /{allPaths=**}
{ // Allow access by all users
allow read, write; }