Два поиска Редактировать тексты в одном упражнении, но работает только один - PullRequest
0 голосов
/ 12 октября 2019

Showing an image with searching car name and it works, both same queries but location does not work

Как вы видите здесь, я пытаюсь объединить две панели поиска в одну операцию, одну для поиска по названию автомобиля, а другую - для поиска по местоположению. Оба запроса одинаковы и должны быть одинаковыми, но работает только поиск по названию автомобиля, но не местоположение по какой-то причине. Когда я выполняю поиск по местоположению, он просто выводит пустые сообщения как «0 Результатов».

ЯПопытка привести оба поиска в соответствие друг с другом, значит, если я ищу по названию автомобиля с помощью lexus, результаты должны дать мне все, что связано с lexus, и если я ищу местоположение, возможно, в Дубае, я хочу только Все Lexus в Дубае.

IЯ не совсем уверен, понимаю ли я, как оба работают друг с другом.

package com.capstone.araba.Fragments;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.capstone.araba.Adapter.PostAdapter;
import com.capstone.araba.Model.Post;
import com.capstone.araba.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class HomeFragment extends Fragment
{

    private PostAdapter postAdapter;
    private List<Post> postList;



    private List<String> followingList;

    private ProgressBar progress_circular;
    private EditText search_bar, search_bar2;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_home_fragment, container, false);

        RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        mLayoutManager.setReverseLayout(true);
        mLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLayoutManager);
        search_bar = view.findViewById(R.id.search_bar);
        search_bar2 = view.findViewById(R.id.search_bar2);
        postList = new ArrayList<>();
        postAdapter = new PostAdapter(getContext(), postList);
        recyclerView.setAdapter(postAdapter);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(),
                LinearLayoutManager.HORIZONTAL, false);

        progress_circular = view.findViewById(R.id.progress_circular);

        checkFollowing();
        readPostsSearch();
//        readPostsSearch2();

        search_bar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchPosts(charSequence.toString().toLowerCase());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        search_bar2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence2, int i, int i1, int i2) {
                searchPosts2(charSequence2.toString().toLowerCase());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        return view;
    }

    private void searchPosts(String s){
        Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("carType")
                .startAt(s)
                .endAt(s+"\uf8ff");



        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                postList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    Post post = snapshot.getValue(Post.class);
                    postList.add(post);
                }

                postAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    private void searchPosts2(String l)
    {
        Query querys = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("location")
                .startAt(l)
                .endAt(l+"\uf8ff");

        querys.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                postList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    Post post = snapshot.getValue(Post.class);
                    postList.add(post);
                }

                postAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }


    private void readPostsSearch() {

        final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (search_bar.getText().toString().equals("") || search_bar2.getText().toString().equals("")) {
                    postList.clear();
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        Post post = snapshot.getValue(Post.class);

                        postList.add(post);

                    }

                    postAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
package com.capstone.araba.Model;

public class Post {
    private String postid;
    private String postimage;
    private String publisher;
    private String carType;
    private String price;
    private String model;
    private String distance;
    private String color;
    private String location;


    public Post(String postid, String postimage, String publisher, String carType, String price, String model, String distance, String color, String location) {
        this.postid = postid;
        this.postimage = postimage;
        this.publisher = publisher;
        this.carType = carType;
        this.price = price;
        this.model = model;
        this.distance = distance;
        this.color = color;
        this.location = location;
    }

    public Post() {
    }

    public String getPostid() {
        return postid;
    }

    public void setPostid(String postid) {
        this.postid = postid;
    }

    public String getPostimage() {
        return postimage;
    }

    public void setPostimage(String postimage) {
        this.postimage = postimage;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getDistance() {
        return distance;
    }

    public void setDistance(String distance) {
        this.distance = distance;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...