Searchview in custom ArrayAdapter - java

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

Related

ExpandableListview set bold and normal text when click menu

I am working on my expandablelistview menu that when I click on the menu item, I want to set the menu item to bold while set the other menu item to normal textype.
ExpandableListAdapter:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private HashMap<String, String> imgnamedata;
private boolean hasChild = false;
private int selectedItem;
public ExpandableListAdapter(MainActivity context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild, HashMap<String, String> img_data) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listDataChild;
this.imgnamedata = img_data;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(
this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public boolean isHasChild (boolean hasChild) {
return hasChild;
}
public void selectItem(int selectedItem){
this.selectedItem = selectedItem;
notifyDataSetChanged();
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition,
childPosition);
//final HeaderModel header = (HeaderModel) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item1, null);
}
final TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
//txtListChild.setTypeface(null, Typeface.NORMAL);
txtListChild.setText(childText);
txtListChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isChildSelectable = true;
txtListChild.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
}
});
return convertView;
}
private boolean isHasChild() {
return hasChild;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(
this._listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
int c_size = getChildrenCount(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
// changing the +/- on expanded list view
// this is the +/- text view that act as image.
// on expand this change to - and on close it again change to +
ImageView txt_plusminus = (ImageView) convertView
.findViewById(R.id.plus_txt);
if (c_size > 0) {
txt_plusminus.setVisibility(View.VISIBLE);
if (isExpanded) {
txt_plusminus.setImageDrawable(this._context.getResources().getDrawable(R.drawable.downarrow));
} else {
txt_plusminus.setImageDrawable(this._context.getResources().getDrawable(R.drawable.rightarrow));
}
} else {
txt_plusminus.setVisibility(View.GONE);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
// lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
lblListHeader.setTypeface(null, Typeface.BOLD);
// Either you can use this below for setting icon in main menu:
// adding icon to expandable list view
ImageView imgListGroup = (ImageView) convertView
.findViewById(R.id.ic_txt);
String icn = this.imgnamedata.get(headerTitle);
if (icn != null) {
String uri = "#drawable/" + icn;
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = null;
try {
res = getResources().getDrawable(imageResource);
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
if (res != null) {
imgListGroup.setImageDrawable(res);
} else {
imgListGroup.setImageResource(R.drawable.ic_launcher_background);
}
} else {
imgListGroup.setImageResource(R.drawable.ic_launcher_background);
}
return convertView;
}
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ExpandableListView interface1,if_list,adons_list,ss_list,tool_list;
ImageView close_d;
Toolbar toolbar;
WebView webview;
TextView lblListHeader;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
RelativeLayout drawer_relative, interface1_test;
private boolean isSelected = false;
private boolean isChildSelectable = false;
private String selectedText = null;
private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener() {
#Override
public void onDrawerStateChanged(int status) {
}
#Override
public void onDrawerSlide(View view, float slideArg) {
}
#Override
public void onDrawerOpened(View view) {
// toolbar.setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View view) {
// toolbar.setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
// invalidateOptionsMenu();
}
};
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
close_d = findViewById(R.id.close_d);
drawer_relative = findViewById(R.id.drawer_relative);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(mDrawerListener);
interface1 = (ExpandableListView) findViewById(R.id.interface1);
if_list = (ExpandableListView) findViewById(R.id.if_list);
adons_list = (ExpandableListView) findViewById(R.id.adons_list);
ss_list = (ExpandableListView) findViewById(R.id.ss_list);
tool_list = (ExpandableListView) findViewById(R.id.tool_list);
lblListHeader = (TextView) findViewById(com.dvinfosys.R.id.lblListHeader);
webview = (WebView) findViewById(R.id.webview);
isSelected = false;
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
// toolbar.setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
// invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
// toolbar.setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
ArrayList dashbord_listDataHeader = new ArrayList<String>();
HashMap<String, List<String>> dashbord_listDataChild = new HashMap<String, List<String>>();
HashMap<String, String> img_data = new HashMap<>();
dashbord_listDataHeader.add("Dashboard");
dashbord_listDataChild.put("Dashboard",new ArrayList<String>());
img_data.put("Dashboard","dashboard");
ExpandableListAdapter listAdapter = new ExpandableListAdapter(MainActivity.this, dashbord_listDataHeader,
dashbord_listDataChild,img_data);
interface1.setAdapter(listAdapter);
interface1.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
selectedText = "Dashboard";
TextView dashboard = v.findViewById(R.id.lblListHeader);
dashboard.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
return false;
}
});
HashMap<String, String> img_data1 = new HashMap<>();
HashMap<String, List<String>> interface_listDataChild = new HashMap<String, List<String>>();
ArrayList interface_listDataHeader = new ArrayList<String>();
List<String> sub_data = new ArrayList<>();
List<String> sub_data1 = new ArrayList<>();
interface_listDataHeader.add("Contacts");
interface_listDataHeader.add("Newsletters");
sub_data.add("Search Contacts");
sub_data.add("Add Contacts");
sub_data.add("Import Contacts");
sub_data1.add("Create Newsletter");
sub_data1.add("My Newsletters");
interface_listDataChild.put("Contacts", sub_data);
interface_listDataChild.put("Newsletters", sub_data1);
img_data1.put("Contacts","contacts");
img_data1.put("Newsletters","newsletter");
ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(MainActivity.this, interface_listDataHeader,
interface_listDataChild,img_data1);
if_list.setAdapter(listAdapter1);
if_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
return false;
}
});
ArrayList addons_listDataHeader = new ArrayList<String>();
HashMap<String, String> img_data2 = new HashMap<>();
HashMap<String, List<String>> addons_listDataChild = new HashMap<String, List<String>>();
List<String> sub_data2 = new ArrayList<>();
addons_listDataHeader.add("Autoresponder");
addons_listDataHeader.add("My Campaign");
addons_listDataHeader.add("Split Tests");
sub_data2.add("Create Autoresponder");
sub_data2.add("My Autoresponder");
addons_listDataChild.put("Autoresponder", sub_data2);
addons_listDataChild.put("My Campaign",new ArrayList<String>());
addons_listDataChild.put("Split Tests",new ArrayList<String>());
img_data2.put("Autoresponder","autoresponder");
img_data2.put("My Campaign","campaign");
img_data2.put("Split Tests","splittest");
ExpandableListAdapter listAdapter2 = new ExpandableListAdapter(MainActivity.this, addons_listDataHeader,
addons_listDataChild,img_data2);
adons_list.setAdapter(listAdapter2);
adons_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
TextView addon_header = v.findViewById(R.id.lblListHeader);
if (id == 1) {
selectedText = "Campaign";
}
else if (id == 2) {
selectedText = "Split Tests";
}
addon_header.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
return false;
}
});
}
When I click on the menu item, example: My Newsletter. The menu item "Dashboard" have a bold so I want to set the "Dashboard" to normal typetext and set the menu item "My Newsletter" to bold typetext. And when I click menu item "Create Newsletter", I want to set the the "My Newsletter" to normal typetext and set the menu item "Create Newsletter" to bold.
On my code, what it will do that it will set the menu item to bold when I click on the menu item but it wont set the other menu item to normal.
Can you please show me an example how I could do that using with my code?
EDIT: I have tried this:
ss_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
TextView ss_header = v.findViewById(R.id.lblListHeader);
ss_header.setTypeface(null, Typeface.NORMAL);
if (id == 0) {
//do something
}
else if (id == 1) {
//do something
}
ss_header.setTypeface(null, Typeface.BOLD);
mDrawerLayout.closeDrawers();
return false;
}
});`
you can try this for changing the text style
button/textView.setTypeface(Typeface.DEFAULT_BOLD/NORMAL);
and on each button press, set the text as you wish.
I hope it could help

How to fill title and grid layouts with the next page "10 items"

In my app I have four layouts, "Card List" , "Card Magazine" , "Title" and "Grid", I make option menu to allow the users to change it from the Option Menu "change the layout", the problem happening here is when running the app first time with choosing Title or Grid layout, it's show the only first page "10 items" the result come from retrofit call
To relate see this question
in old version of this app "When I used activity" I solved this problem with this lines of code on Title and Grid Viewholder
if(position == getItemCount() -1)
if(context instanceof MainActivity){
((MainActivity)context).getMainPagePosts();
}
but in this version I using fragments, so when I tried to thinking to solve it I created interface called "WhichFragmentCalled" and give it the fragment and viewHolder as a parameters
public interface WhichFragmentCalled {
void whichFragmentAndViewModel(Fragment fragment, PostViewModel postViewModel);
}
Then I used it in adapter and fragment like this
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
WhichFragmentCalled whichFragmentCalled = adapter;
whichFragmentCalled.whichFragmentAndViewModel(this,postViewModel);
}
and make the adapter implement this interface, here's the full PostAdapter code
public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements WhichFragmentCalled{
private Context context;
private List<Item> items;
private static final int CARD = 0;
private static final int CARD_MAGAZINE = 1;
private static final int TITLE = 2;
private static final int GRID = 3;
private static final int SDK_VERSION = Build.VERSION.SDK_INT;
public static final String TAG = "POST ADAPTER";
private int viewType;
private int position;
private Fragment fragment;
private PostViewModel postViewModel;
public PostAdapter(Context context, List<Item> items) {
this.context = context;
this.items = items;
}
public void setViewType(int viewType) {
this.viewType = viewType;
notifyDataSetChanged();
}
public int getViewType() {
return this.viewType;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view;
if (this.viewType == CARD) {
view = inflater.inflate(R.layout.card, parent, false);
return new CardViewHolder(view);
} else if (this.viewType == CARD_MAGAZINE) {
view = inflater.inflate(R.layout.card_magazine, parent, false);
return new CardMagazineViewHolder(view);
} else if (this.viewType == TITLE) {
if(SDK_VERSION < Build.VERSION_CODES.LOLLIPOP){
view = inflater.inflate(R.layout.title_layout_v15,parent,false);
}else {
view = inflater.inflate(R.layout.title_layout, parent, false);
}
return new TitleViewHolder(view);
} else {
if(SDK_VERSION < Build.VERSION_CODES.LOLLIPOP){
view = inflater.inflate(R.layout.grid_layout_v15,parent,false);
}else {
view = inflater.inflate(R.layout.grid_layout, parent, false);
}
return new GridViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
this.position = position;
int itemType = getViewType();
Item item = items.get(holder.getAdapterPosition());
final Document document = Jsoup.parse(item.getContent());
final Elements elements = document.select("img");
// Log.e("IMAGE", document.getAllElements().select("img").get(0).attr("src"));
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
Intent intent = new Intent(context, DetailsActivity.class);
switch (itemType) {
case CARD:
if (holder instanceof CardViewHolder) {
CardViewHolder cardViewHolder = (CardViewHolder) holder;
cardViewHolder.postTitle.setText(item.getTitle());
try {
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(cardViewHolder.postImage);
}catch (IndexOutOfBoundsException e){
cardViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
}
cardViewHolder.postDescription.setText(document.text());
try {
date = format.parse(items.get(position).getPublished());
} catch (ParseException e) {
e.printStackTrace();
}
PrettyTime prettyTime = new PrettyTime();
cardViewHolder.postDate.setText(prettyTime.format(date));
cardViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility = 0;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video")) {
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
}
if (youtubeThumbnailImageSrc.isEmpty()) {
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
} else {
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
}
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
}
});
}
break;
case CARD_MAGAZINE:
if (holder instanceof CardMagazineViewHolder) {
CardMagazineViewHolder cardMagazineViewHolder = (CardMagazineViewHolder) holder;
cardMagazineViewHolder.postTitle.setText(item.getTitle());
try {
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(cardMagazineViewHolder.postImage);
}catch (IndexOutOfBoundsException e){
cardMagazineViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
}
try {
date = format.parse(items.get(position).getPublished());
} catch (ParseException e) {
e.printStackTrace();
}
PrettyTime prettyTime = new PrettyTime();
cardMagazineViewHolder.postDate.setText(prettyTime.format(date));
cardMagazineViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility = 0;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video")) {
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
}
if (youtubeThumbnailImageSrc.isEmpty()) {
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
} else {
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
}
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
}
});
}
break;
case TITLE:
if (holder instanceof TitleViewHolder) {
TitleViewHolder titleViewHolder = (TitleViewHolder) holder;
titleViewHolder.postTitle.setText(item.getTitle());
Log.d("TITLE", "title layout called");
try {
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(titleViewHolder.postImage);
}catch (IndexOutOfBoundsException e){
titleViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
}
titleViewHolder.itemView.setOnClickListener(view -> {
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility = 0;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video")) {
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
}
if (youtubeThumbnailImageSrc.isEmpty()) {
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
} else {
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
}
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
});
}
break;
case GRID:
if (holder instanceof GridViewHolder) {
GridViewHolder gridViewHolder = (GridViewHolder) holder;
gridViewHolder.postTitle.setText(item.getTitle());
try {
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(gridViewHolder.postImage);
}catch (IndexOutOfBoundsException e){
gridViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
}
gridViewHolder.itemView.setOnClickListener(view -> {
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video")) {
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
}
if (youtubeThumbnailImageSrc.isEmpty()) {
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
} else {
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
}
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
});
}
}
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void whichFragmentAndViewModel(Fragment fragment, PostViewModel postViewModel) {
this.fragment = fragment;
this.postViewModel = postViewModel;
if(position == getItemCount() -1) {
postViewModel.getPosts();
notifyDataSetChanged();
}
}
public class CardViewHolder extends RecyclerView.ViewHolder {
ImageView postImage;
TextView postTitle,postDescription, postDate;
private CardViewHolder(View itemView) {
super(itemView);
postImage = itemView.findViewById(R.id.postImage);
postTitle = itemView.findViewById(R.id.postTitle);
postDescription = itemView.findViewById(R.id.postDescription);
postDate = itemView.findViewById(R.id.postDate);
}
}
public class CardMagazineViewHolder extends RecyclerView.ViewHolder {
ImageView postImage;
TextView postTitle, postDate;
private CardMagazineViewHolder(View itemView) {
super(itemView);
postImage = itemView.findViewById(R.id.postImage);
postTitle = itemView.findViewById(R.id.postTitle);
postDate = itemView.findViewById(R.id.postDate);
}
}
public class TitleViewHolder extends RecyclerView.ViewHolder {
TextView postTitle;
MyImageview postImage;
private TitleViewHolder(#NonNull View itemView) {
super(itemView);
postTitle = itemView.findViewById(R.id.postTitle);
postImage = itemView.findViewById(R.id.postImage);
}
}
public class GridViewHolder extends RecyclerView.ViewHolder {
TextView postTitle;
MyImageview postImage;
private GridViewHolder(#NonNull View itemView) {
super(itemView);
postTitle = itemView.findViewById(R.id.postTitle);
postImage = itemView.findViewById(R.id.postImage);
}
}
}
now this code work only when I switch from the title or grid layout to others layout and back to it again, I think the onBindViewHolder not detect this implement of interface at the first time, so the challenge is How to move the implement of this interface insede onBindViewHolder method
#Override
public void whichFragmentAndViewModel(Fragment fragment, PostViewModel postViewModel) {
this.fragment = fragment;
this.postViewModel = postViewModel;
if(position == getItemCount() -1) {
postViewModel.getPosts();
notifyDataSetChanged();
}
}
This how I use the change layout in fragments, I removed unrelated with question codes
HomeFragment class
private PostViewModel postViewModel;
public static final String TAG = "HomeFragment";
private RecyclerView recyclerView;
private PostAdapter adapter;
private List<Item> itemArrayList;
private boolean isScrolling = false;
private int currentItems, totalItems, scrollOutItems;
private GridLayoutManager titleLayoutManager, gridLayoutManager;
WrapContentLinearLayoutManager layoutManager;
private SharedPreferences sharedPreferences;
public ItemsDatabase itemsDatabase;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
postViewModel = new ViewModelProvider(this).get(PostViewModel.class);
itemsDatabase = ItemsDatabase.getINSTANCE(getContext());
postViewModel.finalURL.setValue(PostsClient.getBaseUrl() + "?key=" + PostsClient.getKEY() );
postViewModel.getPosts();
View root = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
itemArrayList = new ArrayList<>();
recyclerView = root.findViewById(R.id.homeRecyclerView);
adapter = new PostAdapter(getContext(),itemArrayList);
layoutManager = new WrapContentLinearLayoutManager(getContext(),
LinearLayoutManager.VERTICAL, false);
titleLayoutManager = new GridLayoutManager(getContext(), 2);
gridLayoutManager = new GridLayoutManager(getContext(), 3);
sharedPreferences = getContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
String layout = sharedPreferences.getString("recyclerViewLayout", "cardLayout");
switch (layout) {
case "cardLayout":
recyclerView.setLayoutManager(layoutManager);
adapter.setViewType(0);
recyclerView.setAdapter(adapter);
break;
case "cardMagazineLayout":
recyclerView.setLayoutManager(layoutManager);
adapter.setViewType(1);
recyclerView.setAdapter(adapter);
break;
case "titleLayout":
recyclerView.setLayoutManager(titleLayoutManager);
adapter.setViewType(2);
recyclerView.setAdapter(adapter);
adapter.whichFragmentAndViewModel(this,postViewModel);
break;
case "gridLayout":
recyclerView.setLayoutManager(gridLayoutManager);
adapter.setViewType(3);
recyclerView.setAdapter(adapter);
adapter.whichFragmentAndViewModel(this,postViewModel);
}
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
isScrolling = true;
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
if(layout.equals("cardLayout") || layout.equals("cardMagazineLayout")) {
currentItems = layoutManager.getChildCount();
totalItems = layoutManager.getItemCount();
scrollOutItems = layoutManager.findFirstVisibleItemPosition();
}else if(layout.equals("titleLayout")){
currentItems = titleLayoutManager.getChildCount();
totalItems = titleLayoutManager.getItemCount();
scrollOutItems = titleLayoutManager.findFirstCompletelyVisibleItemPosition();
}else {
currentItems = gridLayoutManager.getChildCount();
totalItems = gridLayoutManager.getItemCount();
scrollOutItems = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
}
if (isScrolling && (currentItems + scrollOutItems == totalItems)) {
isScrolling = false;
postViewModel.getPosts();
// adapter.notifyDataSetChanged();
}
}
}
});
return root;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
//Empty the old menu
// if(menu.hasVisibleItems()){
// menu.clear();
// }
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.change_layout) {
android.app.AlertDialog.Builder builder
= new android.app.AlertDialog.Builder(getContext());
builder.setTitle(getString(R.string.choose_layout));
String[] recyclerViewLayouts = getResources().getStringArray(R.array.RecyclerViewLayouts);
SharedPreferences.Editor editor = sharedPreferences.edit();
builder.setItems(recyclerViewLayouts, (dialog, index) -> {
switch (index) {
case 0: // Card List Layout
adapter.setViewType(0);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "cardLayout");
editor.apply();
break;
case 1: // Cards Magazine Layout
adapter.setViewType(1);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "cardMagazineLayout");
editor.apply();
break;
case 2: // PostTitle Layout
adapter.setViewType(2);
recyclerView.setLayoutManager(titleLayoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "titleLayout");
editor.apply();
break;
case 3: //Grid Layout
adapter.setViewType(3);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "gridLayout");
editor.apply();
}
});
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
WhichFragmentCalled whichFragmentCalled = adapter;
whichFragmentCalled.whichFragmentAndViewModel(this,postViewModel);
}
}
This is more of a suggestion than an answer, but if you are going to use the ViewModel, I strongly suggest that you move all the business logic (pretty much anything non-ui related), and move it inside your viewmodel. You can read more about MVVM architecture from the android site.
As for your actual question, if you are showing only 10 objects, then it sounds like your data list only has 10 objects - so I suggest validating the data list you are receiving from retrofit, and then validate it while it's passing to your adapter. Logs and/or breakpoints will help you.
Also, for simplicity of my explanation, I would move all of the code in onCreateView() that comes after the setHasOptionsMenu(true); and move it into onViewCreated() so you don't accidentally have null views. I would then move all your adapter/recyclerview logic into onResume() so that the lists/ui are properly restored on configuration/state changes.
If PostAdapter is being used for all the different layouts, then there is no need for your interface. You would only need one Fragment class, one ViewModel, and one RecyclerView.Adapter, because if I understand it correctly, you are using the same list of objects, so you really only need to focus on changing the views/layouts for the adapter.
To change layouts:
invalidate your current visible list in the recycler view, by setting the reference to your adapter to null. recyclerView.setAdapter(null);
Create a new instance of your adapter, if you have your data set saved in your viewmodel, you can just pass that to your new adapter, instead of fetching more objects from retrofit.
then, set the new adapter back to the recyclerView, and apply the appropriate LayoutManager for the situation.
postViewModel.getPosts(); - if this is loading post objects from retrofit, then this is another potential bug because retrofit is generally asynchronous, and it doesn't look like you have any conditional checks to make sure your list is ready before passing it to the adapter. You can easily solve this problem with Androids LiveData objects. They're amazing and are perfect for your use case.

SearchView in Toolbar not filtering ListFragment

I'm trying to implement a SearchView within a Toolbar for a ListFragment, but for some reason filtering is not working. The SearchView and keyboard appear as normal, but the ListView does not get filtered as I type something in.
fragment class
public class MyFragment extends ListFragment implements SearchView.OnQueryTextListener {
public MyFragment() {}
private ListView lv;
private MyListAdapter mAdapter;
public static MyFragment newInstance() {
return new MyFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
initialize();
return view;
}
List<Product> myList = new ArrayList<>();
private void initialize() {
String[] items = getActivity().getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getActivity().getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product product = new Product();
product.setProductName(items[n]);
product.setProductDescription(itemDescriptions[n]);
myList.add(product);
}
mAdapter = new MyListAdapter(myList, getActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
mTwoPane = getActivity().findViewById(R.id.detail_container) != null;
assert v != null;
lv = v.findViewById(android.R.id.list);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyListAdapter adapter = (MyListAdapter) parent.getAdapter();
}
});
super.onActivityCreated(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuInflater mInflater = Objects.requireNonNull(getActivity()).getMenuInflater();
mInflater.inflate(R.menu.menu_search, menu);
MenuItem searchitem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchitem.getActionView();
searchView.setQueryHint(Objects.requireNonNull(getContext()).getText(R.string.searchhint_productname));
super.onCreateOptionsMenu(menu, inflater);
}
}
adapter class
public class MyListAdapter extends BaseAdapter implements Filterable {
private List<Product> myList;
private List<Product> myListFull;
private LayoutInflater mInflater;
public MyListAdapter(List<Product> data, Context context) {
myList = data;
myList = new ArrayList(myList);
myListFull = new ArrayList(myList);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Object getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyListAdapter.ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, parent, false);
holder = new MyListAdapter.ViewHolder();
holder.title = convertView.findViewById(R.id.listitem_title);
holder.description = convertView.findViewById(R.id.listitem_subtitle);
convertView.setTag(holder);
} else {
holder = (MyListAdapter.ViewHolder) convertView.getTag();
}
Product mProduct = (Product)getItem(position);
holder.title.setText(mProduct.getProductName());
holder.description.setText(mProduct.getProductDescription());
return convertView;
}
/**
* View holder
*/
static class ViewHolder {
private TextView title;
private TextView description;
}
#Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Product> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(myListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Product item : myListFull) {
if (item.getProductName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
myList.clear();
myList.addAll((List<Product>) results.values);
notifyDataSetChanged();
}
};
}
You're missing OnQueryTextListener on your SearchView, simply attach one so that the adapter knows when to filter:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override public boolean onQueryTextSubmit(String query) {
return false;
}
#Override public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});

notifyDataSetChanged(); not refreshing ListView?

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

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