从FirebaseDatabase

时间:2018-06-15 09:49:58

标签: java android firebase firebase-realtime-database

我想知道可以使用FirebaseDatabase方法为全局变量赋值。我知道FirebaseDatabase方法是异步的,并且在后台执行而不会阻塞主线程。但是我遇到了onDataChange()方法之外需要值的情况。这是我的java类文件:

public class DetailActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {

private ProgressBar mProgressBar;
private CoordinatorLayout coordinatorLayout;

private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerView youTubePlayerView;

int currentPage = 0;
Timer timer;
final long DELAY_MS = 500;
final long PERIOD_MS = 3000;
CircleIndicator circleIndicator;
private ViewPager viewPager;
private PagerAdapter adapter;

private ArrayList<String> images;
private ArrayList<String> imageDetails;

private DatabaseReference databaseReference;

private TextView capital, area, population,languages,literacyRate;
private ImageView appbarImageView;
private ExpandableTextView historyTextView;

private String youTubeVideoLink;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);

    viewPager = findViewById(R.id.view_pager);
    circleIndicator = findViewById(R.id.indicator);
    mProgressBar = findViewById(R.id.progress_bar);

    youTubePlayerView =  findViewById(R.id.youtube_player_view);
    youTubePlayerView.initialize(BuildConfig.ApiKey, this);

    population = findViewById(R.id.population);
    capital = findViewById(R.id.capital);
    area = findViewById(R.id.area);

    coordinatorLayout = findViewById(R.id.detail_container);
    appbarImageView = findViewById(R.id.app_bar_image);
    historyTextView = findViewById(R.id.expand_text_view);
    literacyRate = findViewById(R.id.literacy_rate);
    languages = findViewById(R.id.languages);

    Intent intent = getIntent();
    if(intent.hasExtra("State")) {
        collapsingToolbarLayout.setTitle(intent.getStringExtra("State"));
        databaseReference = FirebaseDatabase.getInstance().getReference().child("States").child(intent.getStringExtra("State").trim());
    }



    final Handler handler = new Handler();
    final Runnable update = new Runnable() {
        @Override
        public void run() {
            if(currentPage == 12) {
                currentPage = 0;
            }
            viewPager.setCurrentItem(currentPage++,true);
        }
    };
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(update);
        }
    },DELAY_MS,PERIOD_MS);
}

private void readDataFromDatabase(final StatesCallback statesCallback) {
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            StateDetails stateDetails = dataSnapshot.getValue(StateDetails.class);
            statesCallback.onCallback(stateDetails);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

@Override
protected void onDestroy() {
    super.onDestroy();
    timer.cancel();
}

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

    readDataFromDatabase(new StatesCallback() {
        @Override
        public void onCallback(StateDetails stateDetails) {
            mProgressBar.setVisibility(View.GONE);
            coordinatorLayout.setVisibility(View.VISIBLE);
            capital.setText(stateDetails.getCapital());
            area.setText(stateDetails.getArea());
            population.setText(stateDetails.getPopulation());
            historyTextView.setText(stateDetails.getHistory());
            languages.setText(stateDetails.getLanguages());
            literacyRate.setText(String.valueOf(stateDetails.getLiteracyRate()));
            images = stateDetails.getImages();
            imageDetails = stateDetails.getImageDetails();
            youTubeVideoLink = stateDetails.getYouTubeVideoLink();

            Log.i("youtube video",youTubeVideoLink);
            Picasso.get().load(images.get(0)).into(appbarImageView);
            adapter = new CustomAdapter(DetailActivity.this, images, imageDetails);
            viewPager.setAdapter(adapter);
            circleIndicator.setViewPager(viewPager);
            adapter.registerDataSetObserver(circleIndicator.getDataSetObserver());

        }
    });
    if(!b) {
        Log.i("Checking order","video link: "+youTubeVideoLink);
        youTubePlayer.cueVideo(youTubeVideoLink);
    }
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
    if(youTubeInitializationResult.isUserRecoverableError()) {
        youTubeInitializationResult.getErrorDialog(DetailActivity.this,RECOVERY_DIALOG_REQUEST);
    } else {
        String errorMessage = getString(R.string.youTubeErrorMessage)+youTubeInitializationResult;
        Toast.makeText(DetailActivity.this,errorMessage,Toast.LENGTH_SHORT).show();
    }

  }
}

以下是日志详情:

I/Checking order: video link: null
I/youtube video: QR19-rUVjNQ

我想为YouTubePlayer分配一个动态视频,该链接通过youTubeVideoLink字符串存储在数据库中。我尝试过列出的方法 here

但这并没有帮助。那么,有没有办法将初始化的youTubeVideoLink发送到onInitializationSuccess()方法?谢谢。

1 个答案:

答案 0 :(得分:1)

您不能简单地创建一个全局变量并在BackgroundImage之外使用它的值,因为这种方法具有异步行为。如果要在onDataChange()方法之外使用来自数据库的值,则有两种选择。第一个是将所需的对象作为参数传递给您的类中定义的方法,或者,如果您想以更复杂的方式使用它,那么请深入了解现代API的异步世界并查看最后一个我在 post 中的部分回答,其中我已经逐步解释了如何实现这一目标。有关详细信息,您还可以查看 video

修改

onDataChange()