Updating ListView after selecting Item from Dialog Window - android

I've got the following Problem.
I have a ListView which displays me Articles with different Categories.
When I select a Category from my Dialog Window and press the PositiveButton "OK", I want to update my ListView, that it now lists only the Articles from the Category, selected in the Dialog Window.
I created an interface in the DialogFragment, which is a callback to get value from the Dialog.
This is the Class:
public class SelectFilterDialog extends DialogFragment implements DialogInterface.OnClickListener{
private static int mSelectedIndex;
private static String mSelectedCategory;
private String[] categories = {"All", "Announcements","Commerce","Development", "Distributions", "Front","Kernel","Legal", "Letters", "Press", "Security"};
static OnDialogSelectListener mDialogSelectorCallback;
//callback method to get values from a Dialog
public interface OnDialogSelectListener{
public void onSelectedOption();
}
public static SelectFilterDialog newInstance(int selected) {
final SelectFilterDialog dialog = new SelectFilterDialog();
mSelectedIndex = selected;
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Filter");
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Cancel", this);
builder.setSingleChoiceItems(categories, mSelectedIndex, this);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case Dialog.BUTTON_POSITIVE:{
dialog.dismiss();
mDialogSelectorCallback.onSelectedOption();
}break;
case Dialog.BUTTON_NEGATIVE:{
dialog.cancel();
}break;
default:
mSelectedIndex = which;
setSelectedCategory(categories[which]);
break;
}
}
public void setDialogSelectListener(OnDialogSelectListener listener){
this.mDialogSelectorCallback = listener;
}
public void setSelectedCategory(String category){
this.mSelectedCategory = category;
}
public static String getSelectedCategory(){
return mSelectedCategory;
}
public static int getSelectedIndex(){
return mSelectedIndex;
}
}
In my SearchFragment Class , i show the List and implement the Interface from the SelectFilterDialog Fragment.
In the Method, i update the selectedCategory, after pressing the OK button, and then update the adapter with notifyDataSetChanged()
SearchFragment:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_bar_filter: {
showDialog();
}
}
return super.onOptionsItemSelected(item);
}
void showDialog() {
SelectFilterDialog dialog = SelectFilterDialog.newInstance(preSelectedValue);
dialog.setDialogSelectListener(this);
dialog.show(getActivity().getFragmentManager(), "dialog");
}
#Override
public void onSelectedOption() {
selectedCategory = dialog.getSelectedCategory();
preSelectedValue = dialog.getSelectedIndex();
Log.i(TAG, "selectedCategory : " +selectedCategory);
article_list_adapter.updateCategory(selectedCategory);
}
In my Adapter, i receive the Category in my updateCategory and fill the currentArticle List with the Articles with the correct Category.
This works fine.
After that i call NotifyDataSetChanged to update the view.
public void updateCategory(String category) {
this.currentArticles.clear();
this.selectedCategory = category;
for (Article article : entireArticles) {
if (category.equals(article.getCategory())) {
currentArticles.add(article);
}
}
notifyDataSetChanged();
}
notifyDataSetChanged();
}
But in the getView it throws an IndexOutOfBounce exception.
After selecting a Category from the dialog, e.g "Kernel", it adds only my 3 Kernel Categories to the currentArticle List, which is fine.
But int the getView statement:
Article currentArticle = currentArticles.get(_position);
It points on index 3 , though there are only 3 elements in the list.
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at klinar.kronlachner.binder.app.Article_List_Adapter.getView(Article_List_Adapter.java:99)
Can you help me ? :)
public Article_List_Adapter(Context _c, int textViewResourceId, List<Article> articles) {
super(_c, textViewResourceId, articles);
this.entireArticles = new ArrayList<Article>();
this.currentArticles = new ArrayList<Article>();
entireArticles.addAll(articles);
currentArticles.addAll(articles);
this.storedArticles = new ArrayList<Article>(articles);
}
public View getView(int _position, View _convertView, ViewGroup _parent) {
View view = _convertView;
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.article_list_row, null);
viewHolder = new ViewHolder();
viewHolder.article_icon = (ImageView) view.findViewById(R.id.article_category_icon);
viewHolder.articleTitle = (TextView) view.findViewById(R.id.article_title);
viewHolder.articleCategory = (TextView) view.findViewById(R.id.article_category);
viewHolder.articleDate = (TextView) view.findViewById(R.id.article_date);
viewHolder.articleAuthor = (TextView) view.findViewById(R.id.article_author);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _convertView.getTag();
}
//Find the article to work with
Article currentArticle = currentArticles.get(_position);
//fill the Article_View
switch (currentArticle.getCategory()) {
case "Kernel": {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_k);
}
break;
case "Security": {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
break;
default: {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
}
viewHolder.articleTitle.setText(currentArticle.getTitle());
viewHolder.articleCategory.setText(currentArticle.getCategory());
viewHolder.articleDate.setText(currentArticle.getDate());
viewHolder.articleAuthor.setText(currentArticle.getAuthor());
return view;

Do this in your adapter class
create two List one for AllCategoryArticle and another for currentCategoryArticle.
class ArticleAdapter{
ArrayList<Model> currentArticle;
ArrayList<Model> entireArticle;
String selectedCategory="all"; //setting default category as "all"
public ArticleAdapter(ArrayList<Model> categoryList){
this.entireList=categoryList;
this.currentList=this.entireList;
}
//create updateCategory in adapter
/*call this method(updateCategory()) in you frgament/activity to update the adapter
according to you category that is selected in dialog
*/
public void updateCategory(String category){
this.currentArticle.clear();
this.selectedCategory=category;
for(Model item: entireArticle){
if(category.equals(item.getCategory()))
{
currentArticle.add(item);
}
}
notifyDataSetChanged();
}
........
........
#Override
public View getView(int _position, View _convertView, ViewGroup _parent) {
View view = _convertView;
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.article_list_row, null);
viewHolder = new ViewHolder();
viewHolder.article_icon = (ImageView) view.findViewById(R.id.article_category_icon);
viewHolder.articleTitle = (TextView) view.findViewById(R.id.article_title);
viewHolder.articleCategory = (TextView) view.findViewById(R.id.article_category);
viewHolder.articleDate = (TextView) view.findViewById(R.id.article_date);
viewHolder.articleAuthor = (TextView) view.findViewById(R.id.article_author);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _convertView.getTag();
}
//Find the article to work with
Article currentArticle = articles.get(_position);
//just remove if condition because already you have filtered article by category in currentArticle
//fill the Article_View
switch (currentArticle.getCategory()) {
case "Kernel":
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_k);
break;
case "Security":
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
break;
default:
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
viewHolder.articleTitle.setText(currentArticle.getTitle());
viewHolder.articleCategory.setText(currentArticle.getCategory());
viewHolder.articleDate.setText(currentArticle.getDate());
viewHolder.articleAuthor.setText(currentArticle.getAuthor());
return view;
}
}
Do this in your Activity/Fragment which has tha ArticleAdapter
modification in onSelectedOption() method in your activity/Fragment
#Override
public void onSelectedOption() {
selectedCategory = dialog.getSelectedCategory();
preSelectedValue = dialog.getSelectedIndex();
Log.i(TAG, "selectedCategory : " +selectedCategory);
article_list_adapter.updateSelectedCategory(selectedCategory);
Log.i(TAG, "adapter Category : " +article_list_adapter.getSelectedCategory());
/*
call updateCategory() instead of notifyDataSetChanged()
updateCategory() will update your adapter
*/
//article_list_adapter.notifyDataSetChanged();
article_list_adapter.updateCategory(selectedCategory);
}
Problem in your code is
your trying to update the adapter using notifyDataSetChanged without updating your list.
notifyDataSetChanged() will work when there is an update in adapter model not in any variable in your adapter . see this how notifyDataSetChanged works in listView
EDIT:changes in adapter class
class Adapter{
ArrayList entireArticle;
ArrayList currentArticle;
public Adapter(Context context,ArrayList list){
this.entireArticle=new ArrayList();
this.currentArticle=new ArrayList();
entireArticle.addAll(list);
currentArticle.addAll(list);
}
public void updateCategory(String category){
this.currentArticle.clear();
this.selectedCategory=category;
if(category.equals("All")){ // add all article from entrieArticle if category=="all"
this.currentArticle.addAll(entireArticle);
}else{ //otherwise filter the article
for(Model item: entireArticle){
if(category.equals(item.getCategory()))
{
currentArticle.add(item);
}
}
}
notifyDataSetChanged();
}
...............
.................
}
do this changes in your adapter class and it will work i've checked this.
I hope this will help you.

