I am making an application that takes all users of a table in Firebase and shows them in CardView, but I would like administrators to appear before the other users.
For this differentiation, all users were saved to the system with an attribute called type which says whether they are normal users or administrators.
This is TelaChat.java file:
public class TelaChat extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseRecyclerOptions<Usuario> options;
private FirebaseRecyclerAdapter<Usuario, ChatAdapter> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
setTitle("Tela de Chat");
recyclerView = findViewById(R.id.cm_rv_membros);
recyclerView.setHasFixedSize(true);
databaseReference = FirebaseDatabase.getInstance().getReference().child("usuario");
options = new FirebaseRecyclerOptions.Builder<Usuario>().setQuery(databaseReference, Usuario.class).build();
adapter = new FirebaseRecyclerAdapter<Usuario, ChatAdapter>(options) {
#Override
protected void onBindViewHolder(ChatAdapter holder, int position, Usuario model) {
Picasso.with(holder.ivFoto.getContext()).load(model.getImageURL()).centerCrop().resize(140, 140).transform(new ImageTrans_CircleTransform2()).into(holder.ivFoto);
holder.tvNome.setText(model.getNome());
holder.tvTipo.setText(model.getTipo());
}
#Override
public ChatAdapter onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_card, parent, false);
return new ChatAdapter(view);
}
};
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 1);
recyclerView.setLayoutManager(gridLayoutManager);
adapter.startListening();
recyclerView.setAdapter(adapter);
}
This is ChatAdapter.java file:
public class ChatAdapter extends RecyclerView.ViewHolder{
public ImageView ivFoto;
public TextView tvNome;
public TextView tvTipo;
public ChatAdapter(View itemView) {
super(itemView);
ivFoto = itemView.findViewById(R.id.cc_iv_foto);
tvNome = itemView.findViewById(R.id.cc_tv_nome);
tvTipo = itemView.findViewById(R.id.cc_tv_tipo);
}
}
I've looked for some tutorials on the internet but none has specified what I want to do. Can someone help me?
Try to add this: orderByChild("type")
databaseReference = FirebaseDatabase.getInstance().getReference().child("usuario").orderByChild("type");
Or here:
options = new FirebaseRecyclerOptions.Builder<Usuario>().setQuery(databaseReference.orderByChild("type"), Usuario.class).build();
Sorry I can't test it right now, hope it works.
I have an idea may help in this set a flag for example called position with initial value 0 and create a new list to order on it and check the type and if is an admin add him in the list with position value and increase the position value else add the value without index
private int position = 0;
private List<Users> myList = new ArrayList();
for(int i = 0 ; i < usersList.size ; i++){
if(userList.get(i).getType.equal("adminstrator")){
myList.add(position,userList.get(i))
position++;
}else{
myList.add(usetList.get(i))
}
}
after set this list "myList" to the recyclerview adapter
Related
My RecyclerView does not update.Even when i call adapterNotifyDataSetChanged().Questions,and answers are loaded properly but items in recycler do not.
They just stay same,not even reordered.
MainActivity
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
EditText edit;
Button provjeri;
List<Item> questions;
int curquestion=0;
TextView pitanje;
public List<String> suggestSource = new ArrayList<>();
public static char[] user_submit_answer;
public char[]answeri;
String corect_answer;
// data to populate the RecyclerView with
String[]data = {"a","b","c","č","ć","d","đ","e","f","g","h","i","j","k","l","m"
,"n","o","p","r","s","š","t","u","v","z","ž"};
String[]simpleArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit=findViewById(R.id.editText);
provjeri=findViewById(R.id.button);
pitanje=findViewById(R.id.textView);
Random random=new Random();
questions=new ArrayList<>();
for(int i=0;i<Database.questions.length;i++){
questions.add(new Item(Database.questions[i], answers[i]));
}
pitanje.setText(questions.get(curquestion).getQuestion());
// data to populate the RecyclerView with
// String[]data = {"a","b","c","č","ć","d","đ","e","f","g","h","i","j","k","l","m"
// ,"n","o","p","r","s","š","t","u","v","z","ž"};
corect_answer=(questions.get(curquestion).getAnswer());
answeri=corect_answer.toCharArray();
user_submit_answer=new char[answeri.length];
suggestSource.clear();
for(char item:answeri)
{
//Add logo name to list
suggestSource.add(String.valueOf(item));}
for(int i = answeri.length; i< answeri.length*2; i++){
suggestSource.add(data[random.nextInt(data.length)]);
}
Collections.shuffle(suggestSource);
simpleArray = new String[ suggestSource.size() ];
suggestSource.toArray( simpleArray );
// set up the RecyclerView
final RecyclerView recyclerView = findViewById(R.id.recyclerView);
int numberOfColumns = 6;
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
adapter = new MyRecyclerViewAdapter(this, simpleArray);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
provjeri.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(edit.getText().toString().equalsIgnoreCase(questions.get(curquestion).getAnswer())){
curquestion++;
pitanje.setText(questions.get(curquestion).getQuestion());
corect_answer=(questions.get(curquestion).getAnswer());
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,"blblblbl",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this,"netacno",Toast.LENGTH_SHORT).show();
}
}
});
//("btw:why must write so much unnecesary text,to accept my question"and still not enough to post question,so wtf i must write some novel here,maybe make up some problems thath do not even exist,or just ....wtf maaaaaaaaan)//
Since nobody didnt answered,i found answer by myself.So the thing was i didnt refresh adapter after updating it,and it was called before it was created
I am creating an AlertDialog custom class, called ActionDialog, which will contains a RecyclerView containing Buttons. I have a List of Button that I populate in the custom class ActionDialog (for now i just populate with useless Button just to try to use it, except one which I create in another class).
The problem is that when i create the AlertDialog, all buttons are showing empty, they are showed but with no text/no clicklistener (as you can see in the image below).
(I have added a custom ActionListener to a Button in another class and then give it as parameter in ActionDialog class. Will it lose the ActionListener?)
Here is the result.
I will leave here my ActionDialog class code, and the adapter class.
This is ActionDialog class:
public class ActionDialog extends AlertDialog{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private Button actionButtons;
private List<Button> buttons;
private Activity context;
public ActionDialog(#NonNull Activity context, Button actionButtons) {
super(context);
this.context = context;
this.actionButtons = actionButtons;
buttons = new ArrayList<>();
initButton();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
}
private void initButton(){
initZoneButton();
//TODO init all buttons
Button b1 = new Button(context);
b1.setText("ExampleButton1");
Button b2 = new Button(context);
b2.setText("ExampleButton2");
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a;
}
});
buttons.add(b1);
buttons.add(b2);
}
private void initZoneButton(){
buttons.add(actionButtons); //this button is created in another class and give as parameter in this class
}
public void createDialog(){
Builder mBuilder = new Builder(context);
View view = context.getLayoutInflater().inflate(R.layout.dialog_actionbuttons_layout, null);
mRecyclerView = view.findViewById(R.id.dialog_actionbuttons_rv);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ActionButtonsAdapter(buttons);
mRecyclerView.setAdapter(mAdapter);
mBuilder.setView(view);
mBuilder.create().show();
}
}
Here is the RecyclerView adapter class:
public class ActionButtonsAdapter extends RecyclerView.Adapter<ActionButtonsAdapter.ViewHolder>{
private List<Button> dataButtons;
static class ViewHolder extends RecyclerView.ViewHolder {
Button actionButton;
ViewHolder(View v) {
super(v);
actionButton = v.findViewById(R.id.action_button_rv);
}
}
public ActionButtonsAdapter(List<Button> dataButtons){
this.dataButtons = dataButtons;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.actionButton = dataButtons.get(position);
//i think the problem is here, maybe
}
#Override
public ActionButtonsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_actionbutton_layout, parent, false);
return new ViewHolder(v);
}
#Override
public int getItemCount() {
return dataButtons.size();
}
}
I think in the onBindViewHolder method you should do what ever you want to do with your button.
Also there is no need for the list of buttons here. Make a list the data you need to be held in the Buttons RecyclerView.
I have a RecyclerView that will display Genres for restaurants lets say, So I will create a List of strings to hold these genres names (chickens, meats, etc,..)
Setting its text
holder.actionButton.setText(// Make use of position here);
Or Click Listeners.
Update
You can check google samples for recyclerview here
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, "Element " + position + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
viewHolder.getTextView().setText(mDataSet[position]);
}
wheres mDataset is Array of Strings.
I have two list<> With different data but that are equal in size , I want to use these two lists in one RecyclerView And I want to fill RecyclerView items using these two lists, but items that are filled with the second list are empty in RecyclerView and Just Items that are filled with the first list are show.
i dont know how to use both List in one recyclerView.
RecyclerViewAdapter :
public class RecyclerViewAdapter_StudentList extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private List<StudentTable> studentData = new ArrayList<>();//First List
private List<PerformanceTable> performanceData = new ArrayList<>();//Second List
private Context context;
private DatabaseHandler database;
public RecyclerViewAdapter_StudentList(Context context , List<StudentTable> tableData , List<PerformanceTable> performanceData)
{
this.context = context;
this.studentData = tableData;
this.performanceData = performanceData;
database = new DatabaseHandler(context);
}
public class itemHolder extends RecyclerView.ViewHolder
{
TextView studentName ;
TextView studentPositive;
TextView studentNegative;
public itemHolder(View itemView)
{
super(itemView);
studentName = (TextView) itemView.findViewById(R.id.item_txt_StudentList_StudentName);
studentPositive = (TextView) itemView.findViewById(R.id.item_StudentList_Positive);
studentNegative = (TextView) itemView.findViewById(R.id.item_StudentList_Negative);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerview_item_student_list, parent, false);
return new itemHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final itemHolder itemHolder = (itemHolder) holder;
final String studentName = studentData.get(position).getStudentName();
itemHolder.studentName.setText(String.valueOf(studentName));
int pCount = performanceData.get(position).getPositive();
int nCount = performanceData.get(position).getNegative();
itemHolder.studentPositive.setText(String.valueOf(pCount));//These items are empty
itemHolder.studentNegative.setText(String.valueOf(nCount));//These items are empty
.
.
.
}
public int getItemCount()
{
return studentData.size();
}
#Nima Khalili
please go through below links this might what you r asking for.
https://stackoverflow.com/a/26245463/4361438
https://www.journaldev.com/12372/android-recyclerview-example
i will explain it if this will fix your problem.
You can do something like this....
List<Model1> list1 = new ArrayList<>();
List<Model2> list2 = new ArrayList<>();
List<BothModels> list3 = new ArrayList<>();
list1.add(new Model1(whatever here));
//add more to list1
list2.add(new Model2(whatever here));
//add more to list2
list3.addAll(list1);
list3.addAll(list2);
Now that everything is in list3, you can use that list to fill in your recycler view.
Its also possible to achieve it with polymorphism... using an interface. Might actually be a better way now that I think about it. If you have no idea what polymorphism is or if you never created an interface before, I would recommend reading up on it. I wont cover that in this answer.
Here is also another answer this is way better....
https://stackoverflow.com/a/13706974/8200290
my recyclerview contains image buttons which are star buttons.
So when the user clicks on the imagebutton it must turn yellow.
When user clicks again on this image button, it must turn gray.
I save the position and the status of the buttons in a hashmap. The status can be -1 or 1.When it is 1, the buttons turns yellow when it is -1 the button turns grey.
The first thing i do is to set for every position in the onBindViewHolder method like a status for every position in a hashMap which is -1, what means that the button is not selected and grey.So the position is the key and the status (-1 or 1) is the value in the hashMap.
public void onBindViewHolder(final MyViewHolder holder, final int position){
if(!hashMapStarButtons.containsKey(position)){
hashMapStarButtons.put(position), -1);
}
So when the image button is pressed, in the
onBindViewHolder(final MyViewHolder holder, final int position)
method i take the position and i check the status and change it
holder.starButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int currentStat = hashMapStarButtons.get(position);
currentStat = currentStat * (-1);
if(currentStat==1){
holder.starButton.setImageDrawable(ContextCompat.getDrawable(view.getContext(),android.R.drawable.btn_star_big_on));
}else{
holder.starButton.setImageDrawable(ContextCompat.getDrawable(view.getContext(),android.R.drawable.btn_star_big_off));
}
The problem here is that when i press a button which is on position 2, and the button must turn yellow because the status turns to 1, the recyclerView turns the buttons on position 12, 22, 32 into yellow too.
When i press the button on position 13 the color of the buttons on position 3, 23, 33 changes too.
Its realy weird.
When i check all the values in the HAshMap only the status for the button which has been pressed has changed but not for others.
Here is my Holder class
class MyViewHolder extends RecyclerView.ViewHolder {
View view;
// final
private ImageButton starButton;
private TextView movie;
public MyViewHolder(View viewItem){
super(viewItem);
starButton = (ImageButton)viewItem.findViewById(R.id.starButton);
movie = (TextView)viewItem.findViewById(R.id.movie);
}
public void setMovie(String movie){
movie.setText(movie);
}
}
This is the adapter class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
private List<String> list;
private HashMap<Integer, Integer> hashMapStarButtons;
public MyAdapter(List<Movie> list){
this.list = list;
hashMapStarButtons = new HashMap<Integer, Integer>();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
// Hole das Layout für die Row
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_row, parent, false));
}
// onBindViewHolder is called for every single item in the RecyclerView
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position){
Movie movie = list.get(position);
holder.setMovie(movie.getMovie());
if(!hashMapStarButtons.containsKey(position)){
hashMapStarButtons.put(position, -1);
}
holder.starButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int currentStat = hashMapStarButtons.get(position);
currentStat = currentStat * (-1);
if(currentStat==1){
holder.starButton.setImageDrawable(ContextCompat.getDrawable(view.getContext(),android.R.drawable.btn_star_big_on));
}else{
holder.starButton.setImageDrawable(ContextCompat.getDrawable(view.getContext(),android.R.drawable.btn_star_big_off));
}
}
});
}
}
here is my activity from where iam loading the data from firebase
public class MyActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference mStatusDB;
// everything for RecyclerView
private RecyclerView recyclerView;
private List<String> list;
private MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mymovies);
mStatusDB = FirebaseDatabase.getInstance().getReference().child("movies");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView = (RecyclerView)findViewById(R.id.movRecylerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
list = new ArrayList<>();
getList();
adapter = new MyAdapter(list);
recyclerView.setAdapter(adapter);
}
private void getList(){
mStatusDB.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Movie movie = new Movie();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
String key = snapshot.getKey();
String mov = snapshot.getValue().toString();
movie.setMovie(value);
}
list.add(movie);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Here you can see the problem only with ten rows:
Please help me where the problem is?
it is not in the hashmap in the statuses.
In the Picture the status for the row 10 would be -1 what means that the button should be gray.
The problem is that you don't check inside the OnBindViewHolder(final MyViewHolder holder, final int position) which is the state of the item at the position position. Looking at the code, you are checking it only inside the OnClickListener().
What is happening in you code is that the view of item 1 is recycled and used to put item 10, but the star in the view was colored in yellow and in your OnBindViewHolder you are not resetting its color to white.
This is my suggestion:
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position){
Movie movie = list.get(position);
holder.setMovie(movie.getMovie());
if(!hashMapStarButtons.containsKey(position)){
hashMapStarButtons.put(position, -1);
}
if(hashMapStarButtons.get(position)==-1){
holder.starButton.setImageDrawable(ContextCompat.getDrawable(view.getContext(),android.R.drawable.btn_star_big_off));
} else {
holder.starButton.setImageDrawable(ContextCompat.getDrawable(view.getContext(),android.R.drawable.btn_star_big_on));
}
...
}
Recylerview recycles or Binds the same view after every 9 items. So if the 1st item is changed it will reflect or reuse the same view after 9th item.
So work around is to make use of setItemViewCacheSize() on recylerview
public void setItemViewCacheSize(int size)
Set the number of offscreen views to retain before adding them to the potentially shared recycled view pool.
The offscreen view cache stays aware of changes in the attached adapter, allowing a LayoutManager to reuse those views unmodified without needing to return to the adapter to rebind them.
Make changes here
list = new ArrayList<>();
getList();
adapter = new MyAdapter(list);
recyclerView.setItemViewCacheSize(list.size());
recyclerView.setAdapter(adapter);
By doing this it will not recycle the same view. This may look simple but it does the work. Give a try.
file with working code to test my issue, you have to add 2 items, then delete any of those and then add a new one to see how the deleted gets on top of the newly addded
https://www.dropbox.com/s/ojuyz5g5f3kaz0h/Test.zip?dl=0
I have a problem when deleting an item from the recyclerview, when ever I delete an item, IF I add a new item, the deleted item will appear in top of the newly added item, how could I get a fresh view or avod this from happening as is a big issue.
this is how i add items from my main activity
if (!resta || (diff > (3*60*1000)))
{
Ri.add(dataroot);
Integer position = adapter.getItemCount() + 1;
adapter.notifyItemInserted(position);
}
here my Adapter
public class ComandaAdapter extends RecyclerView.Adapter<ComandaAdapter.ComandaAdapterViewHolder>{
private Context mContext;
private ArrayList<Integer> lista_entradas = new ArrayList<>();
private ArrayList<Integer> lista_fondos = new ArrayList<>();
private ArrayList<Integer> lista_postres= new ArrayList<>();
private Boolean primeritem;
private ArrayList<DataRoot> Rir;
private TextView txt_comandas;
private TextView txt_entracola;
private TextView txt_fondocola;
private TextView txt_postrecola;
public ComandaAdapter(Context context, TextView tx_entracola, TextView tx_fondocola, TextView tx_postrecola, TextView tx_comandas, ArrayList<DataRoot> Rir)
{
this.mContext = context;
this.txt_comandas = tx_comandas;
this.txt_entracola = tx_entracola;
this.txt_fondocola = tx_fondocola;
this.txt_postrecola = tx_postrecola;
this.Rir= Rir;
}
#Override
public ComandaAdapter.ComandaAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new ComandaAdapter.ComandaAdapterViewHolder(LayoutInflater.from(mContext).inflate(R.layout.row,parent,false));
}
#Override
public void onBindViewHolder(final ComandaAdapter.ComandaAdapterViewHolder holder, final int position)
{
DataRoot Rdata = Rir.get(position);
holder.setdata(Rdata);
}
public void delete(int position)
{
Rir.remove(position);
notifyItemRemoved(position);
}
public class ComandaAdapterViewHolder extends RecyclerView.ViewHolder
{
Button btn_cerrar;
public ComandaAdapterViewHolder(View itemView)
{
super(itemView);
btn_cerrar = (Button) itemView.findViewById(R.id.btn_cerrar);
void setData(final DataRoot Rdata)
{
btn_cerrar.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
btn_cerrar.setEnabled(false);
btn_cerrar.setBackgroundTintList(mContext.getColorStateList(R.color.cboff));
updateRetrofitEstadoorden(Rdata.get_id());
updateRetrofitNrocomanda(Rdata.get_id(), txt_comanda.getText().toString());
delete(getAdapterPosition());
}
});
Rdata.gerOrder();
creaboton():
and here my recyler
private void setAdapter()
{
adapter = new ComandaAdapter(this, txt_entracola, txt_fondocola, txt_postrecola, txt_comandas, Ri);
recyclerView.getRecycledViewPool().setMaxRecycledViews(-1, Ri.size());//va en 0 supuestamente -1 es default
recyclerView.setItemViewCacheSize(Ri.size()); //ver si hay que cambiar con cada item
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
Thanks in advance for any help.
Images to show the problem
You are using the Recyclerview in a very non standard way. The issue you are seeing is because the views are being recycled (as they should be in a Recyclerview) but you are not clearing out the items from the previous view.
The problem in in this method:
public void setData(String value) {
container.removeAllViews(); // Remove all previously added views
textview.setText(value);
Random r = new Random();
int i1 = r.nextInt(5 - 1) + 1;
for (int i = 0; i < i1; i++) {
be = new Button(mContext);
be.setText("Boton " + i);
be.setLayoutParams(new LinearLayout.LayoutParams(240, LinearLayout.LayoutParams.WRAP_CONTENT));
container.addView(be);
}
}
By calling container.addView(be), you are manually adding extra views to the views that the Recyclerview creates. When you remove these views, they are cached and reused the next time you press "Add". The problem is that the cached view still contains all of the manually added views so you are then adding more views under the existing ones.
As you can see in the code above, i added container.removeAllViews(); which removes the views that were added previously ensuring that "Container" is empty before you start adding your extra views to it.
Also, unless you have a very specific reason for doing so, I would removes these lines as I believe you are hurting performance by having them:
list.getRecycledViewPool().setMaxRecycledViews(-1, index);
list.setItemViewCacheSize(index);