我必须将某些INFO上载到实时数据库中。所有详细信息均已正确上传到其中,但图像网址已作为com.google.android.gms.tasks.zzu@****上传。文件已正确上传到存储中。代码添加如下。
主要活动
package com.example.firebase1;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
// Folder path for Firebase Storage.
String Storage_Path = "All_Image_Uploads/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
// Creating button.
Button ChooseButton, UploadButton, DisplayImageButton;
// Creating EditText.
EditText ImageName ;
// Creating ImageView.
ImageView SelectImage;
// Creating URI.
Uri FilePathUri;
// Creating StorageReference and DatabaseReference object.
StorageReference storageReference;
DatabaseReference databaseReference;
// Image request code for onActivityResult() .
int Image_Request_Code = 7;
ProgressDialog progressDialog ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign FirebaseStorage instance to storageReference.
storageReference = FirebaseStorage.getInstance().getReference();
// Assign FirebaseDatabase instance with root database name.
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
//Assign ID'S to button.
ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
UploadButton = (Button)findViewById(R.id.ButtonUploadImage);
DisplayImageButton = (Button)findViewById(R.id.DisplayImagesButton);
// Assign ID's to EditText.
ImageName = (EditText)findViewById(R.id.ImageNameEditText);
// Assign ID'S to image view.
SelectImage = (ImageView)findViewById(R.id.ShowImageView);
// Assigning Id to ProgressDialog.
progressDialog = new ProgressDialog(MainActivity.this);
// Adding click listener to Choose image button.
ChooseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Creating intent.
Intent intent = new Intent();
// Setting intent type as image to select image from phone storage.
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_Request_Code);
}
});
// Adding click listener to Upload image button.
UploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Calling method to upload selected image on Firebase storage.
UploadImageFileToFirebaseStorage();
}
});
DisplayImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, DisplayImagesActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Image_Request_Code && resultCode == RESULT_OK && data != null && data.getData() != null) {
FilePathUri = data.getData();
try {
// Getting selected image into Bitmap.
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
// Setting up bitmap selected image into ImageView.
SelectImage.setImageBitmap(bitmap);
// After selecting image change choose button above text.
ChooseButton.setText("Image Selected");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
// Creating Method to get the selected image file Extension from File Path URI.
public String GetFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
// Returning the file Extension.
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;
}
// Creating UploadImageFileToFirebaseStorage method to upload image on storage.
public void UploadImageFileToFirebaseStorage() {
// Checking whether FilePathUri Is empty or not.
if (FilePathUri != null) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
// Showing progressDialog.
progressDialog.show();
// Creating second StorageReference.
StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));
// Adding addOnSuccessListener to second StorageReference.
storageReference2nd.putFile(FilePathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Getting image name from EditText and store into string variable.
String TempImageName = ImageName.getText().toString().trim();
// Hiding the progressDialog after done uploading.
progressDialog.dismiss();
// Showing toast message after done uploading.
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
@SuppressWarnings("VisibleForTests")
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getStorage().getDownloadUrl().toString());
// Getting image upload ID.
String ImageUploadId = databaseReference.push().getKey();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
}
})
// If something goes wrong .
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Hiding the progressDialog.
progressDialog.dismiss();
// Showing exception erro message.
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
// On progress change upload time.
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
}
});
}
else {
Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}
}
}
示例数据库URL com.google.android.gms.tasks.zzu@441922b
这是我的活动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"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Firebase Image Upload Tutorial"
android:id="@+id/textview"
android:textStyle="bold"
android:textSize="20dp"
android:gravity="center"
android:layout_marginTop="20dp"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="150dp"
android:id="@+id/ShowImageView"
android:layout_below="@+id/textview"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/ButtonChooseImage"
android:layout_below="@+id/ShowImageView"
android:layout_marginTop="20dp"
android:text="Choose Image"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/ImageNameEditText"
android:layout_below="@+id/ButtonChooseImage"
android:layout_marginTop="20dp"
android:hint="Enter Image Name Here"
android:gravity="center"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/ButtonUploadImage"
android:layout_below="@+id/ImageNameEditText"
android:layout_marginTop="20dp"
android:text="Upload image to Firebase Storage"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:id="@+id/DisplayImagesButton"
android:layout_below="@+id/ButtonUploadImage"
android:text="Show All Uploaded Images"/>
我还将感谢您在RecyclerView中垂直或水平显示所有图像的帮助