Related

Refresh Fargment from adapter

I know this question has been around, but trying solutions proposed in SO threads weren't helpful!
I Have an activity (Favorites) with 3 fragment (represent categories, Video/figures/other) ..in each fragment there is a list of favorites following the category ..
my problem is ..when i delete an item from list of favorite ..it get deleted from database but the listview don't get refresh instantely! ..i have to move between fragments for that to happen ..
i tried:
1. notifyDataSetChanged(); //do nothing
2. `refreshEvents(listfavorite);` // after the delete button onclick with refresh events=:
public void refreshEvents(final List<Data> events)
{
this.listfavorite.clear();
this.listfavorite.addAll(events);
notifyDataSetChanged();
The result of 2nd method: the list is cleared instantely but don't get repopulated again!
3.
//after on delete on click
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//listfavorite.addAll(events);
notifyDataSetChanged(); }
}, 1000);
This is my Fragment Adapter
public class FragmentAdapter extends BaseAdapter {
private List<Data> listfavorite;
Context context;
String name, packagename, id, section;
Long _id;
private DBManager dbManager;
boolean isFavourite;
private LayoutInflater mInflater;
public FragmentAdapter(Context FragmentOther,List<Data> resultsFavorite){
this.listfavorite = resultsFavorite;
this.context=FragmentOther;
mInflater = LayoutInflater.from(FragmentOther);
}
public void removeItemAtPosition(int position) {
if (listfavorite != null) {
listfavorite.remove(position);
notifyDataSetChanged();
}
}
public void clearAll() {
if (listfavorite != null) {
listfavorite.clear();
notifyDataSetChanged();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listfavorite.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return listfavorite.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int position, View rowView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if(rowView == null){
rowView = mInflater.inflate(R.layout.activity_view_record, null);
holder = new ViewHolder();
//define those textsview that corresponds to the row views so later we'll retrieve the data from them
holder.idTextView = (TextView) rowView.findViewById(R.id.id);
holder.nameTextView = (TextView) rowView.findViewById(R.id.name);
holder.sectionTextView = (TextView) rowView.findViewById(R.id.section);
holder.packageTextView = (TextView) rowView.findViewById(R.id.packagename);
//retrieve to this strings
id = listfavorite.get(position).getIdFav();
name = listfavorite.get(position).getNameAct();
section = listfavorite.get(position).getSectionName();
packagename = listfavorite.get(position).getPackageAct();
//This will be used for deleting data, because delete data we'll need to pass a long type variable
_id = Long.parseLong(id);
// define the button/textview because the popmenu needs a header!
holder.viewoption=(TextView) rowView.findViewById(R.id.textViewOptions);
holder.viewoption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// so we can use a custom pop menu we'll use this code, first define the contextwrapper
// and define the style of popmenu as second argument! , the style should have as parent
// Widget.AppCompat.PopupMenu ! then
//pass it in popmenu as firstargument
// the gravity.right serve to create margin from right side of the screen
Context wrapper = new ContextThemeWrapper(context, R.style.YOURSTYLE);
//creating a popup menu
PopupMenu popup = new PopupMenu(wrapper, holder.viewoption, Gravity.RIGHT);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
// this is really important! to show icon you should use this function, because the icons in normal
// cases don't show up! (we pass the name of the popupmenu inside
setForceShowIcon(popup);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//delete from database
//Open the database
dbManager = new DBManager(context);
dbManager.open();
dbManager.delete(_id);
//change value of isfav
isFavourite = false;
//save it to sharedprefrenece, the state will be read in other activities and
//show the correspondante state False or true
saveState(isFavourite);
refreshEvents(listfavorite);
notifyDataSetChanged();
//update activity so it'll delete it
// onResume();
break;
case R.id.gotoact:
Intent access_activity = new Intent();
//we use this type of intent because it allow us to use strins for intent
//after retrieving data from row, we'll pass it as second argument
access_activity.setClassName(context,packagename);
context.startActivity(access_activity);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.nameTextView.setText(Html.fromHtml(listfavorite.get(position).getNameAct()));
holder.sectionTextView.setText(listfavorite.get(position).getSectionName());
return rowView;
}
public void refreshEvents(final List<Data> events)
{
this.listfavorite.clear();
this.listfavorite.addAll(events);
notifyDataSetChanged();
}
my fragment.java
public class FragmentVideosFav extends Fragment {
private static final String ARG_TITLE = "title";
private String mTitle;
//------Define Database
private DBManager dbManager;
//
List<Data> listContact;
//ListView
private ListView listView;
// Adapter
private FragmentAdapter adapter;
public FragmentVideosFav (){}
public static FragmentVideosFav getInstance(String title) {
FragmentVideosFav fra = new FragmentVideosFav();
Bundle bundle = new Bundle();
bundle.putString(ARG_TITLE, title);
fra.setArguments(bundle);
return fra;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
mTitle = bundle.getString(ARG_TITLE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_other, container, false);
listContact = Getlistfavorite();
//define the list
listView = (ListView) v.findViewById(R.id.list_view);
//if the list is empty! set the correspondante layout!
listView.setEmptyView(v.findViewById(R.id.empty));
// set list to the adapter
adapter= new FragmentAdapter(getActivity(),listContact);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return v;
}
//refresh fragment when switch to ..
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(
isVisibleToUser);
if (getFragmentManager() != null) {
getFragmentManager()
.beginTransaction()
.detach(this)
.attach(this)
.commit();
}
}
// init Data of fragment
private List<Data> Getlistfavorite(){
List<Data> favoritelist = new ArrayList<Data>();
dbManager = new DBManager(getActivity());
dbManager.open();
Cursor c = dbManager.fetchvideo();
//startManagingCursor(c);
int ititle = c.getColumnIndex(_ID);
int idesc = c.getColumnIndex(ACTIVITY_NAME);
int isection = c.getColumnIndex(SECTION_NAME);
int ipath = c.getColumnIndex(PACKAGE_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
String title = c.getString(ititle);
String desc = c.getString(idesc);
String section = c.getString(isection);
String path = c.getString(ipath);
favoritelist.add(new Data(title, desc , section , path));}
return favoritelist;
}
}
Try this:
View getView(int position, View rowView, ViewGroup parent) {
Data favorite = listfavorite.get(position);
// Etc
case R.id.delete:
dbManager = new DBManager(context);
dbManager.open();
dbManager.delete(_id);
//change value of isfav
isFavourite = false;
//save it to sharedprefrenece, the state will be read in other activities and
//show the correspondante state False or true
saveState(isFavourite);
listfavorite.remove(favorite);
notifyDataSetChanged();

How to get text on selected checkbox from listview in android

I am working on android example, when i click on checkbox then it gets the textviews value of first item(Position) in listview every time. so but i want to get value of selected (position) checkbox textview value. how to solve it please help .i am a fresher.Thanks in advances.
Some Code In BaseAdapter class
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.list_adapter_view, null);
viewItem.txtTitle = (TextView)convertView.findViewById(R.id.inactivelistview);
// viewItem.txtDescription = (TextView)convertView.findViewById(R.id.adapter_text_description);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.txtTitle.setText(valueList.get(position).username);
// viewItem.txtDescription.setText(valueList.get(position).cources_description);
return convertView;
}
Some Code in activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_in_active_list);
listCollege = (ListView)findViewById(R.id.listCollege);
proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
checkbox = (CheckBox)findViewById(R.id.checkbox_me);
button =(Button)findViewById(R.id.button1);
new GetHttpResponse(this).execute();
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkbox_me:
if (checked) {
username = (TextView)findViewById(R.id.inactivelistview);
Username =username.getText().toString();
System.out.println("print username_=== "+Username);
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Do you want activate "+Username+"?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), Username+" acivated", Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
} else
break;
}
I am getting textviews value of first item(Position) in listview every time.
Please help me how to solve.help me update my code
Thank you so much.......
Note that checkbox return array as user can tick multiple elements.
ArrayList<String> selectedStrings = new ArrayList<String>();
The answer describe it in details.
use gettag on onCheckboxClicked method so that you can identify which row number checkbox is click . then you can get the textview of that row use row number
If your CheckBox is in ListView then no need to create ClickListener in Activity. Follow below steps to get selected text from ListView.
First create a model/pojo class, this will help you to store reference of selected CheckBox and also values which is going to show in ListView.
public class MyModel {
private boolean isSelected;
private String name;
public MyModel(boolean isSelected, String name) {
this.isSelected = isSelected;
this.name = name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
this.isSelected = selected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create a interface which will work as a callback.
public interface ItemSelectListener {
void getSelectedItemText(String text);
}
Refactor your BaseAdapter as now it will accept list of our Model class and also callback listener.
public MyAdapter extends BaseAdapter {
private final List<MyModel> mDataItems;
private final ItemSelectListener mItemListener;
public MyAdapter(List<MyModel> dataItems, ItemSelectListener itemListener)
mDataItems = dataItems;
mItemListener = itemListener;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null) {
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.list_adapter_view, null);
viewItem.txtTitle = (TextView)convertView.findViewById(R.id.inactivelistview);
// Add checkbox in your view item and confirm id of checkbox
viewItem.checkBox = (CheckBox)convertView.findViewById(R.id. checkbox_me);
}
else {
viewItem = (ViewItem) convertView.getTag();
}
final MyModel data = mDataItems.get(position);
viewItem.txtTitle.setText(data.getName());
viewItem.checkBox.setChecked(data.isSelected());
viewItem.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton button, boolean checked)
{
data.setSelected(checked);
if(checked) {
// Make sure you override this in your Activity
mItemListener.getSelectedItemText(data.getName());
}
}
});
return convertView;
}
}
Create datasource for ListView in your Activity.
BaseAdapter adapter = new BaseAdapter(dataItems, itemListener);

