0
I am developing an app, this app the user can already choose multiple images, but I am not able to upload the images chosen automatically to Firebase Storage. The user can already authenticate. Someone can help me, how to do this upload process and create together folder that will store the images through each id already authenticated?
public class TelaverGaleriaActivity extends AppCompatActivity {
private static final int SELECAO_GALERIA = 1;
Button botaoGaleria;
private StorageReference storageReference;
private String identificadorUsuario;
private List<String> listaFotosRecuperadas = new ArrayList<>();
//solicitacao de permissao
private String[] permissoesNecessarias = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_telaver_galeria);
//configurações iniciais
storageReference = ConfiguracaoFireBase.getReferenciaStorage();
identificadorUsuario = UsuarioFirebase.getIdentificadorUsuario();
//validar as permissoes
Permissao.validarPermissoes(permissoesNecessarias, this, 1);
botaoGaleria = findViewById(R.id.botaoParaGaleria);
//criar evento onclick para que o usuario tenha acesso a galeria clicando no botao
botaoGaleria.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Selecione Imagem"), SELECAO_GALERIA);
}
});
}
//pegar as varias foto que o usuario selecionou ok ok ok
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECAO_GALERIA) {
if (resultCode == TelaverGaleriaActivity.RESULT_OK) {
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
Log.i("count", String.valueOf(count));
int currentItem = 0;
while (currentItem < count) {
Uri imagemUri = data.getClipData().getItemAt(currentItem).getUri();
Log.i("uri", imagemUri.toString());
listaFotosRecuperadas.add(String.valueOf(imagemUri));
currentItem = currentItem + 1;
}
Log.i("listsize", String.valueOf(listaFotosRecuperadas.size()));
} else if (data.getData() != null) {
String imagePath = data.getData().getPath();
} else if (listaFotosRecuperadas.size() != 5){
exibirMensagemErro("Selecione pelo menos cinco fotos");
}
Uri imagemUri = Uri.fromFile(new File("imagens.jpg"));
StorageReference firebaseRef = storageReference.child( storageReference +imagemUri.getLastPathSegment());
StorageTask<UploadTask.TaskSnapshot> uploadTask = firebaseRef.putFile(imagemUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(TelaverGaleriaActivity.this, "Erro ao enviar imagens", Toast.LENGTH_SHORT).show();
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
Toast.makeText(TelaverGaleriaActivity.this, "Upload com sucesso", Toast.LENGTH_SHORT).show();
}
});
}
}
}
private void exibirMensagemErro(String mensagem) {
Toast.makeText(this, mensagem, Toast.LENGTH_SHORT).show();
}
/* private void salvarImagensFirebase() {
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageReference.child(identificadorUsuario+file.getLastPathSegment());
StorageTask<UploadTask.TaskSnapshot> uploadTask = riversRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
});
}*/
//caso permissao foi negada
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for(int permissaoResultado : grantResults){
if(permissaoResultado == PackageManager.PERMISSION_DENIED){
alertaValidacaoPermissao();
}
}
}
private void alertaValidacaoPermissao(){
AlertDialog.Builder builder = new AlertDialog.Builder(this );
builder.setTitle("Permissoes Negadas");
builder.setMessage("Para utilizar o app é necessario aceitar as permissoes");
builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
Good evening Ivan all right? I tested the code you gave me adapting to the project, but I did not succeed. So I analyzed the contents again and I didn’t need to change much. In Activity result I redid the counter by calling the list of chosen images, I created a method just to get the files and stopped, and within Activity result I used Storagereference with Child to call idusuario (which I had already created a class)and create a folder for each id. Now every user when choosing the photos each has a specific folder, Ivan even so I thank, gratitude.
– LUANA KARLLA SILVA
I’m glad I helped in some way. Abs!
– Ivan Silva