Не получается вернуть картинки из firebase Storage
Не выводит картинки из firebase storage, при этом он не возвращает какие-либо ошибки. Gытаюсь создать каталог из кликабельных плиток с картинками использую Recycle View и ViewHolder.
Сохраняю путь картинки в realtime database вместе с данными о условном продукте.
'''
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_relay);
fab = (Button) findViewById(R.id.fab);
ProductImg = (ImageView) findViewById(R.id.Productimg);
prodName = (EditText) findViewById(R.id.nameprod_img);
Comp1 = (EditText) findViewById(R.id.comp1);
Comp2 = (EditText) findViewById(R.id.comp2);
Comp3 = (EditText) findViewById(R.id.comp3);
Comp4 = (EditText) findViewById(R.id.comp4);
Description = (EditText) findViewById(R.id.desc_text);
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
LoadingBar = new ProgressDialog(this);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ValidateProductData();
}
});
ProductImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(product_relay.this,"click",Toast.LENGTH_SHORT).show();
OpenGallery();
}
});
}
private void ValidateProductData() {
DescriptionT = Description.getText().toString();
productName = prodName.getText().toString();
compon1 = Comp1.getText().toString();
compon2 = Comp2.getText().toString();
compon3 = Comp3.getText().toString();
compon4 = Comp4.getText().toString();
ProductImgRef = FirebaseStorage.getInstance().getReference().child("product_images");
if(ImgUri == null){
Toast.makeText(this, "Add image", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(Description.getText().toString())){
Toast.makeText(this, "Add DESC", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(productName)){
Toast.makeText(this, "Add productName", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(compon1)){
Toast.makeText(this, "Add compon1", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(compon2)){
Toast.makeText(this, "Add compon2", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(compon3)){
Toast.makeText(this, "Add compon3", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(compon4)){
Toast.makeText(this, "Add compon4", Toast.LENGTH_SHORT).show();
}
else{
StoreProductINFO();
}
}
private void StoreProductINFO() {
LoadingBar.setTitle("Data loading...");
LoadingBar.setMessage("Please, waiting...");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("ddMMyyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HHmmss");
SaveCurrentTime = currentTime.format(calendar.getTime());
ProductRandomKey = saveCurrentDate + SaveCurrentTime;
StorageReference filePath = ProductImgRef.child(ImgUri.getLastPathSegment() + ProductRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImgUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
String message = e.toString();
Toast.makeText(product_relay.this, "Error " + message , Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(product_relay.this, "IMG added " , 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();
}
link = filePath.toString();
downloadImgUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if(task.isSuccessful()){
Toast.makeText(product_relay.this, "IMG saved " , Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
}
});
}
});
}
private void SaveProductInfoToDatabase() {
HashMap<String,Object> productMap = new HashMap<>();
productMap.put("pid", ProductRandomKey);
productMap.put("date", saveCurrentDate);
productMap.put("time", SaveCurrentTime);
productMap.put("description", DescriptionT);
//productMap.put("Image", downloadImgUrl);
productMap.put("prodName", productName);
productMap.put("comp1", compon1);
productMap.put("comp2", compon2);
productMap.put("comp3", compon3);
productMap.put("comp4", compon4);
productMap.put("image", downloadImgUrl);
productMap.put("imglink",link);
ProductsRef.child(ProductRandomKey).updateChildren(productMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(product_relay.this,"Item add",Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
Intent loginIntent = new Intent(product_relay.this,Home_activity.class);
startActivity(loginIntent);
}
else {
String message = task.getException().toString();
Toast.makeText(product_relay.this,"Item add error",Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLERYPIC);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERYPIC && resultCode == RESULT_OK && data.getData() != null){
if(resultCode == RESULT_OK)
{
System.out.println("imageuri:"+ data.getData());
ImgUri = data.getData();
ProductImg.setImageURI(ImgUri);
}
}
}
'''
Специально записываю через '''getDownloadUrl()''' и просто через '''filepath''' тк пытался в отображении использовать и picasso и Glide но безуспешно .
Далее в каталоге прописываю возврат своей картинки относительно каждой плитки в recycle View.
public class Catalog extends AppCompatActivity {
DatabaseReference ProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
'''
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(Catalog.this);
recyclerView.setLayoutManager(layoutManager);
}
@Override
protected void onStart(){
super.onStart();
FirebaseRecyclerOptions<Products> options = new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(ProductsRef,Products.class).build();
FirebaseRecyclerAdapter<Products,ProductViewHolder> adapter = new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull ProductViewHolder holder, int i, @NonNull Products products) {
holder.NameProd.setText(products.getProdName());
Picasso.get().load(products.getImage()).resize(60,60).into(holder.imgProd);
Glide.with(Catalog.this)
.load(products.getImglink())
.into(holder.imgProd);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent getCard = new Intent(Catalog.this, Product_card.class);
getCard.putExtra("nameProd",products.getProdName());
getCard.putExtra("comp1",products.getComp1());
getCard.putExtra("comp2",products.getComp2());
getCard.putExtra("comp3",products.getComp3());
getCard.putExtra("comp4",products.getComp4());
getCard.putExtra("Desc",products.getDescription());
//getCard.putExtra("img",products.getProdName());
startActivity(getCard);
System.out.println(products.getProdName());
System.out.println(products.getDate());
System.out.println(products.getTime());
System.out.println(products.getPid());
System.out.println(products.getComp1());
System.out.println(products.getComp2());
System.out.println(products.getComp3());
System.out.println(products.getComp4());
System.out.println(products.getDescription());
System.out.println(products.getImage());
System.out.println(products.getImglink());
}
});
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.produvtitemslayout,parent,false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
} '''
прописываю Холдер
Product View holder
public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView NameProd;
public ImageView imgProd;
public ItemClickListner listner;
public ProductViewHolder(View itemView)
{
super(itemView);
imgProd = itemView.findViewById(R.id.img_prod);
NameProd = itemView.findViewById(R.id.prod_name);
}
public void setItemClickListener(ItemClickListner listener) {this.listner = listner;}
@Override
public void onClick(View view)
{listner.onClick(view, getAdapterPosition(),false);
}
}
И в плитки передаются текстовые данные, но картинки нет и при этом в realtime database записываются пути картинок. но картинки не отображаются.
Опытным путем выяснил что метод getDownloadUrl и load не вытаскивает токен доступа, тк по прямой ссылке с токеном картинка отображается. Уже всю голову сломал, не понимаю что делать.
лог который выводится при открытии каталога
2022-12-05 04:14:27.891 25637-25882/com.example.myapplication V/FA: Recording user engagement, ms: 4038
2022-12-05 04:14:27.912 25637-25881/com.example.myapplication V/FA: onActivityCreated
2022-12-05 04:14:27.991 25637-25882/com.example.myapplication V/FA: Activity paused, time: 58255099
2022-12-05 04:14:27.993 25637-25882/com.example.myapplication V/FA: Activity resumed, time: 58255158
2022-12-05 04:14:28.093 25637-25674/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xa7322d00: ver 3 0 (tinfo 0xaf1f47e0)
2022-12-05 04:14:28.104 25637-25674/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xa7322d00: ver 3 0 (tinfo 0xaf1f47e0)
2022-12-05 04:14:28.121 25637-25674/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xa7322d00: ver 3 0 (tinfo 0xaf1f47e0)
2022-12-05 04:14:28.131 25637-25674/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xa7322d00: ver 3 0 (tinfo 0xaf1f47e0)
2022-12-05 04:14:28.144 25637-25674/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xa7322d00: ver 3 0 (tinfo 0xaf1f47e0)
2022-12-05 04:14:28.156 25637-25674/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xa7322d00: ver 3 0 (tinfo 0xaf1f47e0)
2022-12-05 04:14:33.104 25637-25882/com.example.myapplication V/FA: Inactivity, disconnecting from the service
P.s Честно говоря первый вопрос и все форматирование кода поехало, не судите строго c: