简体   繁体   中英

Show Items in a RecyclerView

I have created a SearchActivity and imported into it an ArrayList like this:

In my MainActivity :

private ArrayList<Accordo> getChords() {
    ArrayList<Accordo> chords = new ArrayList<>();

    Accordo a=new Accordo();
    a.setName("Do maggiore");
    a.setNote("Do, Mi, Sol");
    a.setImage(R.drawable.do_maggiore);
    chords.add(a);

    a=new Accordo();
    a.setName("do 5");
    a.setNote("na, na, na");
    a.setImage(R.drawable.do5);
    chords.add(a);

    a=new Accordo();
    a.setName("do 6");
    a.setNote("na,na,na");
    a.setImage(R.drawable.do6);
    chords.add(a);

    //other elements

    return chords;
    }

/** start SearchActivity when ImageButton is pressed */
    ImageButton cerca = (ImageButton) findViewById(R.id.search);
    cerca.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), SearchActivity.class);

            ArrayList<Accordo> chords = new ArrayList<Accordo>();
            intent.putExtra("chords", chords);


            startActivity(intent);
        }
    });

and this is my SearchActivity :

public class SearchActivity extends Activity {
SearchView sv;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_layout);
    ArrayList<Accordo> chords = (ArrayList<Accordo>) getIntent().getSerializableExtra("chords");

    sv = (SearchView) findViewById(R.id.testo_ricerca);
    RecyclerView rv = (RecyclerView) findViewById(R.id.lista_ricerca);

    //SET THE PROPERTIES
    rv.setLayoutManager(new LinearLayoutManager(this));
    rv.setItemAnimator(new DefaultItemAnimator());

    //SET ADAPTER
    final SearchAdapter adapter = new SearchAdapter(this, chords);
    rv.setAdapter(adapter);

    //SEARCH
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            //FILTER AS YOU TYPE
            adapter.getFilter().filter(newText);
            return false;
        }
    });
}
}

Now even though I have created a custom Adapter the RecyclerView in my SearchActivity isn't displaying any Item.

this is my Adapter:

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchHolder> implements Filterable {

Context context;
ArrayList<Accordo> chords, filterList;
SearchFilter filter;


public class SearchHolder extends RecyclerView.ViewHolder {

    //VIEWS
    TextView nome;

    public SearchHolder(View view){
        super(view);
        this.nome = (TextView) view.findViewById(R.id.ricerca_nome);
    }
}

public SearchAdapter(Context ctx, ArrayList<Accordo> chords){
    this.context = ctx;
    this.chords = chords;
    this.filterList = chords;
}


@Override
public SearchHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // convert xml to View Object
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_row, parent, false);

    return new SearchHolder(v);
}

@Override
public void onBindViewHolder(SearchHolder holder, int position) {

    //BIND DATA
    holder.nome.setText(chords.get(position).getNome());

}

@Override
public int getItemCount() {
    return chords.size();
}

@Override
public Filter getFilter() {
    if (filter==null)
        filter = new SearchFilter(filterList, this); //this e' l'adapter stesso
    return filter;
}
}

when I try to build the app I do not get any error, so I really can't figure out why this happens.

As you can see from the code above, I have a custom search_row for my searchRecyclerView , but still the adapter should be set the right way.

Hopefully you can help me out!

EDIT:

this is my SearchFilter.class

public class SearchFilter extends Filter{

SearchAdapter adapter;
ArrayList<Accordo> filterList;

public SearchFilter(ArrayList<Accordo> filterList, SearchAdapter adapter) {
    this.adapter=adapter;
    this.filterList=filterList;
}


@Override
protected FilterResults performFiltering(CharSequence constraint) {
    FilterResults results = new FilterResults();

    //CHECK CONSTRAINT VALIDITY
    if(constraint!=null && constraint.length()>0){
        /**CHANGE TO UPPER*/
        constraint=constraint.toString().toUpperCase();
        /**STORE THE FILTERED CHORDS*/
        ArrayList<Accordo> filteredChords = new ArrayList<>();

        for(int i=0; i<filterList.size();i++){
            //CHECK
            if(filterList.get(i).getNome().toUpperCase().contains(constraint))
                //ADD CHORD TO FILTEREDCHPRDS
                filteredChords.add(filterList.get(i));
        }

        results.count = filteredChords.size();
        results.values = filteredChords;
    } else {
        results.count = filterList.size(); //0
        results.values = filterList; //null
    }

    return results;
}

@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
    adapter.filterList = (ArrayList<Accordo>) results.values;

    //REFRESH
    adapter.notifyDataSetChanged();

}
}

Please check my edited code:

Please edit your Accordo class as below:

