notifyDataSetChanged(); not refreshing ListView? - java

I'm working on a notes app and I'm running into trouble deleting notes: after the note is deleted, it still shows in the listview.
I'm trying to use notifyDataSetChanged(), but it doesn't seem to be working for me.
MainActivity:
public class MainActivity extends AppCompatActivity {
private ListView mListViewNotes;
ArrayAdapter<Note> listAdapter;
ArrayList<Note> list_items = new ArrayList<>();
int count = 0;
String list_item;
Object mActionMode;
Toolbar app_bar;
ArrayList<Note> notes;
private String mNoteFileName;
private Note mLoadedNote;
Note loadedNote;
ImageView picTest;
NoteAdapter na;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
app_bar = (Toolbar) findViewById(R.id.app_bar);
TextView title_1 = (TextView) findViewById(R.id.title1);
TextView title_2 = (TextView) findViewById(R.id.title2);
TextView title_m = (TextView) findViewById(R.id.title_m);
Typeface music_font = Typeface.createFromAsset(getAssets(), "fonts/melodymakernotesonly.ttf");
Typeface notes_font = Typeface.createFromAsset(getAssets(), "fonts/the unseen.ttf");
setSupportActionBar(app_bar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setElevation(12);
title_1.setTypeface(music_font);
title_2.setTypeface(notes_font);
title_m.setTypeface(music_font);
listAdapter = new ArrayAdapter<Note>(this, R.layout.item_note, R.id.item_note, list_items);
mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
if (mNoteFileName != null && !mNoteFileName.isEmpty()) {
loadedNote = Utilities.getNoteByName(this, mNoteFileName);
}
mListViewNotes = (ListView) findViewById(R.id.listview_notes);
mListViewNotes.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListViewNotes.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (list_items.contains(notes.get(position))) {
count = count-1;
list_items.remove(notes.get(position));
mode.setTitle(count + " Notes Selected");
} else {
count = count+1;
list_items.add(notes.get(position));
mode.setTitle(count + " Notes Selected");
}
if (count == 0) {
mode.setTitle("No Notes Selected");
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
app_bar.setVisibility(View.GONE);
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
deleteNote();
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
count = 0;
app_bar.setVisibility(View.VISIBLE);
list_items.clear();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_note:
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_settings:
Log.d("list:", "testing");
}
return true;
}
#Override
protected void onResume() {
super.onResume();
mListViewNotes.setAdapter(null);
notes = Utilities.getAllSavedNotes(this);
if (notes == null || notes.size() == 0) {
Toast.makeText(this, "No Notes!", Toast.LENGTH_LONG).show();
} else {
na = new NoteAdapter(this, R.layout.item_note, notes);
mListViewNotes.setAdapter(na);
mListViewNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String filename = ((Note) mListViewNotes.getItemAtPosition(position)).getDateTime() + Utilities.FileExtention;
Intent view_note = new Intent(getApplicationContext(), NoteActivity.class);
view_note.putExtra("NOTE_FILE", filename);
startActivity(view_note);
}
});
}
}
private void deleteNote() {
if(list_items.contains(null)) {
finish();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle("Delete")
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (Note loadedNote : list_items) {
Utilities.deleteNote(getApplicationContext(), loadedNote.getDateTime() + Utilities.FileExtention);
}
na.notifyDataSetChanged();
listAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.setCancelable(false);
dialog.show();
}
}
NoteAdapter
public class NoteAdapter extends ArrayAdapter<Note> {
public NoteAdapter(Context context, int resource, ArrayList<Note> notes) {
super(context, resource, notes);
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
//return super.getView(position, convertView, parent);
if(convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_note, null);
}
Note note = getItem(position);
if(note != null) {
TextView title = (TextView) convertView.findViewById(R.id.list_note_title);
TextView content = (TextView) convertView.findViewById(R.id.list_note_content);
TextView date = (TextView) convertView.findViewById(R.id.list_note_date);
Typeface scribble_card = Typeface.createFromAsset(getContext().getAssets(), "fonts/the unseen.ttf");
title.setTypeface(scribble_card);
content.setTypeface(scribble_card);
title.setText(note.getTitle());
date.setText(note.getDateTimeFormatted(getContext()));
if(note.getContent().length() > 25) {
content.setText(note.getContent().substring(0,25) + "...");
} else {
content.setText(note.getContent());
}
if(note.getContent().length() <= 0) {
content.setText("(Empty Note..)");
} else {
content.setText(note.getContent());
}
if (note.getTitle().length() <= 0) {
title.setText("(Untitled)");
} else {
title.setText(note.getTitle());
}
}
return convertView;
}

