Jump to content
Fórum Script Brasil
  • 0
Sign in to follow this  
Sames Davis

Firebase - Enviar foto e recuperar link para download

Question

Olá pessoal,

Estou precisando de descobrir onde está o erro no meu código abaixo onde a ideía é se eu selecionar uma foto, eu envio essa foto para o Storage do Firebase e logo em seguida tenho de recuperar o link para de download da foto para eu gravar no campo de imagem da classe de clientes.

O problema que está acontecendo é que mesmo tendo a foto o onSuccess(UploadTask.TaskSnapshot taskSnapshot) não está funcionando

 

public class ClientescadActivity extends AppCompatActivity  {

    private Toolbar toolbarcadcli;
    private TextInputEditText edtNomeCli;
    private TextInputEditText edtTelefoneCli;
    private Clientes clientes;
    private ImageView imgCli;
    private Uri  filepath;
    private final int REQUEST_CODE = 1234;
    public static final String FB_STORAGE_PATH = "image/";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_clientescad );
        toolbarcadcli = findViewById( R.id.toolbarcadcli );
        setSupportActionBar( toolbarcadcli );

        edtNomeCli = findViewById( R.id.edtNomeCli );
        edtTelefoneCli = findViewById( R.id.edtTelefoneCli );
        edtTelefoneCli.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
        imgCli = findViewById(R.id.imgCli);

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


        });

        RealTime.InicializaFirebase (getApplicationContext(), "Clientes");

    }

    private void ChooseImage()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Selecione uma foto"),REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE && resultCode == RESULT_OK  &&  data != null  && data.getData() != null)
        {
            filepath = data.getData();
            try
            {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath) ;
                imgCli.setImageBitmap(bitmap);

            }catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate( R.menu.menu_clientes_cad,menu );
        return super.onCreateOptionsMenu( menu );
    }

    private boolean ValidaCampos()
    {
        boolean res;

        String nome = edtNomeCli.getText().toString().trim();
        String phone = edtTelefoneCli.getText().toString().trim();

        clientes.setNome(nome);
        clientes.setTelefone(phone);

        if (res = IsFieldEmpty( nome ))
        {
            AlertDialog.Builder dlg = new AlertDialog.Builder(this);
            dlg.setTitle(R.string.title_atencao);
            dlg.setMessage(R.string.message_cliente_obrigatorio);
            dlg.setNeutralButton("Ok",null);
            dlg.show();
            edtNomeCli.requestFocus();
        }

        return res;

    }

    private void SalvarDados()
    {
        clientes = new Clientes();

        if (ValidaCampos() == false)
        {

            try
            {
                StorageReference ref;
                clientes.imagem = "https://firebasestorage.googleapis.com/v0/b/salaobeleza-29ca9.appspot.com/o/image%2Fphotoprofile.png?alt=media&token=ff42f8a8-1a21-43c1-9251-6b227a99c0cd";
                if(filepath != null)
                {
                    ref = RealTime.storageReference.child(FB_STORAGE_PATH + System.currentTimeMillis() + "." + getImageExt(filepath));
                    ref.putFile(filepath)
                            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                             public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    clientes.imagem = taskSnapshot.getDownloadUrl().toString();
                                }
                            });

                }
                String mId = RealTime.databaseReference.push().getKey();
                RealTime.databaseReference.child(mId).setValue(clientes);
                Toast.makeText(ClientescadActivity.this, R.string.message_cadasto_sucesso, Toast.LENGTH_SHORT).show();
                finish();
            }catch (Exception ex){

                AlertDialog.Builder dlg = new AlertDialog.Builder(this);
                dlg.setTitle(R.string.title_atencao);
                dlg.setMessage(ex.getMessage());
                dlg.setNeutralButton("Ok",null);
                dlg.show();

            }
        }
    }

    private boolean IsFieldEmpty(String valor)
    {
        boolean resultado = (TextUtils.isEmpty( valor ) || valor.trim().isEmpty());
        return resultado;
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.action_cli_cad_ok:
                SalvarDados();
                break;
            case R.id.action_cli_cad_remove:
                Toast.makeText( this, "Removendo...", Toast.LENGTH_SHORT ).show();
                break;
        }
        return super.onOptionsItemSelected( item );
    }


    public String getImageExt(Uri uri)
    {
        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
    }
}

 

Share this post


Link to post
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  



  • Forum Statistics

    • Total Topics
      148386
    • Total Posts
      643773
×
×
  • Create New...