FireBase存储 `getDownloadUrl()`。在 `continueWithTask` 方法中出现错误。

huangapple go评论93阅读模式
英文:

FireBase Storage getDownloadUrl() .Getting error in continueWithTask method

问题

#错误: 非静态方法<TContinuationResult>continueWithTask(Continuation<TResult,Task<TContinuationResult>>)不能在静态上下文中引用其中TContinuationResultTResult是类型变量:#

  **这是错误出现的代码部分与continueWithTask有关**<br>

    private void StoreProductInformation()
    {

        loadingBar.setTitle("Add New Product");
        loadingBar.setMessage("Dear Admin,Please wait....., while we are adding the new Product");
        loadingBar.setCanceledOnTouchOutside(false);
        loadingBar.show();

        Calendar calendar=Calendar.getInstance();

        SimpleDateFormat CurrentDate=new SimpleDateFormat("MM DD,YYYY");
        SaveCurrentDate=CurrentDate.format(calendar.getTime());

        SimpleDateFormat CurrentTime=new SimpleDateFormat("HH:mm:ss a");
        SaveCurrentTime=CurrentTime.format(calendar.getTime());

        ProductRsndomKey=SaveCurrentDate + SaveCurrentTime;

        final StorageReference filePath = ProdductImageRef.child(ImageUri.getLastPathSegment() + ProductRsndomKey + ".jpg");

        final UploadTask uploadTask=filePath.putFile(ImageUri);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e)
            {
                String message=e.toString();
                Toast.makeText(AdminAddNewProductActivity.this,"Error: "+message,Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
            {
                Toast.makeText(AdminAddNewProductActivity.this,"Image uploaded successfully...",Toast.LENGTH_SHORT).show();

                Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception
                    {
                        if(!task.isSuccessful())
                        {
                            throw task.getException();
                        }
                        downloadImageUrl=filePath.getDownloadUrl().toString();
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if(task.isSuccessful())
                        {
                            downloadImageUrl=task.getResult().toString();

                            Toast.makeText(AdminAddNewProductActivity.this,"got the Product image , save to Database Successfully...",Toast.LENGTH_SHORT).show();
                            SaveProductInfoToDatabase();
                        }
                    }
                });
            }
        });

    }

