2016-07-04 2 views
0

Я создал SearchActivity и импортированные в него в ArrayList так:Показать товары в RecyclerView

В моей 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); 
     } 
    }); 

и это мой 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; 
     } 
    }); 
} 
} 

Теперь, хотя я создал пользовательский адаптер, RecyclerView в моем SearchActivity не отображает ни одного элемента.

это мой адаптер:

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

, когда я пытаюсь построить приложение я не получить какие-либо ошибки, так что я действительно не могу понять, почему это происходит.

Как вы можете видеть из приведенного выше кода, у меня есть пользовательский search_row для моего searchRecyclerView, но адаптер должен быть установлен правильно.

Надеюсь, вы можете мне помочь!

EDIT:

это мой 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(); 

} 
} 

ответ

1

Пожалуйста, проверьте мой отредактированный код:

Пожалуйста, измените ваш класс Accordo, как показано ниже:

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

Затем отредактируйте свой класс Activity как belo ш:

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


} 
} 

Заменить SearchActivity на ниже:

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

И SearchAdapter с ниже класса:

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

}

+0

К сожалению, я забыл включить в список , конечно, есть вещи в нем, у меня есть это в моей MainActivity – Daniele

+0

Значит, он работает прямо сейчас? – Drv

+0

Я обновил вопрос. Нет, я забыл добавить его в вопрос, но у меня это было в моем проекте. – Daniele

1
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); 
     } 
    } 
} 
+0

Спасибо за ответ! не могли бы вы также дать объяснение? – Daniele

+0

Да, конечно, скажите, что вы не получаете в моем коде ??? – Bhavnik

+0

Прежде всего, должен ли я заменить весь этот Accordo.class на этот? что делает цикл for? почему он идет только до 10? – Daniele