Please suggest me on proper usage of notifyDataSetChanged()

I'm using view pager with swiping tab layouts. And i'm displaying list view of data using custom adapter. And also onclick of list view i have a list view detail activity where I'm displaying data in more detail. In these detail activity i'm performing some changes to the data(some post method). after that I create an instance of customAdapter class and call notifyDataSetChanged() in order to refresh list view. My problem over here is the list view some times refreshes quickly and some times there is a delay of some seconds.
So, Can somebody suggest me proper usage of list view and what changes needs to be done in order to refresh list view whenever a post method is performed.
My code Fragment class:
private void showJsonData(String response) {
try {
String serviceID = LoggedInUserStore.getLoggedInServiceId(getContext());
List<Complaint> userList = new ArrayList<>(); //ArrayList of type user(POJO CLASS)
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
if (serviceID.equals(jsonArray.getJSONObject(i).getString("ServiceID"))) {
if (jsonArray.getJSONObject(i).getString("CallStatusID").equalsIgnoreCase("1")) {
userList.add(0, Complaint.fromJson(jsonArray.getJSONObject(i))); //
}
}
}
assignAdapter = new AssignAdapter(getActivity(), userList);
listView.setAdapter(assignAdapter);
listView.invalidateViews();
assignAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
My custom adapter class
public class AssignAdapter extends BaseAdapter implements Filterable {
List<Complaint> ticket = new ArrayList<>();
private Context context;
String ticketNo, complaint, raiseDate;
Complaint user;
List<Complaint> temporaryList = new ArrayList<>();
/*String status, priority;*/
public AssignAdapter(Context context, List<Complaint> ticket) {
this.context = context;
this.ticket = ticket;
this.temporaryList = ticket;
}
#Override
public int getCount() {
return temporaryList.size();
}
#Override
public Object getItem(int position) {
return temporaryList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class viewHolderItem {
TextView ticketNumberText, complaintNameText, raisedDateText;
}
//Set the layout for the fragment and return it.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolderItem holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_list_view, null, true);
holder = new viewHolderItem();
holder.ticketNumberText = (TextView) convertView.findViewById(R.id.ticketIdSupervisor);
holder.complaintNameText = (TextView) convertView.findViewById(R.id.complaintNameSupervisor);
convertView.setTag(holder);
} else {
holder = (viewHolderItem) convertView.getTag();
}
user = temporaryList.get(position);
if (user != null) {
//Get the Ticket Number
Typeface custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSerif.ttf");
ticketNo = temporaryList.get(position).getTicketNumber();
holder.ticketNumberText.setText(ticketNo);
holder.ticketNumberText.setTag("ticketNumber");
holder.ticketNumberText.setTypeface(custom_font);
//Get the complaint Name
complaint = temporaryList.get(position).getComplaintDetails();
holder.complaintNameText.setText(complaint);
holder.complaintNameText.setTag("complaint");
holder.complaintNameText.setTypeface(custom_font);
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context.getApplicationContext(), ComplaintDetailsSupervisor.class);
i.putExtra("COMPLAINT NAME", temporaryList.get(position).getComplaintDetails());
i.putExtra("RAISED DATE", temporaryList.get(position).getRaisedDate().substring(0, 10));
context.startActivity(i);
}
});
notifyDataSetChanged();
return convertView;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
My List view detail activity class
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
assignComplaint();
al.remove(position);
AssignAdapter assignAdapter = new AssignAdapter(getApplicationContext(), al);
assignAdapter.notifyDataSetChanged();
ComplaintDetailsSupervisor.this.finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
dialogButtonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
}
public void assignComplaint() throws JSONException {
//my custom method...
}
In the list view detail activity class i'm doing this
al.remove(position);
AssignAdapter assignAdapter = new AssignAdapter(getApplicationContext(), al);
assignAdapter.notifyDataSetChanged();
ComplaintDetailsSupervisor.this.finish();
Removing the position of list view and immediately calling adapter. This works fine but I don't know why sometimes it does not refreshes..May be when list view has a single item it does not refreshes immediately.
You are creating a new adapter and calling notifyDatasetChanged on it but have not called setAdapter with the new adapter as a parameter, hence why your list ist not refreshed.
You need to call
setAdapter(assignAdapter)
or reuse your existing assignAdapter and then call notifyDatasetChanged() on it.