#我的整个代码#
    package com.example.ecommerce;


    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.appcompat.app.AppCompatActivity;
    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.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.storage.FirebaseStorage;
    import com.google.firebase.storage.StorageReference;
    import com.google.firebase.storage.UploadTask;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.HashMap;

    public class AdminAddNewProductActivity extends AppCompatActivity {

    private String CategoryName , Description,Price,Pname,SaveCurrentDate,SaveCurrentTime;
    private ImageView InputProductImage;
    private Button AddNewProductButton;
    private EditText InputProductName,InputProductDescription,InputProductPrice;
    private static final int GalleryPick=1;
    private Uri ImageUri;
    private String ProductRsndomKey , downloadImageUrl;
    private StorageReference ProdductImageRef;
    private DatabaseReference ProductsRef;
    private ProgressDialog loadingBar;

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

        CategoryName=getIntent().getExtras().get("category").toString();
        ProdductImageRef = FirebaseStorage.getInstance().getReference().child("Product Images");
        ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");

        AddNewProductButton=findViewById(R.id.add_new_product);
        InputProductImage=findViewById(R.id.select_products_image);
        InputProductName=findViewById(R.id.product_name);
        InputProductDescription=findViewById(R.id.product_description);
        InputProductPrice=findViewById(R.id.product_price);
        loadingBar=new ProgressDialog(this);

        InputProductImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpenGallary();
            }
        });
        AddNewProductButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
               ValidateProductData();
            }
        });
    }

    private void ValidateProductData()
    {
        Description=InputProductDescription.getText().toString();
        Price=InputProductPrice.getText().toString();
        Pname=InputProductName.getText().toString();
        if(ImageUri == null)
        {
            Toast.makeText(this,"Product Image is required...",Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(Description))
        {
            Toast.makeText(this,"Please write product description...",Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(Price))
        {
            Toast.makeText(this,"Please write product Price...",Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(Pname))
        {
            Toast.makeText(this,"Please write product Name...",Toast.LENGTH_SHORT).show();
        }
        else
        {
            StoreProductInformation();
        }
    }

    private void StoreProductInformation()
    {

        loadingBar.setTitle("Add New Product");
        loadingBar.setMessage("Dear Admin,Please wait....., while we are adding the new Product");
        loadingBar.setCanceledOnTouchOutside(false);
        loadingBar.show();

        Calendar calendar=Calendar.getInstance();

        SimpleDateFormat CurrentDate=new SimpleDateFormat("MM DD,YYYY");
        SaveCurrentDate=CurrentDate.format(calendar.getTime());

        SimpleDateFormat CurrentTime=new SimpleDateFormat("HH:mm:ss a");
        SaveCurrentTime=CurrentTime.format(calendar.getTime());

        ProductRsndomKey=SaveCurrentDate + SaveCurrentTime;

        final StorageReference filePath = ProdductImageRef.child(ImageUri.getLastPathSegment() + ProductRsndomKey + ".jpg");

        final UploadTask uploadTask=filePath.putFile(ImageUri);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e)
            {
                String message=e.toString();
                Toast.makeText(AdminAddNewProductActivity.this,"Error: "+message,Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
            {
                Toast.makeText(AdminAddNewProductActivity.this,"Image uploaded successfully...",Toast.LENGTH_SHORT).show();

                Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception
                    {
                        if(!task.isSuccessful())
                        {
                            throw task.getException();
                        }
                        downloadImageUrl=filePath.getDownloadUrl().toString();
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new

<details>
<summary>英文:</summary>

#Error: non-static method &lt;TContinuationResult&gt;continueWithTask(Continuation&lt;TResult,Task&lt;TContinuationResult&gt;&gt;) cannot be referenced from a static context where TContinuationResult,TResult are type-variables:#

  ** This the code where error is with continueWithTask**&lt;br&gt;

    private void StoreProductInformation()
    {

        loadingBar.setTitle(&quot;Add New Product&quot;);
        loadingBar.setMessage(&quot;Dear Admin,Please wait....., while we are adding the new Product&quot;);
        loadingBar.setCanceledOnTouchOutside(false);
        loadingBar.show();

        Calendar calendar=Calendar.getInstance();

        SimpleDateFormat CurrentDate=new SimpleDateFormat(&quot;MM DD,YYYY&quot;);
        SaveCurrentDate=CurrentDate.format(calendar.getTime());

        SimpleDateFormat CurrentTime=new SimpleDateFormat(&quot;HH:mm:ss a&quot;);
        SaveCurrentTime=CurrentTime.format(calendar.getTime());

        ProductRsndomKey=SaveCurrentDate + SaveCurrentTime;

        final StorageReference filePath = ProdductImageRef.child(ImageUri.getLastPathSegment() + ProductRsndomKey + &quot;.jpg&quot;);

        final UploadTask uploadTask=filePath.putFile(ImageUri);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e)
            {
                String message=e.toString();
                Toast.makeText(AdminAddNewProductActivity.this,&quot;Error: &quot;+message,Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }).addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
            {
                Toast.makeText(AdminAddNewProductActivity.this,&quot;Image uploaded successfully... &quot;,Toast.LENGTH_SHORT).show();

                Task&lt;Uri&gt; uriTask = UploadTask.continueWithTask(new Continuation&lt;UploadTask.TaskSnapshot, Task&lt;Uri&gt;&gt;() {
                    @Override
                    public Task&lt;Uri&gt; then(@NonNull Task&lt;UploadTask.TaskSnapshot&gt; task) throws Exception
                    {
                        if(!task.isSuccessful())
                        {
                            throw task.getException();
                        }
                        downloadImageUrl=filePath.getDownloadUrl().toString();
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener&lt;Uri&gt;() {
                    @Override
                    public void onComplete(@NonNull Task&lt;Uri&gt; task) {
                        if(task.isSuccessful())
                        {
                            downloadImageUrl=task.getResult().toString();

                            Toast.makeText(AdminAddNewProductActivity.this,&quot;got the Product image , save to Database Successfully...&quot;,Toast.LENGTH_SHORT).show();
                            SaveProductInfoToDatabase();
                        }
                    }
                });
            }
        });

    }

#my whole Code #
    package com.example.ecommerce;


    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.appcompat.app.AppCompatActivity;
    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.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.storage.FirebaseStorage;
    import com.google.firebase.storage.StorageReference;
    import com.google.firebase.storage.UploadTask;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.HashMap;

    public class AdminAddNewProductActivity extends AppCompatActivity {

    private String CategoryName , Description,Price,Pname,SaveCurrentDate,SaveCurrentTime;
    private ImageView InputProductImage;
    private Button AddNewProductButton;
    private EditText InputProductName,InputProductDescription,InputProductPrice;
    private static final int GalleryPick=1;
    private Uri ImageUri;
    private String ProductRsndomKey , downloadImageUrl;
    private StorageReference ProdductImageRef;
    private DatabaseReference ProductsRef;
    private ProgressDialog loadingBar;

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

        CategoryName=getIntent().getExtras().get(&quot;category&quot;).toString();
        ProdductImageRef = FirebaseStorage.getInstance().getReference().child(&quot;Product Images&quot;);
        ProductsRef = FirebaseDatabase.getInstance().getReference().child(&quot;Products&quot;);

        AddNewProductButton=findViewById(R.id.add_new_product);
        InputProductImage=findViewById(R.id.select_products_image);
        InputProductName=findViewById(R.id.product_name);
        InputProductDescription=findViewById(R.id.product_description);
        InputProductPrice=findViewById(R.id.product_price);
        loadingBar=new ProgressDialog(this);

        InputProductImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpenGallary();
            }
        });
        AddNewProductButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
               ValidateProductData();
            }
        });
    }

    private void ValidateProductData()
    {
        Description=InputProductDescription.getText().toString();
        Price=InputProductPrice.getText().toString();
        Pname=InputProductName.getText().toString();
        if(ImageUri == null)
        {
            Toast.makeText(this,&quot;Product Image is required...&quot;,Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(Description))
        {
            Toast.makeText(this,&quot;Please write product description...&quot;,Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(Price))
        {
            Toast.makeText(this,&quot;Please write product Price...&quot;,Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(Pname))
        {
            Toast.makeText(this,&quot;Please write product Name...&quot;,Toast.LENGTH_SHORT).show();
        }
        else
        {
            StoreProductInformation();
        }
    }

    private void StoreProductInformation()
    {

        loadingBar.setTitle(&quot;Add New Product&quot;);
        loadingBar.setMessage(&quot;Dear Admin,Please wait....., while we are adding the new Product&quot;);
        loadingBar.setCanceledOnTouchOutside(false);
        loadingBar.show();

        Calendar calendar=Calendar.getInstance();

        SimpleDateFormat CurrentDate=new SimpleDateFormat(&quot;MM DD,YYYY&quot;);
        SaveCurrentDate=CurrentDate.format(calendar.getTime());

        SimpleDateFormat CurrentTime=new SimpleDateFormat(&quot;HH:mm:ss a&quot;);
        SaveCurrentTime=CurrentTime.format(calendar.getTime());

        ProductRsndomKey=SaveCurrentDate + SaveCurrentTime;

        final StorageReference filePath = ProdductImageRef.child(ImageUri.getLastPathSegment() + ProductRsndomKey + &quot;.jpg&quot;);

        final UploadTask uploadTask=filePath.putFile(ImageUri);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e)
            {
                String message=e.toString();
                Toast.makeText(AdminAddNewProductActivity.this,&quot;Error: &quot;+message,Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }).addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
            {
                Toast.makeText(AdminAddNewProductActivity.this,&quot;Image uploaded successfully... &quot;,Toast.LENGTH_SHORT).show();

                Task&lt;Uri&gt; uriTask = UploadTask.continueWithTask(new Continuation&lt;UploadTask.TaskSnapshot, Task&lt;Uri&gt;&gt;() {
                    @Override
                    public Task&lt;Uri&gt; then(@NonNull Task&lt;UploadTask.TaskSnapshot&gt; task) throws Exception
                    {
                        if(!task.isSuccessful())
                        {
                            throw task.getException();
                        }
                        downloadImageUrl=filePath.getDownloadUrl().toString();
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener&lt;Uri&gt;() {
                    @Override
                    public void onComplete(@NonNull Task&lt;Uri&gt; task) {
                        if(task.isSuccessful())
                        {
                            downloadImageUrl=task.getResult().toString();

                            Toast.makeText(AdminAddNewProductActivity.this,&quot;got the Product image , save to Database Successfully...&quot;,Toast.LENGTH_SHORT).show();
                            SaveProductInfoToDatabase();
                        }
                    }
                });
            }
        });

    }

    private void SaveProductInfoToDatabase()
    {
        HashMap&lt;String,Object&gt; productMap=new HashMap&lt;&gt;();
        productMap.put(&quot;pid&quot;,ProductRsndomKey);
        productMap.put(&quot;date&quot;,SaveCurrentDate);
        productMap.put(&quot;time&quot;,SaveCurrentTime);
        productMap.put(&quot;discription&quot;,Description);
        productMap.put(&quot;image&quot;,downloadImageUrl);
        productMap.put(&quot;category&quot;,CategoryName);
        productMap.put(&quot;price&quot;,Price);
        productMap.put(&quot;pname&quot;,Pname);

        ProductsRef.child(ProductRsndomKey).updateChildren(productMap).addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;Void&gt; task)
            {
                if ((task.isSuccessful()))
                {
                    Intent intent=new Intent(AdminAddNewProductActivity.this,AdminCategoryActivity.class);
                    startActivity(intent);
                    loadingBar.dismiss();
                    Toast.makeText(AdminAddNewProductActivity.this,&quot;Product is added Successfully...&quot;,Toast.LENGTH_SHORT).show();
                }
                else
                {
                    loadingBar.dismiss();
                    String messg=task.getException().toString();
                    Toast.makeText(AdminAddNewProductActivity.this,&quot;Error :&quot;+messg,Toast.LENGTH_SHORT).show();

                }
            }
        });
    }

    private void OpenGallary()
    {
        Intent galleryIntent=new Intent();
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType(&quot;image/*&quot;);
        startActivityForResult(galleryIntent,GalleryPick);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == GalleryPick &amp;&amp; resultCode == RESULT_OK &amp;&amp; data != null)
        {
            ImageUri=data.getData();
            InputProductImage.setImageURI(ImageUri);

        }
    }
}


</details>


# 答案1
**得分**: 0

`continueWithTask`是一个实例方法而不是静态方法因此您需要使用实例变量`uploadTask`来调用`continueWithTask`:

```java
final UploadTask uploadTask = filePath.putFile(ImageUri);

Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }
        downloadImageUrl = filePath.getDownloadUrl().toString();
        return filePath.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            downloadImageUrl = task.getResult().toString();

            Toast.makeText(AdminAddNewProductActivity.this, "成功获取产品图片,保存到数据库...", Toast.LENGTH_SHORT).show();
            SaveProductInfoToDatabase();
        }
    }
});
英文:

continueWithTask is an instance method not a static method, therefore you need to use the instance variable uploadTask to call continueWithTask:

final UploadTask uploadTask=filePath.putFile(ImageUri);
Task&lt;Uri&gt; uriTask = uploadTask.continueWithTask(new Continuation&lt;UploadTask.TaskSnapshot, Task&lt;Uri&gt;&gt;() {
@Override
public Task&lt;Uri&gt; then(@NonNull Task&lt;UploadTask.TaskSnapshot&gt; task) throws Exception
{
if(!task.isSuccessful())
{
throw task.getException();
}
downloadImageUrl=filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener&lt;Uri&gt;() {
@Override
public void onComplete(@NonNull Task&lt;Uri&gt; task) {
if(task.isSuccessful())
{
downloadImageUrl=task.getResult().toString();
Toast.makeText(AdminAddNewProductActivity.this,&quot;got the Product image , save to Database Successfully...&quot;,Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
}
});
</details>

huangapple
  • 本文由 发表于 2020年4月8日 14:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/61094305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定