错误:找不到符号download_uri = task.getResult()。getDownloadUrl();

时间:2020-05-31 18:40:25

标签: android firebase-storage

我已经研究了多个主题,但无法解决此问题。当我尝试运行该应用程序时,发生以下错误:

    CadastroActivity.java:5862: error: cannot find symbol
            download_uri = task.getResult().getDownloadUrl();
                                           ^
  symbol:   method getDownloadUrl()
  location: class UploadTask.TaskSnapshot

我的活动:

package com.dc.clubedoprofissional;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import de.hdodenhof.circleimageview.CircleImageView;
import id.zelory.compressor.Compressor;
import in.galaxyofandroid.spinerdialog.OnSpinerItemClick;
import in.galaxyofandroid.spinerdialog.SpinnerDialog;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.hamzaahmedkhan.spinnerdialog.SpinnerDialogFragment;
import com.github.rtoshiro.util.format.SimpleMaskFormatter;
import com.github.rtoshiro.util.format.text.MaskTextWatcher;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static java.security.AccessController.getContext;

public class CadastroActivity extends AppCompatActivity {private EditText cadCelular;
    private EditText cadNome;
    private EditText cadCidade;

    private Uri mainImageURI = null;

    private Bitmap compressedImageFile;

    private CircleImageView imgFoto;

    private Boolean mudou = false;

    private Button cadSalvar;

    private ProgressBar progressBarCadastro;

    private FirebaseAuth mAuth;
    private StorageReference storageReference;
    private FirebaseFirestore firebaseFirestore;

    private String user_id;

    private String compara_usuario;

    private Toolbar barra_cadastro;

    private SpinnerDialog spinnerCidade;


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

        progressBarCadastro = (ProgressBar) findViewById(R.id.reg_progress);

        cadCelular = (EditText) findViewById(R.id.cad_celular);
        cadNome = (EditText) findViewById(R.id.cad_nome);
        cadSalvar = (Button) findViewById(R.id.reg_btn);
        cadCidade = (EditText) findViewById(R.id.cad_cidade);



        Toolbar barra_cadastro = findViewById(R.id.barraCadastro);
        setSupportActionBar(barra_cadastro);
        getSupportActionBar().setTitle("Cadastro");
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        //Máscara do número de celular
        SimpleMaskFormatter mascara = new SimpleMaskFormatter("(NN) NNNNN-NNNN");
        MaskTextWatcher mtww = new MaskTextWatcher(cadCelular,mascara);
        cadCelular.addTextChangedListener(mtww);

        imgFoto = (CircleImageView) findViewById(R.id.img_foto);

        mAuth = FirebaseAuth.getInstance();

        user_id = mAuth.getCurrentUser().getUid();
        storageReference = FirebaseStorage.getInstance().getReference();
        firebaseFirestore = FirebaseFirestore.getInstance();

        //progressBarCadastro.setVisibility(View.VISIBLE);
        //cadSalvar.setEnabled(false);


        firebaseFirestore.collection("Usuarios").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                if(task.isSuccessful()){

                    if(task.getResult().exists()){

                        String nome = task.getResult().getString("nome");
                        String cidade = task.getResult().getString("cidade");
                        String celular = task.getResult().getString("celular");
                        String image = task.getResult().getString("image");

                        mainImageURI = Uri.parse(image);


                        cadNome.setText(nome);
                        cadCelular.setText(celular);
                        cadCidade.setText(cidade);

                        RequestOptions placeholderRequest = new RequestOptions();
                        placeholderRequest.placeholder(R.drawable.img_pessoa_foto);

                        Glide.with(CadastroActivity.this).load(image).into(imgFoto);

                    }

                } else {

                    if(getIntent().hasExtra("celular")){
                        Bundle extras = getIntent().getExtras();
                        cadCelular.setText(extras.getString("celular"));
                    }

                    String error = task.getException().getMessage();
                    Toast.makeText(CadastroActivity.this, "(Erro ao carregar os dados...) : " + error, Toast.LENGTH_LONG).show();

                }

