我的操作栏上有一个过滤器图标。点击下面的警告对话框打开
[提醒对话框图片] [1]
[1]:https://i.stack.imgur.com/kearr.png。
正如您所看到的,我希望能够根据用户点击的内容进行过滤。我在alertDialog.Example中的每个项目的firebase中都有一个子元素。我想当用户点击书籍时它只返回firebase数据库中的书籍
[数据库图片] [2] [2]:https://i.stack.imgur.com/ku0mF.png。
过滤器图标的逻辑位于我的 MainActivity.java
中package com.example.database;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.FileObserver;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.database.fragment.MyPostsFragment;
import com.example.database.fragment.MyTopPostsFragment;
import com.example.database.fragment.PostListFragment;
import com.example.database.fragment.RecentPostsFragment;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.EmailAuthCredential;
import com.google.firebase.auth.EmailAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity {
private ArrayList mselected;
private ProgressDialog progressDialog;
private EditText email;
private EditText password;
private String EMAIL;
private String PASSWORD;
private DatabaseReference mDatabase;
private MyPostsFragment myPostsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference();
FragmentPagerAdapter mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
private final Fragment[] mFragments = new Fragment[] {
new RecentPostsFragment(),
new MyPostsFragment(),
new MyTopPostsFragment(),
};
@Override
public Fragment getItem(int position) {
return mFragments[position];
}
@Override
public int getCount() {
return mFragments.length;
}
@Override
public CharSequence getPageTitle(int position) {
return getResources().getStringArray(R.array.headings)[position];
}
};
ViewPager mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
findViewById(R.id.fab_new_post).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, PostSomethingActivity.class));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void FilterIcon(){
mselected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setCustomTitle(LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_layout,null))
.setMultiChoiceItems(R.array.Category, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
switch (i){
case 0:
Toast.makeText(getApplicationContext(),"BOOKS",Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(),"PS3",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(),"PS4",Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getApplicationContext(),"PC GAMES",Toast.LENGTH_SHORT).show();
break;
}
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void AccountDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Account Settings");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
});
builder.setItems(R.array.account_setting_options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i){
case 0:
break;
case 1:
DeleteAccount();
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void DeleteAccount(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.delete_account_layout_credentials,null);
builder.setTitle("DELETE USER");
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
email = (EditText)view.findViewById(R.id.email_address);
password = (EditText)view.findViewById(R.id.password_place);
EMAIL = email.getText().toString().trim();
PASSWORD = password.getText().toString().trim();
RemoveUserFromFirebase();
}
}) ;
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
}) ;
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_chat:
startActivity(new Intent(this, ChatActivity.class));
return true;
case R.id.action_logout:
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(this, SignInActivity.class));
finish();
return true;
case R.id.filter_icon:
FilterIcon();
return true;
case R.id.Account_settings:
AccountDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showProgressDialog(){
if(progressDialog==null){
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Deleting User");
}
progressDialog.show();
}
public void hideProgressDialog(){
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
public void RemoveUserFromFirebase(){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
AuthCredential credential = EmailAuthProvider.getCredential(EMAIL,PASSWORD);
showProgressDialog();
user.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
user.delete()
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Incorrect Email or Password",Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
})
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
hideProgressDialog();
startActivity(new Intent(MainActivity.this,CreateAccount.class));
Toast.makeText(getApplicationContext(),"User Successfully Deleted",Toast.LENGTH_LONG).show();
finish();
}
}
}) ;
}
});
}
}
我有一个名为postListFragments的类,用于显示帖子
package com.example.database.fragment;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.example.database.PostDetailActivity;
import com.example.database.R;
import com.example.database.models.Post;
import com.example.database.viewholder.PostViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
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.google.firebase.database.MutableData;
import com.google.firebase.database.Query;
import com.google.firebase.database.Transaction;
public abstract class PostListFragment extends Fragment {
private Fragment currentFragment;
private Activity mActivity;
private DatabaseReference mDatabase;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
public PostListFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mRecycler = rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
mRecycler.setItemViewCacheSize(50);
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.keepSynced(true);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mActivity = getActivity();
final Dialog mDialog = new Dialog(mActivity, R.style.NewDialog);
mDialog.addContentView(
new ProgressBar(mActivity),
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
);
mDialog.setCancelable(true);
mDialog.show();
setLayout();
// Set up FirebaseRecyclerAdapter with the Query
Query postsQuery = getQuery(mDatabase);
FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(postsQuery, Post.class)
.build();
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
@Override
protected void onBindViewHolder(PostViewHolder viewHolder, int position, final Post model) {
final DatabaseReference postRef = getRef(position);
// Determine if the current user has liked this post and set UI accordingly
if (model.stars.containsKey(getUid())) {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
} else {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
@Override
public void onClick(View starView) {
// Need to write to both places the post is stored
DatabaseReference globalPostRef = mDatabase.child("posts").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("user-posts").child(model.uid).child(postRef.getKey());
// Run two transactions
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postRef.getKey());
startActivity(intent);
Log.d("TAG", "onClick: "+ postRef.getKey());
Log.d("TAG", "onClick: "+ postRef);
}
});
}
@Override
public PostViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
return new PostViewHolder(getContext(), inflater.inflate(R.layout.item_post, viewGroup, false));
}
@Override
public void onDataChanged() {
super.onDataChanged();
mDialog.dismiss();
}
};
mRecycler.setAdapter(mAdapter);
}
@Override
public void onStart() {
super.onStart();
if (mAdapter != null) {
mAdapter.startListening();
}
}
@Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
Log.d("postTransaction", "onComplete:" + dataSnapshot.getKey());
}
});
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
public void setLayout(){
StaggeredGridLayoutManager mManager = new StaggeredGridLayoutManager(2,1);
mManager.setReverseLayout(true);
mRecycler.setLayoutManager(mManager);
}
}