带有进度条的Firebase数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带有进度条的Firebase数据库相关的知识,希望对你有一定的参考价值。
我有个问题。从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_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_light"
>
<!-- полосу на тулбаре я убрал, теперь баг появился статус бар выпрыгивает во время прокрутки -->
<android.support.design.widget.AppBarLayout
android:id="@+id/main.appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/main.collapsing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="220dp"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
tools:ignore="ContentDescription"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.88">
<TextView
android:id="@+id/main_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/mConceptionLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:layout_marginBottom="15dp"
>
<TextView
android:id="@+id/mConception"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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_width="wrap_content"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="15dp"
android:layout_marginBottom="15dp"
>
<TextView
android:id="@+id/titleDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
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_width="wrap_content"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="15dp">
<android.support.v7.widget.RecyclerView
android:id="@+id/horizontal_artist_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
>
<TextView
android:id="@+id/titleMethods"
android:textColor="@color/textColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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_width="wrap_content"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="15dp"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/horizontal_list"
android:layout_width="match_parent"
android:layout_height="220dp"
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_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminate="true"
android:indeterminateTintMode="src_atop"
android:indeterminateTint="@color/grey"
/>
</android.support.design.widget.CoordinatorLayout>
我建议你使用这个库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();
实际上,有一个非常简单的解决方案。我只是把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) {
}
});
你的代码在运行吗?根据你发布的代码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布局。它完美地显示和隐藏进度条。
您需要将进度条设置为活动父布局。首先通过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数据库的主要内容,如果未能解决你的问题,请参考以下文章
用于 onActivityCreated 中通用图像加载器的片段中进度条的 NullPointerException