Why cannot add new list in listView?

I have a listView and icon button in my Activity. When icon is clicked, it should go to Activity B and finally return Activity B value to A by adding a new list. But the problem now is I only can create one list. When it has another value return to A, it update the old list instead of add a new list.
I get the tutorial from here, the difference is I use startActivityForResult to return value from Activity B to A.
Please help me..I've been stuck at here for the whole day...
Activity A
int mClickedPosition; // add list
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addDetails:
View menuItemView = findViewById(R.id.addDetails);
PopupMenu po = new PopupMenu(this, menuItemView); //for drop-down menu
po.getMenuInflater().inflate(R.menu.popup_details, po.getMenu());
po.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplication(), "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
if ("Add Work Details".equals(item.getTitle())) {
mClickedPosition = -1;
Intent intent = new Intent(getApplication(), Add_Details_Information.class); // go to Details class
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
return true;
}
});
po.show(); //showing popup menu
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Add_Details_Information
if(requestCode==PROJECT_REQUEST_CODE)
{
ReceiveProject = data.getStringExtra("Project");
ReceiveDescription = data.getStringExtra("Description");
ReceiveProgress = data.getIntExtra("progress",0);
ReceiveTimeIn = data.getStringExtra("TimeIn");
ReceiveTimeOut = data.getStringExtra("TimeOut");
ArrayList<SearchResults> searchResults = GetSearchResults(ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
(new MyCustomBaseAdapter(this,searchResults)).notifyDataSetChanged();
listview.setAdapter(new MyCustomBaseAdapter(this,searchResults));
}
else if(requestCode==CAMERA_REQUEST_CODE)
{
}
}
private ArrayList<SearchResults> GetSearchResults(String p, String d,int pro, String i, String o) {
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1=new SearchResults();
sr1.setProject(" Project/Service/Training : " + p);
sr1.setDescription(" Description : " + d);
sr1.setProgress(" Progress : " + pro);
sr1.setTimeIn(" Time In : " + i);
sr1.setTimeOut(" Time Out : " + o);
if(mClickedPosition==-1)
{
results.add(sr1);
}
return results;
}
MyCustomBaseAdapter
public class MyCustomBaseAdapter extends BaseAdapter{ // for ListView in WorkDetailsTable
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtProject= (TextView) convertView.findViewById(R.id.ListProject);
holder.txtDescription = (TextView) convertView.findViewById(R.id.ListDescription);
holder.txtProgress = (TextView) convertView.findViewById(R.id.ListProgress);
holder.txtIn=(TextView)convertView.findViewById(R.id.ListTimeIn);
holder.txtOut=(TextView)convertView.findViewById(R.id.ListTimeOut);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtProject.setText(searchArrayList.get(position).getProject());
holder.txtDescription.setText(searchArrayList.get(position).getDescription());
holder.txtProgress.setText(searchArrayList.get(position).getProgress());
holder.txtIn.setText(searchArrayList.get(position).getTimeIn());
holder.txtOut.setText(searchArrayList.get(position).getTimeOut());
return convertView;
}
static class ViewHolder {
TextView txtProject;
TextView txtDescription;
TextView txtProgress;
TextView txtIn;
TextView txtOut;
}
}
Currently instead of adding new item in ListView, passing new object of Adapter to setAdapter which will show only latest added item in ListView instead of add in current Adapter.
Do it as:
1. Create a method in MyCustomBaseAdapter class for adding new item in data-source which size is returned from getCount method:
public void addNewItem(String ReceiveProject,String ReceiveDescription,...){
// add ReceiveProject,ReceiveDescription
// in ArrayList which using in Adapter
SearchResults objSearchResults=new SearchResults();
objSearchResults.setProject(ReceiveProject);
....
searchArrayList.add(objSearchResults);
this. notifyDataSetChanged();
}
2. Use same object of MyCustomBaseAdapter class which passed first time in setAdapter method to call addNewItem method:
if(requestCode==PROJECT_REQUEST_CODE)
{
MyCustomBaseAdapter objMyCustomBaseAdapter=
(MyCustomBaseAdapter)listview.getAdapter();
}

