Я не могу загрузить одно изображение, используя EXTRA_ALLOW_MULTPLE, но я могу загрузить несколько изображений, используя этот метод.
это должно позволить мне загружать одно или несколько изображений.
загружая код этой функции для справки ниже:
Это главный 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=".function.albums.AlbumMediaListActivity">
<GridView
android:id="@+id/fileList_gv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/addPhotos_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:contentDescription="+"
android:backgroundTint="@color/colorPrimaryDark"
android:src="@android:drawable/ic_input_add"
android:tint="@android:color/white"
android:layout_margin="16dp" />
</RelativeLayout>
это Java Код:
package com.example.thakirni.function.albums;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;
import com.example.thakirni.R;
import com.example.thakirni.model.AlbumMedia;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
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 java.util.ArrayList;
import java.util.UUID;
public class AlbumMediaListActivity extends AppCompatActivity {
private FloatingActionButton addPhotos_btn;
private int CODE_MULTIPLE_IMG_GALLERY = 2;
private ArrayList<Uri> ImageList = new ArrayList<>();
private Uri imageUri;
private ProgressDialog progressDialog;
private String albumID, albumThumbnail;
String url;
private GridView fileList_gv;
private ArrayList<AlbumMedia> albumMediaArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_album_media_list);
// getting values from previous activity
url = "";
Intent intent = getIntent();
albumID = intent.getStringExtra("albumID");
albumThumbnail = intent.getStringExtra("albumThumbnail");
// finding XML Reference of activity
addPhotos_btn = findViewById(R.id.addPhotos_btn);
fileList_gv = findViewById(R.id.fileList_gv);
/*************************************************************/
// initializing ProgressDialog and setting its message
progressDialog = new ProgressDialog(AlbumMediaListActivity.this);
progressDialog.setMessage("Uploading Files Please Wait......");
// Printing all images from Album
printAlbumFromFirebase();
// This button will start Gallery Screen and allow user to select files
and will result in uploading them to firebase
addPhotos_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("*/*"); // this means all types of files in
gallery should be visible
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); // allow to
select multiple files together
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
Multiple Files"), CODE_MULTIPLE_IMG_GALLERY);
}
});
}
// This Function Will print all Images and display in album
private void printAlbumFromFirebase() {
progressDialog.setMessage("Loading Album Please Wait!...");
progressDialog.show();
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference fileRef =
database.getReference("albumMedia").child(albumID);
fileRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
albumMediaArrayList = new ArrayList<>();
for (DataSnapshot postSnapshot :
dataSnapshot.getChildren()) {
AlbumMedia albumMedia =
postSnapshot.getValue(AlbumMedia.class);
albumMediaArrayList.add(albumMedia);
}
fileList_gv.setAdapter(new
AlbumMediaListAdapter(AlbumMediaListActivity.this, albumMediaArrayList));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
progressDialog.cancel();
}
// This function will return Links of files that will be uploaded to
Firebase and then run openUploadDialog Function
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CODE_MULTIPLE_IMG_GALLERY && resultCode == RESULT_OK)
{
ClipData clipData = data.getClipData();
if(data.getClipData() != null){
// getting count of how many images selected
int countClipData = data.getClipData().getItemCount();
int currentImageSelect = 0;
// running loop to increment images and add them to ArrayList
while(currentImageSelect < countClipData)
{
imageUri =
data.getClipData().getItemAt(currentImageSelect).getUri();
ImageList.add(imageUri);
currentImageSelect += 1;
}
}
// Opening Loading
openUploadDialog();
}
}
// this will upload images to Firebase Storage and will run the
uploadFilesPathToFirebase function
private void openUploadDialog() {
// Showing Progress Dialog
progressDialog.show();
// Running Loop to upload multiple Images 1 by 1
for(int i=0; i < ImageList.size(); i++)
{
StorageReference ImageFolder =
FirebaseStorage.getInstance().getReference().child("Files/"+ albumID + "/"
+
UUID.randomUUID().toString());
ImageFolder.putFile(ImageList.get(i)).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Getting URL of each Image
url = String.valueOf(taskSnapshot.getDownloadUrl());
uploadFilesPathToFirebase(url);
}
}).addOnCompleteListener(new
OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot>
task) {
progressDialog.dismiss();
}
});
}
Toast.makeText(AlbumMediaListActivity.this, "Files Uploaded
Successfully", Toast.LENGTH_SHORT).show();
}
// this function will upload values to firebase and update album Cover
using
updateAlbumCover Function
private void uploadFilesPathToFirebase(final String downloadUrl) {
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference photoRef = database.getReference("albumMedia");
// Setting Firebase Values
AlbumMedia albumMedia = new AlbumMedia();
albumMedia.setFileUrl(downloadUrl);
// this will add File Information to Firebase
photoRef.child(albumID).child(photoRef.push().getKey()).
setValue(albumMedia).ad
dOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
if(albumThumbnail.equalsIgnoreCase(""))
{
updateAlbumCover(downloadUrl);
}
}
});
}
// this function will update albumCover from UploadFilesPathToFirebase
function
private void updateAlbumCover(String thumArt) {
FirebaseDatabase database2 = FirebaseDatabase.getInstance();
DatabaseReference albumRef =
database2.getReference("album").child(albumID);
// this will update albumThumbnail
albumRef.child("albumThumbnail").setValue(thumArt);
}
}