我正在尝试在Firebase上上传图像。但是,当我选择要上传的图片时,它会在烤面包上给我一些错误消息。
Error:com.google.firebase.storage.StorageException:未知错误 发生,请检查HTTP结果代码和内部异常 服务器响应。
我的代码如下
SettingsActivity.java:
package com.example.whatsapp2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button UpdateAccountSetting;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserId;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
private Toolbar SettingsToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSetting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
});
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("image"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Please set & update your profile information...",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this,"Please write your user name first....",Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)) {
Toast.makeText(this,"Please write your status....",Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserId);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserId).updateChildren(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(getApplicationContext(),"Profile Updated Successfully...",Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error : "+message,Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void InitializeFields() {
UpdateAccountSetting = findViewById(R.id.update_settings_button);
userName = findViewById(R.id.set_user_name);
userStatus =findViewById(R.id.set_profile_status);
userProfileImage = findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
SettingsToolbar = findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserId+".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Profile Image uploaded Successfully...",Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
}
我的Gradle文件
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.whatsapp2"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.google.firebase:firebase-messaging:17.3.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-auth:16.0.3'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'
implementation 'de.hdodenhof:circleimageview:3.0.0'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.firebaseui:firebase-ui-database:3.2.2'
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
如何解决此错误?谁能帮我吗?