1

Este es el codigo en el que estoy trabajando, realice una seleccion multiple de imagenes y las mostre en un gridview array que lo llame listaImagenes, pero me recomendaron convertir las imagenes a base64 para tener mas eficacia al momento de subir y mostrar las imagenes, así que busque ejemplos y documentaciones y encontre una forma de convertirlos, pero quedo algo confuso, porqué el array donde se guardan las imagenes que era listaImagenes tuve que pasarla a un String cadena, pero no entendi muy bien como subirlas al firebase tanto al storage como al database, ya que son imagenes que se guardaran de productos que se van a mostrar en la tienda este es el codigo

AQUI VA LA ACTIVIDAD DONDE EL SE VAN A CARGAR LOS DATOS, LOS DATOS COMO NOMBRE PRECIO Y DESCRIPCIÓN YA SE SUBIERON AL DATABSE, LAS IMAGENES NO.

public class adminActivity extends AppCompatActivity {

    private EditText nombreP, precioP, infoP;
    int PICK_IMAGE = 100;
    Uri imagenUri;
    Button btnCargar;
    Button btnEditar;
    GridView gvImagenes;

    List<Uri> listaImagenes = new ArrayList<>();
    List<Uri> listaBase64Imagenes = new ArrayList<>();
    GridViewAdapter baseAdapter;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;
    StorageReference mStorageRef;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        /*INICIALIZAMOS LA CONEXION CON FIREBASE*/
        FirebaseApp.initializeApp(this);
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference();
        mStorageRef = FirebaseStorage.getInstance().getReference();

        nombreP = (EditText) findViewById(R.id.nameProducto);
        precioP = (EditText) findViewById(R.id.precioProducto);
        infoP =  (EditText) findViewById(R.id.infoProducto);
        gvImagenes = findViewById(R.id.gvImagenes);
        btnEditar = findViewById(R.id.editar);
        btnCargar = (Button) findViewById(R.id.cargar);

        btnEditar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                abrirGaleria();
            }
        });

        btnCargar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nombre = nombreP.getText().toString();
                String precio = precioP.getText().toString().trim();
                String infor = infoP.getText().toString();


                if (!nombre.isEmpty() && !precio.isEmpty() && !infor.isEmpty()){
                    cargarUsuario();
                    limpiarCaja();
                }else {
                    Toast.makeText(adminActivity.this,"Deben llenarse todos los campos.",Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        });

    }

    private void limpiarCaja() {
        nombreP.setText("");
        precioP.setText("");
        infoP.setText("");
    }

    public void cargarUsuario() {

        listaBase64Imagenes.clear();

        for (int i = 0 ; i < listaImagenes.size() ; i++){
            try {
                InputStream is = getContentResolver().openInputStream(listaImagenes.get(i));
                Bitmap bitmap = BitmapFactory.decodeStream(is);

                String cadena = convertirUriToBase64(bitmap);

                enviarImagen(cadena);

                bitmap.recycle();
            } catch (IOException e){

            }
        }


        //Toast.makeText(this, "Producto Registrado", Toast.LENGTH_LONG).show();
        String nombre = nombreP.getText().toString();
        String precio = precioP.getText().toString();
        String infor = infoP.getText().toString();

        productos p = new productos();
        p.setUid(UUID.randomUUID().toString());
        p.setNombre(nombre);
        p.setPrecio(precio);
        p.setInformacion(infor);
        databaseReference.child("Productos").child(p.getUid()).setValue(p);
        Toast.makeText(adminActivity.this,"Agregado.",Toast.LENGTH_SHORT).show();
    }

    private void enviarImagen(final String cadena) {
        StorageReference folderRef = mStorageRef.child("imagenesProductos");

        folderRef.putFile((Uri) listaImagenes).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();
            }
        });
    }

    private String convertirUriToBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        String encode = Base64.encodeToString(bytes, Base64.DEFAULT);

        return encode;
    }

    private void abrirGaleria() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "SELECCIONA LAS IMAGENES"),PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ClipData clipData = data.getClipData();

        if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
            /*PARA UNA SOLA IMAGEN*/
            if (clipData == null){
                imagenUri = data.getData();
                listaImagenes.add(imagenUri);
            }
        }else {
            /*PARA VARIAS IMAGENES*/
            for (int i = 0; i < clipData.getItemCount(); i++){
                listaImagenes.add(clipData.getItemAt(i).getUri());
            }
        }

        baseAdapter = new GridViewAdapter(adminActivity.this, listaImagenes);
        gvImagenes.setAdapter(baseAdapter);
    }

}

Y AQUI ESTA EL CODIGO DEL ADAPTADOR DEL GRIDVIEW

public class GridViewAdapter extends BaseAdapter {

    Context context;
    List<Uri> listaImagenes;
    LayoutInflater layoutInflater;

    public GridViewAdapter(Context context, List<Uri> listaImagenes) {
        this.context = context;
        this.listaImagenes = listaImagenes;
    }

    @Override
    public int getCount() {
        return listaImagenes.size();
    }

    @Override
    public Object getItem(int position) {
        return listaImagenes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {

        if (view == null){
            layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.item_carga_imagenes, null);
        }

        ImageView ivImagen = view.findViewById(R.id.ivImagen);
        ImageButton ibtnEliminar = view.findViewById(R.id.ibtnEliminar);

        ivImagen.setImageURI(listaImagenes.get(position));

        ibtnEliminar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listaImagenes.remove(position);
                notifyDataSetChanged();
            }
        });

        return view;
    }
}

AQUI SEÑALO EL METODO DONDE INTENTO HACER LA CONEXIÓN AL STORAGE DE FIREBASE, PODRIAN AYUDAR A RECONSTRUIRLA CON EL FIN DE PODER SUBIRLAS AL STORAGE Y TAMBIEN A LA DATABASE CON SU RESPECTIVO NOMBRE, PRECIO Y DESCRIPCION

 private void enviarImagen(final String cadena) {
        StorageReference folderRef = mStorageRef.child("imagenesProductos");

        folderRef.putFile((Uri) listaImagenes).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();
            }
        });
    }

4
  • Mira Cómo preguntar para que tu pregunta sea mejor recibida. También, aprovecha y haz el recorrido de bienvenida para entender mejor cómo funcionamos y de paso obtener tu primera medalla!
    – gbianchi
    el 11 jun. 2020 a las 0:15
  • @gbianchi trate de ser lo mas claro posible , leeré entonces eso. pero podrias ayudarme con mi pregunta? o no fui lo suficientemente claro? el 11 jun. 2020 a las 0:20
  • yo no conozco esta tecnologia.. solo te indico enlances que te pueden ayudar a conseguir una respuesta
    – gbianchi
    el 11 jun. 2020 a las 0:27
  • entiendo, gracias! el 11 jun. 2020 a las 0:29

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.