How to search within a Recycleview?

Asked

Viewed 466 times

1

I have a Recycleview that receives data from Firebase, each data creates a box in the layout with the information contained within each key there in Firebase. I want you to search for a certain data box in this list and show me on the screen. For example, in a multi-button layout, when the first button is clicked, I want you to open Recycleview and click for me a certain data box that is inside this list. I need to know if it is possible to do this with Recycleview, if negative, how this model could be implemented.

public class ShowImagesActivity extends AppCompatActivity {
    private RecyclerView recyclerView;

    private RecyclerView.Adapter adapter;

    private DatabaseReference mDatabase;

    private ProgressDialog progressDialog;

    private List<Upload> uploads;

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

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        progressDialog = new ProgressDialog(this);

        uploads = new ArrayList<>();

        progressDialog.setMessage("Aguardando...");
        progressDialog.show();
        mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {

                progressDialog.dismiss();

                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Upload upload = postSnapshot.getValue(Upload.class);
                    uploads.add(upload);
                }

                adapter = new MyAdapter(getApplicationContext(), uploads);

                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                progressDialog.dismiss();
            }
        });

    }
}

upload class

public class Upload{

        public String name;
        public String descricao;
        public String local;
        public String url;

    public Upload() {
    }

    public Upload(String name, String descricao,String local,String url) {
        this.name = name;
        this.descricao = descricao;
        this.local = local;
        this.url= url;
    }

    public String getName() {
        return name;
    }
    public String getDescricao() {
        return descricao;
    }
    public String getLocal() {
        return local;
    }
    public String getUrl() {
        return url;
    }
}

showmap class:

public class ShowMap extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;
    public RecyclerView recyclerView;
    public List<Upload> uploads;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_activity);
        FirebaseApp.initializeApp(this);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    }
    public int findInUploadsArray(List<Upload> uploads, String name){
        for(int i = 0; i < uploads.size(); i++){
            // supondo que sua classe possui um atributo "nome" e você está procurando um nome específico
            if(uploads.get(i).getName().equals(name)) return i;
        }

        return -1;
    }



    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        uploads = new ArrayList<>();
        recyclerView = new RecyclerView(getApplicationContext());

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();



        ref.child("uploads").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Iterator<DataSnapshot> dataSnapshotsChat =  dataSnapshot.getChildren().iterator();

                while (dataSnapshotsChat.hasNext()) {
                    DataSnapshot dataSnapshotChild = dataSnapshotsChat.next();
                    String latitudeL = dataSnapshotChild.child("latitude").getValue().toString();
                    String longitudeL = dataSnapshotChild.child("longitude").getValue().toString();
                    double latitude1 = Double.parseDouble((latitudeL));
                    double longitude1 = Double.parseDouble(longitudeL);
                    LatLng local = new LatLng(latitude1, longitude1);
                    final String title = dataSnapshotChild.child("name").getValue().toString();


                    mMap.addMarker(new MarkerOptions().position(local).title(title));
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(local, 10));
                    Log.v("log",""+local);
                    Log.v("log",""+title);


                    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {

                            int position = findInUploadsArray(uploads,marker.getTitle());
                            Log.v("log",""+marker.getTitle());

                            recyclerView.scrollToPosition(position);
                            return true;
                        }
                    });
                }}

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });

    }

}
  • This solves your problem: https://stackoverflow.com/a/30429439/2570426

  • acklay, I need something automated, when clicking a button is automatically directed to the data that is somewhere in the list.

  • If you have already done something, it would be interesting to edit the question is to insert what there is done.

  • I put the code above.

1 answer

0

How do you store the data in a ArrayList<Upload>, create a method that finds what you want in this Array (can be a loop with an internal if) and return the position of it.

Ex:

public int findInUploadsArray(List<Upload> uploads, String nome){
  for(int i = 0; i < uploads.size(); i++){
    // supondo que você está procurando um box por um nome específico
    if(uploads.get(i).getName().equals(nome)) return i;
  }

  return -1;
}

Then you can move Recyclerview to this position:

Ex:

// Coloque esse código no clickListener dos botões. 
// A variável dadoProcurado fica por sua conta preencher de acordo com o botão clicado
int position = findInUploadsArray(uploads, dadoProcurado);   
recyclerView.scrollToPosition(position);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.