带有进度条的 Firebase 数据库
Posted
技术标签:
【中文标题】带有进度条的 Firebase 数据库【英文标题】:Firebase database with progressbar 【发布时间】:2018-01-27 06:05:45 【问题描述】:我有问题。从 Firebase 数据库加载数据时,我无法将 progressbar
附加到我的活动中。我尝试通过Asynctask
附加进度条,
将firebase监听器放入AsyncTask
doInBackGround
,在PreExecute
和PostExecute
方法中设置可见性,但progressbar
没有出现。任何帮助表示赞赏。
package org.wangjie.wheelview.DirectionActivity.Direction;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.firebase.crash.FirebaseCrash;
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.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import org.wangjie.wheelview.R;
import org.wangjie.wheelview.gameActivity.SixStep;
import org.wangjie.wheelview.sample.TimelineActivity;
import java.util.ArrayList;
public class ActivityMainDirection extends AppCompatActivity
ArrayList<Direction> gArray;
TextView mConception,mDescription,mTools,mDirectionTitle,mTitleDirection,mTitleConception,mTitleMethods;
ProgressBar progressBar;
ImageView mFirstImage;
LinearLayoutManager layoutManager,layoutManager2 ;
private NavigationView mNavigationView;
DatabaseReference databaseReference;
int number,i;
RecyclerView recycler_artist;
RecyclerView recycler_pictures;
TextView mTextView;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.scroll_main_direction);
Toolbar mToolbar=findViewById(R.id.toolbar);
progressBar=findViewById(R.id.progressBar);
PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.drawer_item_home).withSelectable(false).withTextColor(Color.BLACK);
// SecondaryDrawerItem item2 = new SecondaryDrawerItem().withIdentifier(2).withName(R.string.drawer_paintings).withSelectable(false).withTextColor(Color.BLACK);
SecondaryDrawerItem item3 = new SecondaryDrawerItem().withIdentifier(2).withName(R.string.malevichGame).withSelectable(false).withTextColor(Color.BLACK);
// item1.withName("A new name for this drawerItem").withBadge("19").withBadgeStyle(new BadgeStyle().withTextColor(Color.BLACK));
//notify the drawer about the updated element. it will take care about everything else1
//create the drawer and remember the `Drawer` result object
// Create the AccountHeader
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.i_007)
.build();
//Now create your drawer and pass the AccountHeader.Result
//additional Drawer setup as shown above
Drawer result = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.addDrawerItems(
item1,
//new DividerDrawerItem(),
// item2,
item3
// new SecondaryDrawerItem().withName(R.string.drawer_item_settings)
).withTranslucentStatusBar(false).withAccountHeader(headerResult).withActionBarDrawerToggle(true).withActionBarDrawerToggleAnimated(true).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener()
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem)
// do something with the clicked item :D
if(position==1)
Intent intent=new Intent(view.getContext(), TimelineActivity.class);
startActivity(intent);
if(position==2)
Intent intent=new Intent(view.getContext(), SixStep.class);
startActivity(intent);
return false;
).withSelectedItem(-1)
.build();
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// result.getActionBarDrawerToggle().setDrawerIndicatorEnabled(true);
FirebaseDatabase database=FirebaseDatabase.getInstance();
databaseReference=database.getReference();
gArray=new ArrayList<>();
recycler_artist= (RecyclerView) findViewById(R.id.horizontal_artist_list);
recycler_pictures=(RecyclerView) findViewById(R.id.horizontal_list);
mDescription= (TextView) findViewById(R.id.mDescription);
mConception= (TextView) findViewById(R.id.mConception);
mTools= (TextView) findViewById(R.id.mToolsText);
mTitleConception=findViewById(R.id.titleConception);
mTitleDirection=findViewById(R.id.titleDescription);
mTitleMethods=findViewById(R.id.titleMethods);
mFirstImage=(ImageView) findViewById(R.id.first_image);
mDirectionTitle=(TextView) findViewById(R.id.main_title);
View targetView = findViewById(R.id.mConceptionLayout);
targetView.getParent().requestChildFocus(targetView,targetView);
layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//recycler_artist.setHasFixedSize(false);
recycler_artist.setLayoutManager(layoutManager);
layoutManager2=new LinearLayoutManager(this);
layoutManager2.scrollToPositionWithOffset(2,20);
layoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
//recycler_pictures.setHasFixedSize(true);
layoutManager2.scrollToPositionWithOffset(2,20);
recycler_pictures.setLayoutManager(layoutManager2);
FirebaseCrash.logcat(Log.INFO,"Activity Direction"," WTF ");
new Downloader().execute();
//
//
//
// databaseReference.addChildEventListener(new com.google.firebase.database.ChildEventListener()
//
// @Override
// public void onChildAdded(DataSnapshot dataSnapshot, String s)
//
// Log.e("children tag",(dataSnapshot).toString());
//
// Iterable<DataSnapshot> children = dataSnapshot.getChildren();
//
// for (DataSnapshot child : children)
//
// //Log.e("child tag",child.toString());
//
// Direction direction = child.getValue(Direction.class);
// gArray.add(direction);
// Log.e("new_dir_added", direction.toString());
//
//
// Intent intent=getIntent();
// String srt=intent.getStringExtra("Number_in_list");
//
// number=Integer.parseInt(srt);
//
// Log.e("arrSize", gArray.size() +" " + number)
// ;
//
// Log.e("url image erre",(gArray.get(number).toString()));
// Log.e("image_url", gArray.get(number).getMUrlImage());
//
// String [] mPictureList=gArray.get(number).getMUrlImage().split(",");
//
// String [] mArtistListImage=gArray.get(number).getMArtistListImage().split(",");
//
//
//
// // recycler_artist.setAdapter(new ArtistAdapter(gArray,number));// список художников в Направлении
// // recycler_pictures.setAdapter(new HorizontalRVAdapter(gArray,number)); // список картин в направлении
//
// recycler_artist.setAdapter(new ArtistAdapter(mArtistListImage,number));
// recycler_pictures.setAdapter(new HorizontalRVAdapter(mPictureList,number));
//
// mConception.setText(gArray.get(number).getConcept());
// mDescription.setText(gArray.get(number).getDesc());
// mTools.setText(gArray.get(number).getTechnique());
// mDirectionTitle.setText(gArray.get(number).getName());
//
// Glide.with(getApplicationContext())
// .load(gArray.get(number).getImage())
// .placeholder(R.drawable.papiros)
// .into(mFirstImage);
//
//
// @Override
// public void onChildChanged(DataSnapshot dataSnapshot, String s)
//
//
//
// @Override
// public void onChildRemoved(DataSnapshot dataSnapshot)
//
//
//
// @Override
// public void onChildMoved(DataSnapshot dataSnapshot, String s)
//
//
//
// @Override
// public void onCancelled(DatabaseError databaseError)
//
//
// );
class Downloader extends AsyncTask<Object, Object, Void>
private final ProgressBar progress=findViewById(R.id.progressBar);
// public Downloader(ProgressBar progress)
// this.progress = progress;
// Log.e("DownloaderCons", String.valueOf(progress.getId() == R.id.progressBar));
//
@Override
protected void onPreExecute()
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
progress.setMax(100);
@Override
protected void onPostExecute(Void aVoid)
super.onPostExecute(aVoid);
progress.setVisibility(View.GONE);
@Override
protected void onProgressUpdate(Object... values)
super.onProgressUpdate(values);
progress.setProgress((Integer) values[0]);
@Override
protected Void doInBackground(Object... voids)
//return null;
for (i=0 ;i<20;i++)
publishProgress(i);
try
Thread.sleep(30);
catch (InterruptedException ie)
ie.printStackTrace();
databaseReference.addChildEventListener(new com.google.firebase.database.ChildEventListener()
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
Log.e("children tag",(dataSnapshot).toString());
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child : children)
//Log.e("child tag",child.toString());
Direction direction = child.getValue(Direction.class);
gArray.add(direction);
Log.e("new_dir_added", direction.toString());
Intent intent=getIntent();
String srt=intent.getStringExtra("Number_in_list");
number=Integer.parseInt(srt);
Log.e("arrSize", gArray.size() +" " + number)
;
Log.e("url image erre",(gArray.get(number).toString()));
Log.e("image_url", gArray.get(number).getMUrlImage());
String [] mPictureList=gArray.get(number).getMUrlImage().split(",");
String [] mArtistListImage=gArray.get(number).getMArtistListImage().split(",");
// recycler_artist.setAdapter(new ArtistAdapter(gArray,number));// список художников в Направлении
// recycler_pictures.setAdapter(new HorizontalRVAdapter(gArray,number)); // список картин в направлении
recycler_artist.setAdapter(new ArtistAdapter(mArtistListImage,number));
recycler_pictures.setAdapter(new HorizontalRVAdapter(mPictureList,number));
mConception.setText(gArray.get(number).getConcept());
mDescription.setText(gArray.get(number).getDesc());
mTools.setText(gArray.get(number).getTechnique());
mDirectionTitle.setText(gArray.get(number).getName());
Glide.with(getApplicationContext())
.load(gArray.get(number).getImage())
.placeholder(R.drawable.papiros)
.into(mFirstImage);
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
@Override
public void onChildRemoved(DataSnapshot dataSnapshot)
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
@Override
public void onCancelled(DatabaseError databaseError)
);
//
return null;
return null;
这是我的 xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:background="@android:color/background_light"
>
<!-- полосу на тулбаре я убрал, теперь баг появился статус бар выпрыгивает во время прокрутки -->
<android.support.design.widget.AppBarLayout
android:id="@+id/main.appbar"
android:layout_
android:layout_
android:fitsSystemWindows="true"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/main.collapsing"
android:layout_
android:layout_
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="64dp"
>
<ImageView
android:src="@drawable/papiros"
android:id="@+id/first_image"
android:layout_marginTop="55dp"
android:layout_
android:layout_
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
tools:ignore="ContentDescription"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_
android:layout_
app:layout_collapseMode="pin"
>
<RelativeLayout
android:layout_
android:layout_
android:layout_weight="0.88">
<TextView
android:id="@+id/main_title"
android:layout_
android:layout_
android:gravity="left"
android:text=""
android:textColor="#000000"
android:textSize="19sp"
android:visibility="visible"
tools:ignore="HardcodedText,RtlHardcoded"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_
android:layout_
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<LinearLayout
android:layout_
android:layout_
android:orientation="vertical">
<RelativeLayout
android:id="@+id/mConceptionLayout"
android:layout_
android:layout_
android:layout_margin="15dp"
android:layout_marginBottom="15dp"
>
<TextView
android:id="@+id/mConception"
android:layout_
android:layout_
android:text=""
android:textColor="@color/textColor"
android:textSize="15sp"
android:layout_marginTop="40dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
/>
<TextView
android:id="@+id/titleConception"
android:layout_
android:layout_
android:textSize="15sp"
android:textColor="@color/textColor"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="13dp"
android:text="Концепция"
android:textStyle="bold"
tools:ignore="HardcodedText"/>
</RelativeLayout>
<RelativeLayout
android:layout_
android:layout_
android:orientation="vertical"
android:layout_margin="15dp"
android:layout_marginBottom="15dp"
>
<TextView
android:id="@+id/titleDescription"
android:layout_
android:layout_
android:text="Описание"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="13dp"
android:textColor="@color/textColor"
android:textSize="15sp"
android:textStyle="bold"
tools:ignore="HardcodedText"/>
<TextView
android:textColor="@color/textColor"
android:id="@+id/mDescription"
android:layout_
android:layout_
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginTop="70dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:text=""
android:textSize="15sp"
/>
</RelativeLayout>
<RelativeLayout
android:layout_
android:layout_
android:layout_marginTop="10dp"
android:layout_marginBottom="15dp">
<android.support.v7.widget.RecyclerView
android:id="@+id/horizontal_artist_list"
android:layout_
android:layout_
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_
android:layout_
android:layout_margin="15dp"
>
<TextView
android:id="@+id/titleMethods"
android:textColor="@color/textColor"
android:layout_
android:layout_
android:text="Методы и техники"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="10dp"
android:textSize="15sp"
android:textStyle="bold"
tools:ignore="HardcodedText"/>
<TextView
android:id="@+id/mToolsText"
android:layout_
android:layout_
android:textColor="@color/textColor"
android:textSize="15sp"
android:text="
"
android:layout_marginTop="40dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
tools:ignore="HardcodedText"/>
</RelativeLayout>
<LinearLayout
android:layout_
android:layout_
android:layout_marginTop="30dp"
android:layout_marginBottom="15dp"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/horizontal_list"
android:layout_
android:layout_
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_
android:layout_
android:layout_gravity="center"
android:indeterminate="true"
android:indeterminateTintMode="src_atop"
android:indeterminateTint="@color/grey"
/>
</android.support.design.widget.CoordinatorLayout>
【问题讨论】:
【参考方案1】:我建议你使用这个库afollestad/material-dialogs
在开始加载之前显示你的对话框
MaterialDialog.Builder builder = new MaterialDialog.Builder(this)
.title(R.string.title)
.content(R.string.content)
.positiveText(R.string.agree);
MaterialDialog dialog = builder.build();
dialog.show();
完成加载数据后,像这样关闭对话框
dialog.dismiss();
【讨论】:
这就是我要找的:)。【参考方案2】:实际上,有一个非常简单的解决方案。我只是把 progressBar.setVisibility(View.INVISIBLE);进入 for (DataSnapshot child : children) ... 循环,这是我的代码
databaseReference.addChildEventListener(new com.google.firebase.database.ChildEventListener()
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
int count=0;
Log.e("children tag",(dataSnapshot).toString());
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child : children)
count++;
if(count >= dataSnapshot.getChildrenCount())
//stop progress bar here
progressBar.setVisibility(View.INVISIBLE);
mTitleConception.setVisibility(View.VISIBLE);
mTitleDirection.setVisibility(View.VISIBLE);
mTitleMethods.setVisibility(View.VISIBLE);
//Log.e("child tag",child.toString());
Direction direction = child.getValue(Direction.class);
gArray.add(direction);
Log.e("new_dir_added", direction.toString());
Intent intent=getIntent();
String srt=intent.getStringExtra("Number_in_list");
number=Integer.parseInt(srt);
Log.e("arrSize", gArray.size() +" " + number)
;
Log.e("url image erre",(gArray.get(number).toString()));
Log.e("image_url", gArray.get(number).getMUrlImage());
String [] mPictureList=gArray.get(number).getMUrlImage().split(",");
String [] mArtistListImage=gArray.get(number).getMArtistListImage().split(",");
// recycler_artist.setAdapter(new ArtistAdapter(gArray,number));// список художников в Направлении
// recycler_pictures.setAdapter(new HorizontalRVAdapter(gArray,number)); // список картин в направлении
recycler_artist.setAdapter(new ArtistAdapter(mArtistListImage,number));
recycler_pictures.setAdapter(new HorizontalRVAdapter(mPictureList,number));
mConception.setText(gArray.get(number).getConcept());
mDescription.setText(gArray.get(number).getDesc());
mTools.setText(gArray.get(number).getTechnique());
mDirectionTitle.setText(gArray.get(number).getName());
Glide.with(getApplicationContext())
.load(gArray.get(number).getImage())
.placeholder(R.drawable.rama)
.into(mFirstImage);
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
@Override
public void onChildRemoved(DataSnapshot dataSnapshot)
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
@Override
public void onCancelled(DatabaseError databaseError)
);
初始化实例计数以了解您的数据何时加载。
【讨论】:
值得注意的是,如果您的记录为空,这将不起作用。OnChildAdded
只有在你的记录中有数据时才会被调用,如果没有,它不会被调用;导致无限加载循环(就用户所见),直到添加数据。【参考方案3】:
您的代码正在运行吗?根据您发布的代码progressBar=findViewById(R.id.progressBar);
,由于未完成转换,这将引发错误。正确的是progressBar = (ProgressBar) findViewById(R.id.progressBar);
。我已经使用了您的 xml 布局和 aynctask,如下所示
public class MainActivity extends AppCompatActivity
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
new AsyncTask<Object, Void, Void>()
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
@Override
protected void onPreExecute()
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
@Override
protected Void doInBackground(Object... params)
try
Thread.sleep(2000);
catch (InterruptedException e)
e.printStackTrace();
return null;
@Override
protected void onPostExecute(Void aVoid)
super.onPostExecute(aVoid);
progressBar.setVisibility(View.GONE);
.execute();
以上 java 与您的 xml 布局一起工作正常。它完美地显示和隐藏进度条。
【讨论】:
【参考方案4】:您需要为您的活动父布局设置进度条。首先通过 findviewbyid 找到你的父布局
那么只需创建progressbar对象的对象,你不需要为它创建任何xml。
ProgressBar progressBar = new ProgressBar(MainActivity.this,null,android.R.attr.progressBarStyleLarge);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100,100);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
yourParentLayout.addView(progressBar,params);
progressBar.setVisibility(View.VISIBLE); //To show ProgressBar
当你想隐藏progressBar 时使用progressBar.setVisibility(View.GONE);
【讨论】:
以上是关于带有进度条的 Firebase 数据库的主要内容,如果未能解决你的问题,请参考以下文章