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
Related
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
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to populate a ListView using an ArrayAdapter that I am filling with input from an EditText. My program seems to compile fine but during app start up it immediately crashes. I suspect that it has something to do with me trying to set-up my list view. I am not sure what I am initializing wrong such that my app instantly crashes. Any and all tips would be greatly appreciated. Thanks in advance!
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
ListView listView = (ListView) findViewById(R.id.dispScores);
listView.setAdapter(adapter);
My Adapter Class:
private class ScoreAdapter extends ArrayAdapter<scoreScreen> {
private ScoreAdapter(Context context, ArrayList<scoreScreen> scores) {
super(context, 0, scores);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
scoreScreen score1 = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_scores, parent, false);
}
TextView holeNum = (TextView) convertView.findViewById(R.id.holeNum);
holeNum.setText(score1.hole);
return convertView;
}
}
My ListView inside of my onCreate method.
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
I am assuming my problem is not inside my EditText inputs since they are inside of an OnClickListener method, but just incase I have attached it below.
public View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
//savedScores.add(input1.getText().toString());
scoreScreen addScore = new scoreScreen("Score is" + num1);
adapter.add(addScore);
j++;
input1.setText(""); //Clear input text box
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
//CURRENTLY ONLY DISPLAYS THE LAST NUNMBER IN THE TEXTEDIT, NEED TO SET UP LISTVIEW!!!!!!
for (int i=0; i < j; i++){
// output1.setText(savedScores.get(i));
} break;
}
}
};
onCreate method added as requested:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Button scoresAct = (Button) findViewById(R.id.allScores); //THIS IS TO GO TO ALL SCORES ACTIVITY
scoresAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent scoreScreen = new Intent(MainActivity.this, AllScoresAct.class);
startActivity(scoreScreen);
}
});*/
Button sumScores = (Button) findViewById(R.id.buttTotal);
Button saveScores = (Button) findViewById(R.id.allScores);
Button changeScores = (Button) findViewById(R.id.editScore);
sumScores.setOnClickListener(onClickListener);
saveScores.setOnClickListener(onClickListener);
changeScores.setOnClickListener(onClickListener);
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
}
After moving my adapter and ArrayList into my onCreate, I get a new error. I did some research on null pointers, but I have already initialized both of these. Below is my logcat, any ideas? Thanks
Make sure super.onCreate(savedInstanceState) is the first thing you are calling in your onCreate() and also not trying to access any view from the layout xml before setContentView().
EDIT:
Initialize the adapter in onCreate() method instead of doing it globally.
onCreate() {
.......
this.adapter = new ScoreAdapter(this, savedScores);
}
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
You can declare those globally, but for the Adapter, the this parameter must be used within/after onCreate, as the error says
System services not available to Activities before onCreate()
For example
private ArrayList<ScoreScreen> savedScores = new ArrayList<>();
private ScoreAdapter adapter;
#Override
protected void onCreate(Bundle b) {
...
adapter = new ScoreAdapter(this, savedScores);
}
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);
I saw all the questions which is similar to my question ( in this , this , this and this link )
I had myAdapter.notifyDataSetChanged() in my Activity but it doesn't work
I have 3 classes,
DBHelper - For storing and getting Database contents ( NO ISSUES HERE )
SimpleRecyclerAdapter - Adapter for RecyclerList
ThirdActivity
What i did in ThirdActivity :
I have TextBox to get data and store it in Database and a Button. In
the Onclicklistener of Button, i specified code to
get text from textbox
add it into table using DBHelper
retrive data as ArrayList from DBHelper
myAdapter.notifyDataSetChanged()
When i click the Button, I got Data in LogCat which i specified inside OnclickListener but it is not reflected to the listview.
Here is my code,
ThirdActivity:
public class ThirdActivity extends AppCompatActivity{
private DrawerLayout mDrawerLayout;
DbHelper dbHelper;
EditText et;
Button addButton;
RecyclerView rv;
ArrayList<String> myNotesList;
SimpleRecycler3Adapter adapter3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
myNotesList = new ArrayList<>();
et=(EditText) findViewById(R.id.et);
addButton=(Button)findViewById(R.id.addButton);
rv = (RecyclerView) findViewById(R.id.dbListrv);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext());
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
adapter3 = new SimpleRecycler3Adapter(myNotesList);
rv.setAdapter(adapter3);
dbHelper = new DbHelper(this, null, null, 1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("DB", "Constructor");
String note=et.getText().toString();
dbHelper.addNote(note);
printData();
}
});
}
public void printData(){
Log.d("DB","Constructor");
myNotesList=dbHelper.databasetostring();
Log.d("DB","Data came"+myNotesList.get(myNotesList.size()-1));
// adapter3 = new SimpleRecycler3Adapter(myNotesList);
// rv.setAdapter(adapter3);
adapter3.notifyDataSetChanged();
}
}
SimpleRecyclerViewAdapter :
public class SimpleRecycler3Adapter extends RecyclerView.Adapter<SimpleRecycler3Adapter.NotesHolder> {
private ArrayList<String> myNotesList=new ArrayList<String>();
String TAG="ThirdAdapter kbt";
RecyclerView rv;
public SimpleRecycler3Adapter(ArrayList<String> myList) {
Log.d(TAG,"Constructor");
Log.d(TAG,"Not null");
int i = 0;
while (i < myNotesList.size()) {
myNotesList.add(myList.get(i).toString());
}
Log.d(TAG,"finish");
}
#Override
public NotesHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Log.d(TAG,"On create started");
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerlist3_item, viewGroup, false);
Log.d(TAG,"ADAP STAR ONCR second switch 2nd line");
NotesHolder viewHolder2 = new NotesHolder(view2);
Log.d(TAG,"ADAP STAR ONCR second switch 3nd line");
return viewHolder2;
}
#Override
public void onBindViewHolder(NotesHolder notesHolder, int i) {
Log.d(TAG, "ONBIND SECOND i value is " + i);
// notesHolder.thumbnail.setImageResource(R.drawable.placeholder);
notesHolder.dblistitem.setText(myNotesList.get(i));
Log.d(TAG,"ONBIND second title issssss");
}
#Override
public int getItemCount() {
return myNotesList.size();
}
class NotesHolder extends RecyclerView.ViewHolder {
protected ImageView thumbnail;
protected TextView dblistitem;
public NotesHolder(View itemView) {
super(itemView);
Log.d(TAG, "JSON Inside HOLDER");
rv=(RecyclerView)itemView.findViewById(R.id.dbListrv);
// thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
dblistitem = (TextView) itemView.findViewById(R.id.dblistitem);
}
}
}
You're not updating the myNotesList that is in adapter class but in activity class. But the adapter uses it's local myNotesList.
So on button click, update myNotesList of adapter with latest data available and notify the adapter.
EDIT
Pass the latest data to adapter. Have this method in adapter class and call this before notifyDataSetChanged();
public void updateNotes(ArrayList<String> notesList) {
myNotesList = notesList;
}
1.you are intializing your dbhelper after setting adapter to listview so it couldn't contain any data initially
2.for updating recycler view data list do as follows
myNotesList.clear();
myNotesList.addAll(dbHelper.databasetostring());
adapter3.notifyDataSetChanged();
You have a problem in your SimpleRecyclerViewAdapter, just change this:
while (i < myNotesList.size()) {
myNotesList.add(myList.get(i).toString());
}
For this:
myNotesList = myList;
And in your activity's printData() change:
myNotesList=dbHelper.databasetostring();
for this:
myNotesList.clear();
myNotesList.addAll(dbHelper.databasetostring());
adapter3.notifyDataSetChanged();
Explanation:
First you initialize myNotesList variable:
myNotesList = new ArrayList<>();
Then you initialize adapter3
adapter3 = new SimpleRecycler3Adapter(myNotesList);
But your adapter is not saving the reference, instead you're copying its data into another variable:
while (i < myNotesList.size()) {
myNotesList.add(myList.get(i).toString());
}
Doing that, if you change myNotesList variable in your activity will not modify your adapter's dataset.
In your method printData() you change myNotesList variable. Which will not touch your adapter or its data
public void printData(){
Log.d("DB","Constructor");
myNotesList=dbHelper.databasetostring();
Log.d("DB","Data came"+myNotesList.get(myNotesList.size()-1));
// adapter3 = new SimpleRecycler3Adapter(myNotesList);
// rv.setAdapter(adapter3);
adapter3.notifyDataSetChanged();
}
You can't change myNotesList by changing myList.
public SimpleRecycler3Adapter(ArrayList<String> myList) {
Log.d(TAG,"Constructor");
Log.d(TAG,"Not null");
// int i = 0;
// while (i < myNotesList.size()) {
// myNotesList.add(myList.get(i).toString());
// }
this.myNotesList = myList;
Log.d(TAG,"finish");
}
Not a good idea to call notifyDataSetChanged() when you know exactly what changed in your data collection.
See this implementation here.
They have even documented to use notifyDataSetChanged() as a last resort in this doc.
You get nice animations for free if you use methods like notifyItemInserted() and the rest.
Also do not go on replacing the collection object entirely, see the implmentation link that has been attached.
I am new to Android. I am Using "com.devsmart.android.ui.HorizontalListView" to show my items(playing cards). In the List I am getting 8 cards in the first attempt. What I want if I again call the method the there must be 7 cards so on means 1 cards must be remove from the list at each time till the list gets empty. But I am not able not do this removing of item from the list. I am posting my code here. Help will be appreciated.
MainActivity.java
ArrayList<HashMap<String, String>> aList9;
Button btn_aditional_card;
HorizontalListView list1;
int[] cards3 = new int[]{
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1
};
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_aditional_card = (Button) findViewById(R.id.btn_aditional_card);
list1 = (HorizontalListView) findViewById(R.id.listview1);
btn_aditional_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add8();
}
});
}
public void add8() {
final android.view.animation.Animation animScale = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
list1.startAnimation(animScale);
aList9 = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 8; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("card", Integer.toString(cards3[i]));
aList9.add(hm);
}
String[] from = {"card"};
int[] to = {R.id.ImageView};
final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList9, R.layout.activity_animation__adapter, from, to);
list1.setAdapter(adapter);
adapter.notifyDataSetChanged();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
});
}
Here removing of item from the list must be done on list1.setOnItemClickListener but I don't have any idea how.
In your list1.setOnItemClickListener, do this:
if (aList9.size() > 0) {
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
When removing item from data list, you have to notify your adapter to update view.
You can remove the last item from the list like;
if (aList9.size() > 0) {
aList9.remove(aList9.size() - 1);
}
Another solution,
Take Length of your integer array and traverse the loop inside your add8 method according to this length and at the end of the method decrement the length by one, like;
int length = cards3.length;
Inside your add8 method;
for (int i = 0; i < length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("card", Integer.toString(cards3[i]));
aList9.add(hm);
}
After for loop decrement the length like;
length--;
Hope you'll get the solution.
In your main activity the code should look like.I am using arraylist instead you can use hashmap.This code is only to show you way what you need to do. follow this code in your project you will get solution this is tested in my site and working fine you need to change somewhere according to your code.In button click i am only removing last item from arraylist and notifying that dataset changed.hope it will help you.
ArrayList<String> arrlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrlist.add("B");
arrlist.add("C");
arrlist.add("D");
arrlist.add("E");
arrlist.add("F");
arrlist.add("G");
ListView lv = (ListView) findViewById(R.id.listview);
Button btnShowList = (Button) findViewById(R.id.btnShowList);
final ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arrlist);
//Listview adapter
lv.setAdapter(adapter);
btnShowList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (arrlist.size() > 0) {
arrlist.remove(arrlist.size() - 1);
adapter.notifyDataSetChanged();
}
}
});
}
Read the comments
class MainActivity extends AppCompatActivity {
//make your Adapter global
private SimpleAdapter adapter;
ArrayList<HashMap<String, String>> aList9;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add8();
btn_aditional_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// on button click you can add a view to the listview if you want
// if you don't want this just comment out the following line
// i still don't understand what you want to do with this button
alist9.add(...);
// if you add stuff in the array list then notify the adapter
// it will update the view
adapter.notifyDataSetChanged();
}
});
}
public void add8() {
// initialize your ArrayList and listview
//populate them
for(int i = 0; i < 8; i++) {
// do your stuff.
// populate the list
}
// initialize your adapter as before
adapter = new SimpleAdapter(....);
listview.setadapter(adapter);
adapter.notifyDataSetChanged();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// delete the items like this
// check if size is greater than 0 and then remove
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
});
}
}