You are setting adapter with a list:
na = new NoteAdapter(this, R.layout.item_note, notes);
mListViewNotes.setAdapter(na);
na.notifyDataSetChanged(); will only work if your notes list is changed.
And I don't see that you remove/add/modify on notes list.
If you are deleting item from list you need to remove it from notes list, too:
notes.remove(position_to_remove);
na.notifyDataSetChanged();

Related

How Do We Handle Click From Multiple Item View in RecyclerView? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have problem:
There is three part of data that displayed in one RecyclerView. As you know, all of data are displayed in favourite page, which mean, they are not constant. If user press the favourite button, the data will be displayed in favourite page, otherwise it's won't. So, all of data are change every time, it depends on user activity. Because of this, I get trouble in getting item's ID when user click certain item.
I've already tried to solve this problem, but still stuck many days...
ShowFavouriteList.java
public class ShowFavouriteList extends AppCompatActivity implements AdapterFavList.FavListener {
private RecyclerView recyclerView;
private TextView noFavtsTV;
AppPreferences appPreferences;
private SearchView searchView;
private AdapterFavList yAdapterFavlist;
private AdapterFavList mAdapterFavlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_favourite_list);
SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
//toolbar logo and desc
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
setSupportActionBar(topToolBar); //munculkan menu ke toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button
recyclerView = findViewById(R.id.recycler_view);
noFavtsTV = findViewById(R.id.no_favt_text);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences sPTuru = getApplicationContext().getSharedPreferences("MyTuru", 0);
SharedPreferences sPHome = getApplicationContext().getSharedPreferences("MyHome", 0);
PreferenceMenejer preferenceMenejer = new PreferenceMenejer(sharedPreferences, sPTuru, sPHome);
appPreferences = new AppPreferences(preferenceMenejer);
fetchData();
} // Oncreate
private void fetchData() {
List<Story> storyList = appPreferences.getFavouriteCardList();
List<YukulModel> yukulList = appPreferences.getFavouriteYukul();
List<HomeModel> modelList = appPreferences.getFavouriteHome();
if(storyList != null && storyList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(new AdapterFavList(this, storyList, yukulList, modelList, this, appPreferences));
}
if(yukulList != null && yukulList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
yAdapterFavlist = new AdapterFavList(this, storyList, yukulList, modelList, this, appPreferences);
recyclerView.setAdapter(yAdapterFavlist);
}
if(modelList != null && modelList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mAdapterFavlist = new AdapterFavList(this, storyList, yukulList, modelList, this, appPreferences);
recyclerView.setAdapter(mAdapterFavlist);
}
}
#Override
public void onItemKlik(int pos) {
// Tidur List
List<HomeModel> modelList = appPreferences.getFavouriteHome();
HomeModel click = modelList.get(pos);
Toast.makeText(getApplicationContext(), "Selected: " + click.getName(), Toast.LENGTH_LONG).show();
int id = Integer.parseInt(click.getIdStory());
if(modelList != null && modelList.size() > 0) {
if (id == 0) {
startActivity(new Intent(this, DoaPagi.class));
} else if (id == 1) {
startActivity(new Intent(this, DoaSore.class));
} else if (id == 2) {
startActivity(new Intent(this, DoaWc.class));
} else if (id == 3) {
startActivity(new Intent(this, DoaMasjid.class));
} else if (id == 4) {
startActivity(new Intent(this, DzikirShalat.class));
} else if (id == 5) {
startActivity(new Intent(this, ChildYukul.class));
} else if (id == 6) {
startActivity(new Intent(this, DoaPakaian.class));
} else if (id == 7) {
startActivity(new Intent(this, ChildTidur.class));
}
}
}
private void showNoFavtText(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_fav, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable_tidur configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search_fav).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapterFavlist.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapterFavlist.getFilter().filter(query);
return false;
}
});
return true;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.search_fav) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
AdapterFavList.java
public class AdapterFavList extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
public static final String ACTION_LIKE_IMAGE_CLICKED = "action_like_image_button";
final int VIEW_TYPE_TIDUR = 0;
final int VIEW_TYPE_YUKUL = 1;
final int VIEW_TYPE_HOME = 2;
private Context context;
private AppPreferences appPreferences;
private List<Story> storyList;
private List<YukulModel> yukulList;
private List<HomeModel> homeList;
private List<HomeModel> homeListFiltered;
private List<Object> collection = new ArrayList<Object>();
private FavListener listener;
private int changedItemPosition;
private int posisiItemYukul;
private int posisiItemHome;
private boolean isLiked;
public AdapterFavList(Context context, List<Story> storyList, List<YukulModel> yukulList, List<HomeModel> homeList, FavListener listener, AppPreferences appPreferences) {
this.context = context;
this.storyList = storyList;
this.yukulList = yukulList;
this.homeListFiltered = homeList;
this.listener = listener;
this.appPreferences = appPreferences;
addData();
}
public interface FavListener {
void onItemKlik(int pos);
// void onTidurKlik(int pos);
// void onYukulKlik(int pos);
}
public void addData() {
storyList = appPreferences.getFavouriteCardList();
yukulList = appPreferences.getFavouriteYukul();
homeList = appPreferences.getFavouriteHome();
if(storyList != null && storyList.size() > 0) {
collection.addAll(storyList);
}
if(yukulList != null && yukulList.size() > 0) {
collection.addAll(yukulList);
}
if(homeList != null && homeList.size() > 0) {
collection.addAll(homeListFiltered);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_TIDUR) {
return new tidurViewHolder(LayoutInflater.from(context).inflate(R.layout.item_story_favourite_list, parent, false));
}
if(viewType == VIEW_TYPE_YUKUL) {
return new yukulViewHolder(LayoutInflater.from(context).inflate(R.layout.item_favourite_yukul, parent, false));
}
if(viewType == VIEW_TYPE_HOME) {
return new homeViewHolder(LayoutInflater.from(context).inflate(R.layout.item_fav_home, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Object item = collection.get(position);
if(holder instanceof tidurViewHolder){
((tidurViewHolder) holder).setViewData((Story) item, holder.getAdapterPosition());
}
if(holder instanceof yukulViewHolder){
((yukulViewHolder) holder).viewDataYukul((YukulModel) item, holder.getAdapterPosition());
}
if(holder instanceof homeViewHolder){
((homeViewHolder) holder).viewDataHome((HomeModel) item, holder.getAdapterPosition());
}
}
#Override
public int getItemCount() {
return collection.size();
}
#Override
public int getItemViewType(int position){
Object item = collection.get(position);
if(item instanceof Story) {
return VIEW_TYPE_TIDUR;
}
if(item instanceof YukulModel){
return VIEW_TYPE_YUKUL;
}
if(item instanceof HomeModel){
return VIEW_TYPE_HOME;
}
return -1;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
List<HomeModel> homeList = appPreferences.getFavouriteHome();
if (charString.isEmpty()) {
homeListFiltered = homeList;
}
else {
List<HomeModel> filteredList = new ArrayList<>();
for (HomeModel row : homeList) {
if ( row.getName().toLowerCase().contains(charString.toLowerCase()) ) {
filteredList.add(row);
}
}
homeListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = homeListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
homeListFiltered = (ArrayList<HomeModel>) filterResults.values;
notifyDataSetChanged();
}
};
} //Filter
public void tidurPutHeart(boolean isChecked, Story tidurstory) {
SharedPreferences tidursharedPreferences = context.getSharedPreferences("Turu", Activity.MODE_PRIVATE);
SharedPreferences.Editor tidureditor = tidursharedPreferences.edit();
tidureditor.putBoolean(tidurstory.getIdStory(), isChecked);
tidureditor.commit();
}
public void yukulPutHeart(boolean isChecked, YukulModel yukulstory) {
SharedPreferences yukulsharedPreferences = context.getSharedPreferences("Yukul", Activity.MODE_PRIVATE);
SharedPreferences.Editor yukuleditor = yukulsharedPreferences.edit();
yukuleditor.putBoolean(yukulstory.getIdStory(), isChecked);
yukuleditor.commit();
}
public void homePutHeart(boolean isChecked, HomeModel homestory) {
SharedPreferences homesharedPreferences = context.getSharedPreferences("Home", Activity.MODE_PRIVATE);
SharedPreferences.Editor homeeditor = homesharedPreferences.edit();
homeeditor.putBoolean(homestory.getIdStory(), isChecked);
homeeditor.commit();
}
//ViewHolder
public class tidurViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public tidurViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
}
});
} // itemView
public void setViewData(final Story story, final int adapterPosition) {
textView.setText(story.getName());
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
tidurPutHeart(isChecked, story);
appPreferences.saveFavouriteCard(story);
}
else {
isLiked = false;
tidurPutHeart(isChecked, story);
appPreferences.deleteCard(story.getIdStory());
// updateLikes();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //setviewdata
public void updateLikes() {
if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //tidurViewholder
//homeViewHolder
public class homeViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public homeViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemKlik(position);
}
}
}
});
} // itemView
public void viewDataHome(final HomeModel story, final int adapterPosition) {
textView.setText(story.getName());
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
homePutHeart(isChecked, story);
appPreferences.saveFavouriteHome(story);
}
else {
isLiked = false;
homePutHeart(isChecked, story);
appPreferences.deleteCardHome(story.getIdStory());
// updateLikesHome();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //setviewdata
public void updateLikesHome() {
if (!isLiked && homeList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
homeList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //homeviewholder
public class yukulViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public yukulViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
}
});
} //itemview
public void viewDataYukul(final YukulModel yukulId, final int adapterPosition) {
textView.setText(yukulId.getName());
if (yukulId.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
posisiItemYukul = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
yukulPutHeart(isChecked, yukulId);
appPreferences.saveFavouriteYukul(yukulId);
}
else {
isLiked = false;
yukulPutHeart(isChecked, yukulId);
appPreferences.deleteCardYukul(yukulId.getIdStory());
// updateLikeYukul();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //viewdatayukul
public void updateLikeYukul() {
if (!isLiked && yukulList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
yukulList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //yukulviewholder
} //HomeAdapter
try it adapter
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ClickItem clickItem;
Context context;
//your data model
ArrayList<ModelField> modelFields;
public RecyclerviewAdapter(Context context, ArrayList<ModelField> modelField, ClickItem clickItem) {
this.context = context;
this.modelFields = modelField;
this.clickItem = clickItem;
}
#Override
public int getItemViewType(int position) {
//get view type
return super.getItemViewType(position);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// get view create
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
// set bind view
if (holder instanceof viewHolder_1) {
((viewHolder_1) holder).bind(modelFields.get(position));
} else if (holder instanceof viewHolder_2) {
((viewHolder_2) holder).bind(modelFields.get(position));
} else if (holder instanceof viewHolder_3) {
((viewHolder_3) holder).bind(modelFields.get(position));
}
}
#Override
public int getItemCount() {
//arraylist size
return modelFields.size();
}
interface ClickItem {
void onClick(RecyclerView.ViewHolder viewHolder, ModelField modelField, int position);
}
public class viewHolder_1 extends RecyclerView.ViewHolder {
public viewHolder_1(#NonNull View itemView) {
super(itemView);
//casting views
}
public void bind(final ModelField item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickItem.onClick(viewHolder_1.this, item, getAdapterPosition());
}
});
}
}
public class viewHolder_2 extends RecyclerView.ViewHolder {
public viewHolder_2(#NonNull View itemView) {
super(itemView);
//casting views
}
public void bind(final ModelField item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickItem.onClick(viewHolder_2.this, item, getAdapterPosition());
}
});
}
}
public class viewHolder_3 extends RecyclerView.ViewHolder {
public viewHolder_3(#NonNull View itemView) {
super(itemView);
//casting views
}
public void bind(final ModelField item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickItem.onClick(viewHolder_3.this, item, getAdapterPosition());
}
});
}
}
}
and using
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(this, your data arraylist, new RecyclerviewAdapter.ClickItem() {
#Override
public void onClick(RecyclerView.ViewHolder viewHolder, ModelField modelField, int position) {
}
});
recyclerview.setAdapter(recyclerviewAdapter);