How to remove item from list without deleting it in Android?

I am new to Android and My question is I have created a method "Mark As Completed" when I am clicking on it, it set true value into the database. What I want now is when I click on mark as completed that item deleted from the list but not from the database. Is it possible?
EDIT:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
addTasklist = (EditText)findViewById(R.id.addTasklist);
taskList_completed = (CheckBox)findViewById(R.id.completedflag);
Button ok = (Button)findViewById(R.id.add);
ok.setOnClickListener(this);
list();
}
public void list(){
db = new TodoTask_Database(getApplicationContext());
list_tasklistname = (ListView)findViewById(R.id.listview);
list = db.getAllTaskList();
adapter = new CustomAdapter(Main_Activity.this, R.layout.tasklist_row, list);
list_tasklistname.setAdapter(adapter);
db.close();
adapter.notifyDataSetChanged();
registerForContextMenu(list_tasklistname);
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Position = info.position;
switch (item.getItemId()) {
case R.id.MarkAsCompleted:
db = new TodoTask_Database(getApplicationContext());
task = adapter.getItem(Position);
int taskList_Id = task.getTaskListId();
// here is database method which is setting item value true when mark as completed on long click listener is pressed.
db.Complete_TaskList(taskList_Id);
break;
}
return super.onOptionsItemSelected(item);
}
My Custom list Adapter:
public class CustomAdapter extends ArrayAdapter<Task> {
private List<Task> dataitem;
private Activity activity;
TodoTask_Database db;
public CustomAdapter(Activity a, int textViewResourceId, List<Task> items) {
super(a, textViewResourceId, items);
this.dataitem = items;
this.activity = a;
}
public static class ViewHolder{
public TextView tasklistTitle;
public TextView createdDate;
public CheckBox completedflag;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.tasklist_row, null);
holder = new ViewHolder();
holder.tasklistTitle = (TextView) v.findViewById(R.id.tasklistTitle);
holder.createdDate = (TextView) v.findViewById(R.id.createdDate);
holder.completedflag = (CheckBox) v.findViewById(R.id.completedflag);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final Task custom = dataitem.get(position);
if (custom != null) {
holder.tasklistTitle.setText(custom.getTaskListTitle());
holder.createdDate.setText(custom.getTaskListCreated());
holder.completedflag.setText(custom.getTaskListCompletedFlag());
}
return v;
}
public synchronized void refresAdapter(List<Task> dataitems) {
dataitem.clear();
dataitem.addAll(dataitems);
notifyDataSetChanged();
}
}
Add
list.remove(Position); // Remove item from List
adapter.notifyDataSetChanged(); // Notify adapter
at case R.id.MarkAsCompleted. Like below
case R.id.MarkAsCompleted:
db = new TodoTask_Database(getApplicationContext());
task = adapter.getItem(Position);
int taskList_Id = task.getTaskListId();
// here is database method which is setting item value true when mark as completed on long click listener is pressed.
db.Complete_TaskList(taskList_Id);
// Remove from List
list.remove(Position); // Added here
adapter.notifyDataSetChanged(); // Added here
break;
this will remove the item form ListView.

Categories

Resources