吐司一直循环

Posted

技术标签:

【中文标题】吐司一直循环【英文标题】:Toast keeps on loop 【发布时间】:2021-01-29 02:57:51 【问题描述】:

我的 Toast 一直在运行或循环,我不明白为什么。

 private void fetchTheData() 
    //fetch subjects
    recyclerView = getView().findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    fetchData = new ArrayList<>();


    databaseReference = FirebaseDatabase.getInstance().getReference("subject");
    final ProgressBar progressBar = getView().findViewById(R.id.progressBar);
    progressBar.setVisibility(View.VISIBLE);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() 
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) 
            for (DataSnapshot ds:dataSnapshot.getChildren())
                FetchDatadata = ds.getValue(FetchData.class);
                fetchData.add(data);
                progressBar.setVisibility(View.INVISIBLE);
                Toast.makeText(getContext(), "Subjects Successfully Loaded", Toast.LENGTH_SHORT).show();
            
            helperAdapter = new HelperAdapter(fetchData);
            recyclerView.setAdapter(helperAdapter);
        

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) 
        
    );

Subjects Successfully Loaded 正在循环中,它会在显示 10 次后停止

我在public void onViewCreated(View view, Bundle savedInstanceState)上调用fetchTheData()方法

【问题讨论】:

【参考方案1】:

将 Toast 排除在 for 循环之外:

boolean success = false;
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() 
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) 
        for (DataSnapshot ds:dataSnapshot.getChildren())
            FetchDatadata = ds.getValue(FetchData.class);
            fetchData.add(data);
            progressBar.setVisibility(View.INVISIBLE);
        success = true;
            
        
       if(success)
       Toast.makeText(getContext(), "Subjects Successfully Loaded", Toast.LENGTH_SHORT).show();
       success = false
       
        helperAdapter = new HelperAdapter(fetchData);
        recyclerView.setAdapter(helperAdapter);
    

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) 
    
);

【讨论】:

以上是关于吐司一直循环的主要内容,如果未能解决你的问题,请参考以下文章

java 带图标的吐司(带图标的吐司)

TIJ -- 吐司BlockingQueue

75.『Ruby烘焙』牛奶吐司(面包机版)

CoCoa双色吐司

“覆盖”上的吐司通知

不能在片段中工作吐司