Searchview in custom ArrayAdapter

I have a custom 'ArrayAdapter' in a 'ListView', my problem is using a menu 'SearchView'. It's not working properly. I don´t know if the problem is searching or showing the results, because nothing appears. And, if possible, I wnat to show a custom list of results. Thanks!
Fragment with the adapter
ArrayList<Favoritos> favorites;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.list_item, container, false);
favorites = new ArrayList<Favoritos>();
favorites.add(new Favorites("Title", "addres", 5, false, 7, 22, 4.5f));
favorites.add(new Favorites("Title", "addres", 3.5 , true, 7, 22, 3.0f));
favorites.add(new Favorites("Title", "addres", 2, false, 7, 22, 4.0f));
favorites.add(new Favorites("Titleo", "addres", 4.5, true, 7, 22, 5.0f));
FavoritesAdapter adapter = new FavoritesAdapter(getActivity(), favorites);
ListView listView = (ListView) rootView.findViewById(R.id.list_item);
listView.setAdapter(adapter);
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String string) {
search(string);
return true;
}
//This is the search method
public void search(String s) {
if (s == null || s.trim().equals("")) {
cleanSearch(); //In this method I just "reset" the adapter when the user "give up"
return;
}
ArrayList<Favoritos> estacionamentosEncontrados = new ArrayList<Favoritos>(favoritos);
for (int i = estacionamentosEncontrados.size() - 1; i >= 0; i--) {
Favoritos estacionamento = estacionamentosEncontrados.get(i);
Favoritos nenhumResultado = new Favoritos("Nenhum resultado encontrado");
if (!estacionamento.mIndicacao.toUpperCase().contains(s.toUpperCase())) {
estacionamentosEncontrados.remove(estacionamento);
} else {
estacionamentosEncontrados.add(nenhumResultado);
}
}
adapter = new EncontradosAdapter(getActivity(), estacionamentosEncontrados);
ListView listView = (ListView) getActivity().findViewById(R.id.list_item);
listView.setAdapter(adapter);
}
Favorites.java
public String mIndicacao;
public String mEndereco;
private double mPreco;
public boolean mDisponibilidade;
private double mHoraAbre;
private double mHoraFecha;
private float mAvaliacao;
public Favoritos(){
}
public Favoritos(String indicacao, String endereco, double preco, boolean disponibilidade, double horaAbre, double horaFecha, float avaliacao){
mIndicacao = indicacao;
mEndereco = endereco;
mPreco = preco;
mDisponibilidade = disponibilidade;
mHoraAbre = horaAbre;
mHoraFecha = horaFecha;
mAvaliacao = avaliacao;
}
//Getters and Setters
And the custom Adapter
public class FavoritesAdapter extends ArrayAdapter<Favorites> {
public FavoritesAdapter(Context context, ArrayList<Favorites> favorites){
super(context, 0, favoritos);
}
public static class ItemViewHolder{
TextView indicadorTextView;
TextView enderecoTextView;
TextView precoTextView;
TextView horaAbreTextView;
TextView horaFechaTextView;
RatingBar notaEstacionamento;
ImageView disponivelImg;
TextView disponivelTextView;
ImageView esconderView;
public ItemViewHolder(View view){
indicadorTextView = (TextView) view.findViewById(R.id.indicador);
enderecoTextView = (TextView) view.findViewById(R.id.endereco);
precoTextView = (TextView) view.findViewById(R.id.precoValor);
horaAbreTextView = (TextView) view.findViewById(horaAbre);
horaFechaTextView = (TextView) view.findViewById(horaFecha);
notaEstacionamento = (RatingBar) view.findViewById(R.id.ratingBar);
disponivelImg = (ImageView) view.findViewById(R.id.img_disponibilidade);
disponivelTextView = (TextView) view.findViewById(R.id.disponivel);
esconderView = (ImageView) view.findViewById(R.id.esconder_view_btn);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.favorites_item, parent, false);
}
Favorites currentFavorito = getItem(position);
final ItemViewHolder holder;
if(listItemView.getTag() == null){
holder = new ItemViewHolder(listItemView);
listItemView.setTag(holder);
} else {
holder = (ItemViewHolder) listItemView.getTag();
}
if(currentFavorito.getDisponibilidade()){
holder.disponivelTextView.setText(currentFavorito.getIndicacao());
} else {
holder.disponivelTextView.setText(currentFavorito.getIndicacao());
}
holder.indicadorTextView.setText(currentFavorito.getIndicacao());
holder.enderecoTextView.setText(currentFavorito.getEndereco());
holder.precoTextView.setText(currentFavorito.getPreco());
holder.horaAbreTextView.setText(currentFavorito.getHoraAbre());
holder.horaFechaTextView.setText(currentFavorito.getHoraFecha());
holder.notaEstacionamento.setRating(currentFavorito.getAvaliacao());
if(currentFavorito.getDisponibilidade()){
holder.disponivelImg.setImageResource(R.drawable.ir_img);
holder.disponivelTextView.setText(R.string.aberto);
holder.disponivelTextView.setTextColor(getContext().getResources().getColor(R.color.verde));
} else {
holder.disponivelImg.setImageResource(R.drawable.fechado_img);
holder.disponivelTextView.setText(R.string.fechado);
holder.disponivelTextView.setTextColor(getContext().getResources().getColor(R.color.vermelho)); }
return listItemView;
}
}
Step : 1 Create option menu in fragment for searchview like
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
//menu.clear();
inflater.inflate(R.menu.ticket_fragment_search_menu, menu);
MenuItem actionSearch = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(actionSearch);
searchView.setMaxWidth(Integer.MAX_VALUE);
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setSingleLine(true);
searchEditText.setTextColor(getResources().getColor(R.color.black));
searchEditText.setHintTextColor(getResources().getColor(R.color.black));
searchView.setQueryHint(getResources().getString(R.string.txt_search_here));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//apply Filter
adapter.setFilter(newText)
return false;
}
});
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "search open");
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
Log.e(TAG, "search close");
return false;
}
});
}
Step 2 : create function for filter or search in adapter
public void setFilter(String str) {
aList = new ArrayList<>();
if (aListTemp.size() > 0) {
for (int i = 0; i < aListTemp.size(); i++) {
if (aListTemp.get(i).toLowerCase().contains(str.toLowerCase())
) {
aList.add(aListTemp.get(i));
}
}
}
notifyDataSetChanged();
}

