如何将值事件侦听器添加到实时数据库

时间:2018-08-30 17:32:06

标签: java android firebase firebase-realtime-database firebase-storage

我已将一些图像导入到Firebase存储中,并且已将图像链接添加到实时数据库的一个名为images的文件夹下。我希望我的应用程序在更改实时数据库中的链接图像后自动将图像同步给用户。我不太确定如何添加值事件侦听器和创建数据库引用。 目前,我正在使用直接链接检索图像,如下面的代码所示。但是,这不能正常工作,因为我必须更改代码中的链接以更新新内容。谁能帮忙解决此问题?请分享一些代码,这些代码可能会让我深入了解如何实现此目标。

imageActivity.java

package com.example.android.zamcatalog;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

public class gameActivity extends AppCompatActivity {

    ViewPager viewPager;
    ViewPagerAdapter adapter;

 private String[] images = {
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame1.jpg?alt=media&token=b3917686-090f-43fb-852e-0365ac67dd6e",
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame2.jpg?alt=media&token=25e4eb76-5361-42a6-9bfd-6e3b1153611f",
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame3.jpg?alt=media&token=a5d4c8b9-9ecb-4ea1-a095-557955db1d19",
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame4.jpg?alt=media&token=b4598019-13b3-4600-aa49-86fd0a8c5c64",
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame5.jpg?alt=media&token=a4991bfe-d3b4-4f1c-be65-55ddfd1de7ba",
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame6.jpg?alt=media&token=e8b43bb6-c967-495f-b5e2-336f082225b6",
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame7.jpg?alt=media&token=0f135b82-1a05-4585-a511-bbab35a5613a",
            "https://firebasestorage.googleapis.com/v0/b/zamcatalog.appspot.com/o/Game%2Fgame8.jpg?alt=media&token=ab8a9fcf-db2d-4c9c-afd8-969a4db22a8c"
    };


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

        viewPager = (ViewPager)findViewById(R.id.viewpager);
        adapter = new ViewPagerAdapter(gameActivity.this,images);
        viewPager.setAdapter(adapter);
    }
}

ViewPagerAdapter.java

package com.example.android.zamcatalog;

        import android.app.Activity;
        import android.content.Context;
        import android.support.annotation.NonNull;
        import android.support.v4.view.PagerAdapter;
        import android.support.v4.view.ViewPager;
        import android.util.DisplayMetrics;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageView;

        import com.bumptech.glide.Glide;
        import com.firebase.ui.storage.images.FirebaseImageLoader;
        import com.google.firebase.database.DatabaseReference;
        import com.google.firebase.storage.FirebaseStorage;

public class ViewPagerAdapter extends PagerAdapter {
    Activity activity;
    String[] images;
    LayoutInflater inflater;

    public ViewPagerAdapter(Activity activity, String[] images) {
        this.activity = activity;
        this.images = images;
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        inflater = (LayoutInflater) activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemview = inflater.inflate(R.layout.viewpager_item, container, false);

        ImageView image;
        image = (ImageView) itemview.findViewById(R.id.imageView);
        DisplayMetrics dis = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dis);
        int height = dis.heightPixels;
        int width = dis.widthPixels;
        image.setMinimumHeight(height);
        image.setMinimumWidth(width);

        try {
            Glide.with(activity.getApplicationContext())                     
                    .load(images[position])  
                    .into(image);
        } catch (Exception ex) {

        }

        container.addView(itemview);
        return itemview;

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((View) object);
    }

}

1 个答案:

答案 0 :(得分:1)

您应该将这些图像存储在数据库中,首先获取它们的链接,然后使用GlidePicasso检索这些图像。

此代码段将图像保存到存储中并获取其下载URL:

final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file); //your image

Task<Uri> urlTask = 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();
        }

        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
            //Here you can write that url to your database like this
             yourDatabaseRef.push().child("photo").setValue(downloadUri);
        } else {
            // Handle failures
            // ...
        }
    }
});

然后使用 addValueEventListener

检索该链接
// Attach a listener to read the data at our posts reference
yourImageRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    String photoUrl = dataSnapshot.getValue(String.class);
    //Manage picasso or glide to load that url

       //Glide example
      GlideApp
           .with(Context)
           .load(photoUrl)
           .centerCrop()
           .placeholder(R.drawable.loading_spinner)
           .into(myImageView);
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    System.out.println("The read failed: " + databaseError.getCode());
  }
});

我们存储图像URL以便与Picasso或Glide一起显示,这是使用Firebase加载图像的最简单方法。