Android RecyclerView不会显示任何数据
主要活动Android RecyclerView不会显示任何数据,android,firebase,android-recyclerview,Android,Firebase,Android Recyclerview,主要活动 <RelativeLayout 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_h
<RelativeLayout 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"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recyclerview"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/floatingactionbutton"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/seekbar"
android:layout_above="@+id/floatingactionbutton"/>
</RelativeLayout>
视频适配器
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.MyViewHolder> {
private List<Video> videoList;
private Context context;
public static final String Position="AdapterPosition";
public VideoAdapter(List<Video> videoList, Context context) {
this.videoList = videoList;
this.context = context;
}
@Override
public VideoAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, null);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(VideoAdapter.MyViewHolder holder, int position) {
Video contacts = videoList.get(position);
holder.textView.setText("Hi");
Toast.makeText(context,contacts.getVideoUrl().toString(),Toast.LENGTH_SHORT).show();
}
@Override
public int getItemCount() {
return videoList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView textView;
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
textView = (TextView) itemView.findViewById(R.id.textview);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
}
}
}
公共类VideoAdapter扩展了RecyclerView.Adapter{
私人列表视频列表;
私人语境;
公共静态最终字符串位置=“AdapterPosition”;
公共视频适配器(列表视频列表、上下文){
this.videoList=视频列表;
this.context=上下文;
}
@凌驾
public VideoAdapter.MyViewHolder onCreateViewHolder(视图组父级,int-viewType){
视图=LayoutFlater.from(上下文)。充气(R.layout.list_项,空);
返回新的MyViewHolder(视图);
}
@凌驾
public void onBindViewHolder(VideoAdapter.MyViewHolder,int位置){
视频联系人=videoList.get(位置);
holder.textView.setText(“Hi”);
Toast.makeText(上下文,contacts.getVideoUrl().toString(),Toast.LENGTH_SHORT.show();
}
@凌驾
public int getItemCount(){
返回videoList.size();
}
公共类MyViewHolder扩展了RecyclerView.ViewHolder实现了View.OnClickListener{
公共文本视图文本视图;
私人最终语境;
公共MyViewHolder(查看项目视图){
超级(项目视图);
context=itemView.getContext();
textView=(textView)itemView.findViewById(R.id.textView);
setOnClickListener(这个);
}
@凌驾
公共void onClick(视图v){
}
}
}
主要活动
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
private static final int RC_PHOTO_PICKER = 2;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private SeekBar seekBar;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
NotificationCompat.Builder notificationBuilder;
VideoAdapter videoAdapter;
List<Video> videoList;
NotificationManager notificationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingactionbutton);
videoList = new ArrayList();
// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
seekBar = (SeekBar) findViewById(R.id.seekbar);
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("videomessages");
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("videos");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
onSignedInInitialize(user.getDisplayName());
} else {
// User is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(
AuthUI.EMAIL_PROVIDER,
AuthUI.GOOGLE_PROVIDER)
.build(),
RC_SIGN_IN);
}
}
};
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
attachDatabaseReadListener();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
} else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
new MyAsyncTask().execute(selectedImageUri);
// Get a reference to store file at chat_photos/<FILENAME>
}
;
}
@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
@Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
attachDatabaseReadListener();
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
private void attachDatabaseReadListener() {
mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
videoList.clear();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Video postSnapshotValue = postSnapshot.getValue(Video.class);
if (!videoList.contains(postSnapshotValue)) {
videoList.add(postSnapshotValue);
Log.i(TAG, "onDataChange: " + videoList);
}
}
videoAdapter = new VideoAdapter(videoList, getApplicationContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setAdapter(videoAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class MyAsyncTask extends AsyncTask<Uri, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Uri... params) {
StorageReference photoRef = mChatPhotosStorageReference.child(params[0].getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(params[0])
.addOnSuccessListener(MainActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
// progressBar.setVisibility(View.VISIBLE);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Video video = new Video(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(video);
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
seekBar.setProgress(progress);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("Download in progress")
.setContentIntent(contentIntent(getApplicationContext()))
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
}
notificationManager = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
for (int incr = progress; incr <= 100; incr += 5) {
notificationBuilder.setProgress(100, progress, false);
notificationManager.notify(20, notificationBuilder.build());
}
if(progress>=100){
notificationBuilder.setContentText("Download complete").setProgress(0, 0, false);
notificationManager.notify(20, notificationBuilder.build());
}
}
});
return null;
}
@Override
protected void onPostExecute(Void integer) {
super.onPostExecute(integer);
// Do the "lengthy" operation 20 times
}
}
private PendingIntent contentIntent(Context context) {
Intent startActivityIntent = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(
context,
0,
startActivityIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
public类MainActivity扩展了AppCompatActivity{
私有静态最终字符串TAG=“MainActivity”;
公共静态最终字符串ANONYMOUS=“ANONYMOUS”;
公共静态最终整数RC_SIGN_IN=1;
专用静态最终int RC_PHOTO_PICKER=2;
私人弦乐博物馆名称;
//Firebase实例变量
私有FirebaseDatabase mFirebaseDatabase;
私有数据库引用mMessagesDatabaseReference;
私有ChildEventListener-mChildEventListener;
私有FirebaseAuth mFirebaseAuth;
私有FirebaseAuth.AuthStateListener mAuthStateListener;
私有FirebaseStorage mFirebaseStorage;
私有存储引用mChatPhotosStorageReference;
私有FirebaseRemoteConfig mFirebaseRemoteConfig;
私人SeekBar SeekBar;
私人回收站;
私有浮动操作按钮浮动操作按钮;
NotificationCompat.Builder notificationBuilder;
视频适配器;
列表视频列表;
通知经理通知经理;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername=匿名;
recyclerView=(recyclerView)findViewById(R.id.recyclerView);
floatingActionButton=(floatingActionButton)findViewById(R.id.floatingActionButton);
videoList=新的ArrayList();
//初始化Firebase组件
mFirebaseDatabase=FirebaseDatabase.getInstance();
mFirebaseAuth=FirebaseAuth.getInstance();
mFirebaseStorage=FirebaseStorage.getInstance();
mFirebaseRemoteConfig=FirebaseRemoteConfig.getInstance();
seekBar=(seekBar)findViewById(R.id.seekBar);
mMessagesDatabaseReference=mFirebaseDatabase.getReference().child(“视频消息”);
mChatPhotosStorageReference=mFirebaseStorage.getReference().child(“视频”);
mAuthStateListener=new FirebaseAuth.AuthStateListener(){
@凌驾
AuthStateChanged上的公共void(@NonNull FirebaseAuth FirebaseAuth){
FirebaseUser=firebaseAuth.getCurrentUser();
如果(用户!=null){
//用户已登录
onSignedInitialize(user.getDisplayName());
}否则{
//用户已注销
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.CreateSignInEntBuilder()
.setIsSmartLockEnabled(错误)
.setProviders(
AuthUI.EMAIL\u提供程序,
AuthUI.GOOGLE_提供程序)
.build(),
RC_登录);
}
}
};
floatingActionButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
意向意向=新意向(意向.行动\u获取\u内容);
intent.setType(“video/*”);
intent.putExtra(仅intent.EXTRA_本地_,true);
startActivityForResult(Intent.createChooser(Intent,“使用完成操作”),RC\u PHOTO\u PICKER;
}
});
attachDatabaseReadListener();
}
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==RC\u登录){
if(resultCode==RESULT\u OK){
//登录成功,设置用户界面
Toast.makeText(这是“已登录!”,Toast.LENGTH_SHORT.show();
}else if(resultCode==RESULT\u取消){
//用户已取消登录,请完成活动
Toast.makeText(这是“已取消登录”,Toast.LENGTH_SHORT).show();
完成();
}
}else if(requestCode==RC\u PHOTO\u PICKER&&resultCode==RESULT\u OK){
Uri selectedImageUri=data.getData();
新建MyAsyncTask().execute(选择图像URI);
//在聊天室获取存储文件的引用/
}
;
}
@凌驾
受保护的void onResume(){
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStat
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.MyViewHolder> {
private List<Video> videoList;
private Context context;
public static final String Position="AdapterPosition";
public VideoAdapter(List<Video> videoList, Context context) {
this.videoList = videoList;
this.context = context;
}
@Override
public VideoAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, null);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(VideoAdapter.MyViewHolder holder, int position) {
Video contacts = videoList.get(position);
holder.textView.setText("Hi");
Toast.makeText(context,contacts.getVideoUrl().toString(),Toast.LENGTH_SHORT).show();
}
@Override
public int getItemCount() {
return videoList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView textView;
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
textView = (TextView) itemView.findViewById(R.id.textview);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
}
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
private static final int RC_PHOTO_PICKER = 2;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private SeekBar seekBar;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
NotificationCompat.Builder notificationBuilder;
VideoAdapter videoAdapter;
List<Video> videoList;
NotificationManager notificationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingactionbutton);
videoList = new ArrayList();
// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
seekBar = (SeekBar) findViewById(R.id.seekbar);
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("videomessages");
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("videos");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
onSignedInInitialize(user.getDisplayName());
} else {
// User is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(
AuthUI.EMAIL_PROVIDER,
AuthUI.GOOGLE_PROVIDER)
.build(),
RC_SIGN_IN);
}
}
};
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
attachDatabaseReadListener();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
} else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
new MyAsyncTask().execute(selectedImageUri);
// Get a reference to store file at chat_photos/<FILENAME>
}
;
}
@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
@Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
attachDatabaseReadListener();
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
private void attachDatabaseReadListener() {
mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
videoList.clear();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Video postSnapshotValue = postSnapshot.getValue(Video.class);
if (!videoList.contains(postSnapshotValue)) {
videoList.add(postSnapshotValue);
Log.i(TAG, "onDataChange: " + videoList);
}
}
videoAdapter = new VideoAdapter(videoList, getApplicationContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setAdapter(videoAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class MyAsyncTask extends AsyncTask<Uri, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Uri... params) {
StorageReference photoRef = mChatPhotosStorageReference.child(params[0].getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(params[0])
.addOnSuccessListener(MainActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
// progressBar.setVisibility(View.VISIBLE);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Video video = new Video(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(video);
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
seekBar.setProgress(progress);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("Download in progress")
.setContentIntent(contentIntent(getApplicationContext()))
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
}
notificationManager = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
for (int incr = progress; incr <= 100; incr += 5) {
notificationBuilder.setProgress(100, progress, false);
notificationManager.notify(20, notificationBuilder.build());
}
if(progress>=100){
notificationBuilder.setContentText("Download complete").setProgress(0, 0, false);
notificationManager.notify(20, notificationBuilder.build());
}
}
});
return null;
}
@Override
protected void onPostExecute(Void integer) {
super.onPostExecute(integer);
// Do the "lengthy" operation 20 times
}
}
private PendingIntent contentIntent(Context context) {
Intent startActivityIntent = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(
context,
0,
startActivityIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
@Override public VideoAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent,false);
return new MyViewHolder(view);
}
compile 'com.android.support:recyclerview-v7:25.0.1'
getApplicationContext()
MainActivity.this
this
public class Video { private String videoUrl; public Video() { } public Video(String videoUrl) { this.videoUrl = videoUrl; } public String getVideoUrl() { return videoUrl; } public void setVideoUrl(String videoUrl) { this.videoUrl = videoUrl; } }``