                progressBarCadastro.setVisibility(View.INVISIBLE);
                cadSalvar.setEnabled(true);

            }

        });


        cadSalvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String m_nome = cadNome.getText().toString();
                final String m_celular = cadCelular.getText().toString();
                final String m_cidade = cadCidade.getText().toString();

                if (!TextUtils.isEmpty(m_nome) && mainImageURI != null) {

                    progressBarCadastro.setVisibility(View.VISIBLE);

                    if(mudou) {

                        final String user_id = mAuth.getCurrentUser().getUid();

                        File newImageFile = new File(mainImageURI.getPath());
                        try {

                            compressedImageFile = new Compressor(CadastroActivity.this)
                                    .setMaxHeight(125)
                                    .setMaxWidth(125)
                                    .setQuality(50)
                                    .compressToBitmap(newImageFile);

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

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] thumbData = baos.toByteArray();

                        final UploadTask image_path = storageReference.child("perfil_imagens").child(user_id + ".jpg").putBytes(thumbData);

                        image_path.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                                if (task.isSuccessful()) {
                                    storeFirestore(task, m_nome, m_celular, m_cidade);


                                } else {

                                    String error = task.getException().getMessage();
                                    Toast.makeText(CadastroActivity.this, "(IMAGE Error) : " + error, Toast.LENGTH_LONG).show();

                                    progressBarCadastro.setVisibility(View.INVISIBLE);

                                }
                            }
                        });

                    } else{
                        storeFirestore(null,m_nome,m_celular,m_cidade);
                    }
                }

            }
        });

        imgFoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

                    if(ContextCompat.checkSelfPermission(CadastroActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){

                        Toast.makeText(CadastroActivity.this, "Necessário permissão", Toast.LENGTH_LONG).show();
                        ActivityCompat.requestPermissions(CadastroActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

                    } else {

                        BringImagePicker();

                    }

                } else {

                    BringImagePicker();

                }

            }

        });

    }


    private void storeFirestore(@NonNull Task<UploadTask.TaskSnapshot> task, String m_nome, String m_celular, String m_cidade) {

        Uri download_uri;

        if(task != null && m_nome !=null && m_celular != null && m_cidade != null) {

            download_uri = task.getResult().getDownloadUrl();

        } else {

            download_uri = mainImageURI;

        }
        Map<String, String> userMap = new HashMap<>();
        userMap.put("nome", m_nome);
        userMap.put("celular", m_celular);
        userMap.put("cidade", m_cidade);
        userMap.put("image", download_uri.toString());


        firebaseFirestore.collection("Usuarios").document(user_id).set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {

                if (task.isSuccessful()) {

                    Toast.makeText(CadastroActivity.this, "Salvo com sucesso...", Toast.LENGTH_SHORT).show();
                    vaiProInicio();

                } else {

                    String erro = task.getException().getMessage();
                    Toast.makeText(CadastroActivity.this, "Erro: " + erro, Toast.LENGTH_SHORT).show();

                }
                progressBarCadastro.setVisibility(View.INVISIBLE);

            }
        });

    }



    @Override
    protected void onStart() {
        super.onStart();

        FirebaseUser currentUser = mAuth.getCurrentUser();
        if(currentUser == null){

            vaiProInicio();

        }
    }

    private void vaiProInicio() {

        Intent inicio = new Intent(CadastroActivity.this,MainActivity.class);
        startActivity(inicio);
        finish();

    }

    private void BringImagePicker() {

        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1, 1)
                .start(CadastroActivity.this);

    }

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

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {

                mainImageURI = result.getUri();
                imgFoto.setImageURI(mainImageURI);

                mudou = true;

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                Exception error = result.getError();

            }
        }
    }
}

我在build.gradle中使用它:

implementation 'com.google.firebase:firebase-storage:19.1.1'

0 个答案:

没有答案