How to resolve custom list view while scrolling checking condition not working properly

I want to display items in list view with four attributes: id, name, marks, and date. Its working fine but when I scroll the listview and select the 1st item, it also selects the 16th item and sometimes the app crashes. I searched a lot but can't understand what's the problem.
//Adapter class
public class Adapter extends ArrayAdapter<Item> {
private Activity activity;
int id;
ArrayList<Item> items;
public Adapter(Activity context, int resource, ArrayList<Item> objects) {
super(context, resource, objects);
this.activity=context;
this.id=resource;
this.items=objects;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(id, null);
}
Item item = items.get(position);
TextView tv_id = (TextView) convertView.findViewById(R.id.tv_id);
TextView tv_name = (TextView) convertView.findViewById(R.id.tv_name);
TextView tv_marks = (TextView) convertView.findViewById(R.id.tv_marks);
TextView tv_date = (TextView) convertView.findViewById(R.id.tv_date);
tv_id.setText(item.getId());
tv_name.setText(item.getName());
tv_marks.setText(item.getMarks());
tv_date.setText(item.getDat());
return convertView;
}
//item class-----------
public class Item {
private String id;
private String name;
private String surname;
private String marks;
private String dat;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
public String getDat() {
return dat;
}
public void setDat(String dat) {
this.dat = dat;
}
}
// List view Class
public class List_Viwer extends AppCompatActivity {
Context ctx = this;
ListView listView;
Adapter adapter;
CheckBox checkBox;
DatabaseHelper myDb = new DatabaseHelper(this);
ArrayList<Item> arrayList=new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list__viwer);
//checkBox.setVisibility(View.GONE);
Cursor cursor = myDb.getAllData();
if(cursor!= null) {
if (cursor.moveToFirst()){
do{
Item item = new Item();
item.setId(cursor.getString(0));
item.setName(cursor.getString(1));// gets id fromm database
item.setSurname(cursor.getString(2)); //gets title from database
item.setMarks(cursor.getString(3));
item.setDat(cursor.getString(4));// gets content / body from database
arrayList.add(item);
}while (cursor.moveToNext());
}
adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView temp_txt = (TextView) view.findViewById(R.id.tv_id);
String tempID = temp_txt.getText().toString();
// Toast.makeText(ctx, ID, Toast.LENGTH_LONG).show();
Intent i = new Intent(ctx, View_Person.class);
i.putExtra("ID", tempID);
ctx.startActivity(i);
}
});
//-----------------Long Clikced Listener Starts from here-----------------------------
listView.setAdapter(adapter);
listView.setChoiceMode(listView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
ArrayList<String> list_ids = new ArrayList<String>();
int count = 0;
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
String data = adapter.getItem(position).getId();
Toast.makeText(ctx, data, Toast.LENGTH_SHORT).show();
if (list_ids.contains(data)) {
for (int i = 0; i < list_ids.size(); i++) {
// String temp = list_ids.get(i);
if (data == list_ids.get(i)) {
count--;
mode.setTitle(count + " Items Selected");
list_ids.remove(i);
listView.getChildAt(position).setBackgroundResource(R.drawable.bg1);
}
}
}
else {
// listView.getChildAt(pos).setBackgroundColor(Color.YELLOW);
count++;
mode.setTitle(count + " Items Selected");
listView.getChildAt(position).setBackgroundResource(R.drawable.bg2);
list_ids.add(data);
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflator = mode.getMenuInflater();
inflator.inflate(R.menu.menu_delete, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.action_delete:
for (int i=0; i<list_ids.size(); i++)
{
String temp = list_ids.get(i);
myDb.deleteData(temp);
}
Toast.makeText(ctx, count+" Items Deleted.", Toast.LENGTH_SHORT).show();
mode.finish();
count = 0;
list_ids.clear();
arrayList.clear();
refreshdata(); //gets data from method and Sets to list View item
//listView.clearChoices();
//adapter.notifyDataSetChanged();
//break;
default:
return false;
//break;
}
//return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("checkBox", "false");
editor.apply();
count = 0;
list_ids.clear();
arrayList.clear();
refreshdata();
// listView.clearChoices();
listView.setBackgroundColor(Color.TRANSPARENT);
// listView.clearChoices();
// listView.setBackgroundColor(Color.TRANSPARENT);
}
}); //-----------Lon clik listener ends---------------------------------
} //-------------On Create bundel method ends------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// adapter.getFilter().filter(newText);
// getPlanets(newText);
arrayList.clear(); // MUST CLEAR THE PREVIOUS DATA FROM LIST
Cursor cursor = myDb.SearchData(newText);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setId(cursor.getString(0));
item.setName(cursor.getString(1));// gets id fromm database
item.setSurname(cursor.getString(2)); //gets title from database
item.setMarks(cursor.getString(3));
item.setDat(cursor.getString(4));// gets content / body from database
// item.setCheckBox();
arrayList.add(item);
} while (cursor.moveToNext());
}
listView.setAdapter(adapter);
}
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
public void refreshdata(){
final Cursor cursor = myDb.getAllData();
if(cursor!= null) {
if (cursor.moveToFirst()){
do{
Item item = new Item();
item.setId(cursor.getString(0));
item.setName(cursor.getString(1));// gets id fromm database
item.setSurname(cursor.getString(2)); //gets title from database
item.setMarks(cursor.getString(3));
item.setDat(cursor.getString(4));// gets content / body from database
arrayList.add(item);
}while (cursor.moveToNext());
}
adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
}
/// my log cat
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: FATAL EXCEPTION: main
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: java.lang.NullPointerException
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: at com.hexa.adnan.mysqllitedemo.List_Viwer$2.onItemCheckedStateChanged(List_Viwer.java:101)
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: at android.widget.AbsListView$MultiChoiceModeWrapper.onItemCheckedStateChanged(AbsListView.java:6077)

Delete Multiple Selected Items in ListView (cab) in android

I want to delete multiple selected items (row) in my listview (Gmail style).
If I select (with longClick) a row, nothing happens.
I've found this code on internet, and i've tried to insert it in my project.
MainActivity
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(Lista.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menu) {
switch (menu.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selectedItem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selectedItem);
}
}
actionMode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.delete_menu, menu);
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position,
long arg2, boolean arg3) {
final int checkedOut = Lista.getCheckedItemCount();
actionMode.setTitle(checkedOut + " selezionato");
adapter.toggleSelection(position);
}
and this is the adapter
public class ListaAdapter extends ArrayAdapter<ListViewItem> {
private Context context;
private ArrayList<ListViewItem> items;
private SparseBooleanArray mSelectedItemsIds;
public ListaAdapter(Context context, int resourceId,
ArrayList<ListViewItem> items) {
super(context, resourceId, items);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.items = items;
}
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtSubTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_view_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView
.findViewById(R.id.TitoloPrincipale);
holder.txtSubTitle = (TextView) convertView
.findViewById(R.id.Sottotitolo);
holder.imageView = (ImageView) convertView.findViewById(R.id.Image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListViewItem list = getItem(position);
holder.txtTitle.setText(list.getNomeFarmaco());
holder.txtSubTitle.setText(list.getFasceOrarie());
holder.imageView.setImageResource(list.getIcon());
// convertView
// .setBackgroundColor(mSelectedItemsIds.get(position)
// : Color.TRANSPARENT);
return convertView;
}
public void remove(ListViewItem item) {
items.remove(item);
notifyDataSetChanged();
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
have you got any idea?
tks
That code has nothing to do with long-clicks. The only occurrence of "long" is for a long parameter to a method. :-)
This sample project demonstrates an action mode starting up based upon a long-click of a list row. The key is onItemLongClick():
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setItemChecked(position, true);
return(true);
}
Here (courtesy of registering the activity as the OnItemLongClickListener for the ListView), we toggle on CHOICE_MODE_MULTIPLE_MODAL and check the item that was long-clicked, thereby activating the action mode.
The major problem you have not setMultiChoiceModeListener for listview like below
(Plz, see carefully onCreateActionMode and the loop in onActionItemClicked)
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
mode.getMenuInflater().inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
// TODO Auto-generated method stub
switch (menuItem.getItemId()) {
case R.id.mnDelete:
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for(int i = sparseBooleanArray.size() -1; i >= 0; i--)
items.remove(sparseBooleanArray.keyAt(i));
adapter.notifyDataSetChanged();
mode.finish();
break;
default:
break;
}
return true;
}
});
}
I've solved. thank you all.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch (arg1.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selecteditem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selecteditem);
}
}
// Close CAB
arg0.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
arg0.getMenuInflater().inflate(R.menu.delete_menu, arg1);
return true;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode arg0, int arg1, long arg2,
boolean arg3) {
final int checkedCount = Lista.getCheckedItemCount();
arg0.setTitle(checkedCount + " Selected");
adapter.toggleSelection(arg1);
}
}

How do i call a context menu on longclick in a ListView Item?

HomeFragment
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
I just need 3 items on the context menu: Like, Comment and Favorite. I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.
Here´s my adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Are the changes supposed to go in the adapter or the fragment? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick. Any help would be appreciated.
I managed to get one context menu working, right here:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
adapter = new ListViewAdapter(getActivity(), arraylist);
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Opções");
menu.add(0, v.getId(), 0, "Like");
menu.add(1, v.getId(), 0, "Comment");
menu.add(2, v.getId(), 0, "Favorite");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
addLike(item.getItemId());
} else if (item.getTitle() == "Comment") {
} else if (item.getTitle() == "Favorite") {
// code
} else {
return false;
}
return true;
}
public void addLike(int id){
}
Right after the return rootView in the HomeFragment. Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case).
first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setAdapter(adapter);
then register for MultiChoiceModeListener and override his methods in your liking :)
myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// here you will inflate your CAB
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Here is the link

Categories