Android firebase查询搜索标题问题

时间:2017-02-09 04:46:58

标签: android firebase android-viewpager firebase-realtime-database

这是SearchActivity.java

public class SearchActivity extends AppCompatActivity
{
    /*UI*/
    private EditText mSearchText;
    private Button mSearchBtn;
    private Toolbar mSearchToolbar;

    private FragmentPagerAdapter mPagerAdapter;
    private ViewPager mViewPager;

    private String value;

    private TextWatcher tw;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        mSearchText = (EditText)findViewById(R.id.activity_search_search_text);
        mSearchBtn = (Button)findViewById(R.id.activity_search_search_btn);

        mSearchToolbar = (Toolbar)findViewById(R.id.activity_search_toolbar);
        setSupportActionBar(mSearchToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(null);

        mSearchBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                value = mSearchText.getText().toString();
                Toast.makeText(SearchActivity.this, "value test 1: " + value, Toast.LENGTH_LONG).show();
                searchText(value);
            }
        });
    }

    private void searchText(final String value)
    {
        Toast.makeText(SearchActivity.this, "value test 2: " + value, Toast.LENGTH_LONG).show();
        mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
        {
            private final Fragment[] mFragments = new Fragment[]
                    {
                            new FragmentSearch(value)
                    };

            @Override
            public Fragment getItem(int position)
            {
                return mFragments[position];
            }

            @Override
            public int getCount()
            {
                return mFragments.length;
            }
        };
        mViewPager = (ViewPager) findViewById(R.id.activity_search_view_pager);
        mViewPager.setAdapter(mPagerAdapter);
    }
}

这是FragmentSearch.java

public class FragmentSearch extends MainFragment
{
    public String value;

    public FragmentSearch(String value)
    {
        this.value = value;
    }

    @Override
    public Query getQuery(DatabaseReference databaseReference)
    {
        Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
        Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);

        return postsQuery;
    }
}

这是MainFragment.java

public abstract class MainFragment extends Fragment
{
    private DatabaseReference mDatabase;

    private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
    private RecyclerView mRecycler;
    private LinearLayoutManager mManager;

    public MainFragment()
    {

    }

    @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);

        mDatabase = FirebaseDatabase.getInstance().getReference();

        mRecycler = (RecyclerView)rootView.findViewById(R.id.messages_list);
        mRecycler.setHasFixedSize(true);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);

        mManager = new LinearLayoutManager(getActivity());
        mManager.setReverseLayout(true);
        mManager.setStackFromEnd(true);
        mRecycler.setLayoutManager(mManager);

        Query postsQuery = getQuery(mDatabase);

        mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
                PostViewHolder.class, postsQuery)
        {
            @Override
            protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position)
            {
                final DatabaseReference postRef = getRef(position);

                final String postKey = postRef.getKey();
                viewHolder.itemView.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
//                        Intent intent = new Intent(getActivity(), PostDetailActivity.class);
//                        intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
//                        startActivity(intent);
                    }
                });

                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);
                }

                viewHolder.bindToPost(model, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View starView)
                    {
                        DatabaseReference globalPostRef = mDatabase.child("Post").child(postRef.getKey());
                        DatabaseReference userPostRef = mDatabase.child("UserPost").child(model.uid).child(postRef.getKey());

                        onStarClicked(globalPostRef);
                        onStarClicked(userPostRef);
                    }
                });
            }
        };
        mRecycler.setAdapter(mAdapter);
    }

    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) {
            }
        });
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (mAdapter != null)
        {
            mAdapter.cleanup();
        }
    }

    public String getUid()
    {
        return FirebaseAuth.getInstance().getCurrentUser().getUid();
    }

    public abstract Query getQuery(DatabaseReference databaseReference);

}

这是PostViewHolder.java

public class PostViewHolder extends RecyclerView.ViewHolder
{
    public TextView titleView;
    public TextView authorView;
    public ImageView starView;
    public TextView numStarsView;
    public TextView bodyView;

    public PostViewHolder(View itemView)
    {
        super(itemView);

        titleView = (TextView) itemView.findViewById(R.id.post_title);
        authorView = (TextView) itemView.findViewById(R.id.post_author);
        starView = (ImageView) itemView.findViewById(R.id.star);
        numStarsView = (TextView) itemView.findViewById(R.id.post_num_stars);
        bodyView = (TextView) itemView.findViewById(R.id.post_body);
    }

    public void bindToPost(Post post, View.OnClickListener starClickListener)
    {
        titleView.setText(post.title);
        authorView.setText(post.author);
        numStarsView.setText(String.valueOf(post.starCount));
        bodyView.setText(post.body);

        starView.setOnClickListener(starClickListener);
    }
}

这是Post.java

@IgnoreExtraProperties
public class Post
{
    public String uid;
    public String author;
    public String title;
    public String body;
    public int starCount = 0;
    public String type;

    public Map<String, Boolean> stars = new HashMap<>();

    public Post()
    {
    }

    public Post(String uid, String author, String title, String body, String type)
    {
        this.uid = uid;
        this.author = author;
        this.title = title;
        this.body = body;
        this.type = type;
    }

    @Exclude
    public Map<String, Object> toMap()
    {
        HashMap<String, Object> result = new HashMap<>();
        result.put("uid", uid);
        result.put("author", author);
        result.put("title", title);
        result.put("body", body);
        result.put("starCount", starCount);
        result.put("stars", stars);
        result.put("type", type);

        return result;
    }

}

非常感谢您的阅读。我创建了一个程序来搜索帖子的标题。当我在EditText中键入标题然后按搜索按钮,我的toast1测试,toast2测试和toast3测试给出正确和相同的值,它成功列出我想要的查询。但问题是,当我在删除前一个文本后在EditText中键入不同的文本然后按Enter键,toast3 test(在FragmentSearch.java中)保持不变并且不会更改值。所以,它只是给出了以前的结果,而没有改变结果。任何人都可以帮我这个吗?谢谢!

1 个答案:

答案 0 :(得分:0)

问题是您只需更改FragmentSearch构造函数的值。此构造函数仅调用一次,而不是按Enter键。

您应该更改getQuery方法以将此值作为参数。

在MainFragment.java上:

public abstract Query getQuery(DatabaseReference databaseReference, String value);

在FragmentSearch.java上:

@Override
    public Query getQuery(DatabaseReference databaseReference, String value)
    {
        this.value = value;
        Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
        Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);

        return postsQuery;
    }