public class Accordo implements Serializable {
int image;
String name;
String note;

public String getNote() {
    return note;
}

public void setNote(String note) {
    this.note = note;
}

public Accordo(int image, String name, String note) {
    this.image = image;
    this.name = name;
    this.note=note;
}

public int getImage() {
    return image;
}

public void setImage(int image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

And then edit your Activity class as below:

public class YOUR_SENDING_ACTIVITY extends Activity{

ArrayList<Accordo> chords =null;

      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.YOURLAYOUT);

         chords = new ArrayList<Accordo>();

         chords.add(new Accordo(R.drawable.do_maggiore,"Do maggiore","Do, Mi, Sol"));
         chords.add(new Accordo(R.drawable.do5,"Do 5","Na, na, na"))

         ImageButton cerca = (ImageButton) findViewById(R.id.search);
         cerca.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
                 intent.putExtra("chords", chords);
                 startActivity(intent);
    }
});


}
}

Replace your SearchActivity by below:

public class SearchActivity extends AppCompatActivity {

RecyclerView rv;
SearchView sv;
ArrayList<Accordo> chords = null;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_search);

    chords = (ArrayList<Accordo>) getIntent().getSerializableExtra("chords");

    sv = (SearchView) findViewById(R.id.testo_ricerca);
    rv = (RecyclerView) findViewById(R.id.lista_ricerca);
    rv.setLayoutManager(new LinearLayoutManager(SearchActivity.this, LinearLayoutManager.VERTICAL, false));
    rv.setHasFixedSize(true);

    final SearchAdapter adapter = new SearchAdapter(this, chords);
    rv.setAdapter(adapter);

    //SEARCH
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            //FILTER AS YOU TYPE
            final List<Accordo> filteredModelList = filter(chords, newText);
            adapter.setFilter(filteredModelList);
            return true;
        }
    });

}

private List<Accordo> filter(List<Accordo> models, String query) {
    query = query.toLowerCase();

    final List<Accordo> filteredModelList = new ArrayList<>();
    for (Accordo model : models) {
        final String text = model.getName().toLowerCase();
        if (text.contains(query)) {
            filteredModelList.add(model);
        }
    }
    return filteredModelList;
}
}

And SearchAdapter with below class:

public class SearchAdapter  extends RecyclerView.Adapter<SearchAdapter.SearchHolder>{

Context context;
ArrayList<Accordo> chords;

public class SearchHolder extends RecyclerView.ViewHolder {

    //VIEWS
    TextView nome;

    public SearchHolder(View view){
        super(view);
        this.nome = (TextView) view.findViewById(R.id.ricerca_nome);
    }
}

public SearchAdapter(Context ctx, ArrayList<Accordo> chords){
    this.context = ctx;
    this.chords = chords;
    //        this.filterList = chords;
}


@Override
public SearchHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // convert xml to View Object
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_row, parent, false);

    return new SearchHolder(v);
}

@Override
public void onBindViewHolder(SearchHolder holder, int position) {

    //BIND DATA
    holder.nome.setText(chords.get(position).getName());

}

@Override
public int getItemCount() {
    return chords.size();
}

public void setFilter(List<Accordo> accordoList) {
    chords = new ArrayList<>();
    chords.addAll(accordoList);
    notifyDataSetChanged();
}

}

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Test extends AppCompatActivity implements View.OnClickListener { 
    private List<Model> list = new ArrayList<Model>();
    private Model model; // Here model would be your Accordo class.

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

        for(int i=0; i<10; i++) {
            model = new Model(); // You've added 3 data in your question, while I've added 10 data for sample code.
            model.setName("My Name is " + i);
            model.setNote("My Note is " + i);
            list.add(model);
        }

        findViewById(R.id.btn_send_data).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send_data:
                Intent intent = new Intent(this, SearchActivity.class);
                intent.putExtra("data", (Serializable) list);  // This will pass the whole arraylist to search activity
                startActivity(intent);
                break;
        }
    }
}

public class SearchActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private List<Model> list;

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

    try {
        list = (List<Model>) getIntent().getSerializableExtra("data");  // Here you will get that list using Intent
        Log.e("data===", list.get(0).getName());
    } catch(Exception e) {
        e.printStackTrace();
    }

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

    RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(this, list); // Added that arraylist in my recyclerview adapter and that's it....
    recyclerView.setAdapter(recyclerViewAdapter);
}

private class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

    private List<Model> data = new ArrayList<Model>();
    private Context mContext;

    public RecyclerViewAdapter(Context ctx, List<Model> mData) {
        mContext = ctx;
        data = mData;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        view = LayoutInflater.from(mContext).inflate(R.layout.row_tv, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        try {
            if(!data.isEmpty()) {
                holder.tvNote.setText(data.get(position).getNote());
                holder.tvName.setText(data.get(position).getName());
            } else {
                holder.tvNote.setText("No data available....");
                holder.tvName.setText("No data available....");
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    //My ViewHolder class
    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView tvName, tvNote;

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

            tvName = (TextView) itemView.findViewById(R.id.tv_name);
            tvNote = (TextView) itemView.findViewById(R.id.tv_note);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM