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();
Related
I have an a gridView that has items, each item has a name and quantity. When I click the item in the gridView, I would like to add the item and the quantity to a dynamic list view that is in the same activity. If I click on the item a several times, the items quantity in the dynamic listView should be increased (no duplicate items are allowed.) This is my current gridView, I have removed the code that adds and a previous listView that failed and I am having it just toast for now:
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listItem;
private ArrayList<Integer> listPicture;
private Activity activity;
public GridviewAdapter(Activity activity, ArrayList<String> listItem, ArrayList<Integer> listPicture) {
super();
this.listItem = listItem;
this.listPicture = listPicture;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView itemPicture;
public TextView itemName;
public TextView itemPrice;
public TextView itemStock;
public TextView itemAvailability;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.item_grid_row,
null);
view.itemName = (TextView)
convertView.findViewById(R.id.itemName);
view.itemPrice = (TextView)
convertView.findViewById(R.id.itemPrice);
view.itemStock = (TextView)
convertView.findViewById(R.id.itemStock);
view.itemAvailability = (TextView)
convertView.findViewById(R.id.itemAvailability);
view.itemPicture = (ImageView)
convertView.findViewById(R.id.itemPicture);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.itemName.setText(listItem.get(position));
// view.itemPicture.setImageDrawable(listItem.get(position));
return convertView;
}
}
this is the code for the checkout fragment where the gridView is clicked.
public class CheckoutFragment extends Fragment {
private CheckoutViewModel checkoutViewModel;
private EditText editText1;
private GridviewAdapter mAdapter;
private ArrayList<String> listItem;
private ArrayList<Integer> listPicture;
private GridView gridView;
DBHelper db;
LinearLayout layout_total, layout_grid;
private Button sum;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_checkout,
container, false);
db = new DBHelper(getActivity());
Display display =
getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
editText1 = (EditText)root.findViewById(R.id.editText1);
editText1.setHeight(height/12);
editText1.setShowSoftInputOnFocus(false);
editText1.setFocusable(false);
editText1.setTextColor(Color.parseColor("#FFFFFF"));
editText1.setHintTextColor(Color.parseColor("#FFFFFF"));
editText1.getBackground().setColorFilter(Color.parseColor("#008577"),
PorterDuff.Mode.SRC_ATOP);
editText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart = new Intent(getActivity(),
CartActivity.class);
startActivity(cart);
}
});
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(getActivity(),db.getAll(),
listPicture);
// Set custom adapter to gridview
gridView = (GridView)root.findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new
AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
position,
long arg3) {
//this is where the grid is clicked and items added to dynamic listView
Toast.makeText(getActivity(),
mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
return root;
}
public void prepareList() {
// listItem = new ArrayList<String>();
db = new DBHelper(getActivity());
List<Item> listItem = new ArrayList<>();
listItem = db.getAllItems(db.ITEMS_TABLE_NAME);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.action_add_customer:
//startActivity(getActivity(),
NewCustomerActivity.class);
Intent newCustomer = new Intent(getActivity(),
NewCustomerActivity.class);
startActivity(newCustomer);
return true;
/* case R.id.action_add_customer:
return true;*/
default:
return super.onOptionsItemSelected(item);
}
}
}
You need to explain the situation a bit better. For now i assume your problem is that the items are duplicating the second list instead of appending the count. For this there is no
one line solution. What you need to do is once an item is selected in the grid, search if it exists in the second list. In that case update the quantity, otherwise add it to the list. Since your second list is based on a Table , you have to execute 2 queries. One to identify if the item already exists (Select Query) and other to change the value (Insert or Update Query). If i misunderstood please correct me so that i can help you better.
Why don't you return the model class in your GridView getItem(..) method instead of 'String' it should work like this
public class GridviewAdapter extends BaseAdapter
{
ArrayList<GridModel> gridItems;
//Constructor
public GridviewAdapter(Activity activity, ArrayList<GridModel> gridItems) {
super();
this.gridItems = gridItems;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return griditems.size();
}
#Override
public GridModel getItem(int position) {
// TODO Auto-generated method stub
return gridItems.get(position);
}
//...add your getView...
}
//GridModel Should be Like So..
class GridModel {
public String itemPicture;
public String itemName;
public String itemPrice;
public String itemStock;
public String itemAvailability;
//or use private variables with getter-setter methods
}
I have three fragments, the second and the third one, have a listView in their respective layout.
initially, the listView of both "second and third Frament", is populated with the same items. i other words, initially the the listView of
the second fragment and the third one, contain the following where CB: is checkBox and IV: is ImageView and t is: textview, and SaveButton is a buton
t1........CB.......IV
t2........CB.......IV
t3........CB.......IV
t4........CB.......IV
t5........CB.......IV
t6........CB.......IV
SaveButton
what i am trying to do is, while i am in the second fragment and selected an item(s) from the listView "using the checkbox" and clicked "Save" button, then, that item i selected, should be deleted from the listView in the third Fragment.
to achieve this,in getview(), i checked if the the checkBox is checked from the the listView of the second fragment, and if it is checked, i add the checked items
to a list. as shown in getView():
Second Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, ECO_FRAG_ID);
this.listView.setAdapter(adapter);
}
Third Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
BaseAdapter:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater layoutinflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutinflater.inflate(R.layout.list_items_layout, null);
}
if (this.checkedItemsList1 == null) {
this.checkedItemsList1 = new ArrayList<String>();
}
if (this.checkedItemsList2 == null) {
this.checkedItemsList2 = new ArrayList<String>();
}
final TextView tv = (TextView) convertView.findViewById(R.id.tvlist_topic);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cbList_hook);
final ImageView iv = (ImageView) convertView.findViewById(R.id.ivList_delete);
tv.setText(this.topicsList.get(position));
if (cb.isChecked() && (this.id == 1) ) {
this.checkedItemsList1.add(this.topicsList.get(position));
this.setCheckedItemsList1(this.checkedItemsList1);
}
if (cb.isChecked() && (this.id == 2) ) {
this.checkedItemsList2.add(this.topicsList.get(position));
this.setCheckedItemsList2(this.checkedItemsList2);
}
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (cb.isChecked())
cb.setChecked(false);
topicsList.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
And i created an interface, which is initialised in onAttach() and called when i click the savebuton in the secondFragment as folows:
private OnClickListener btnSaveListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Save to SQLite", Toast.LENGTH_SHORT).show();
Log.d(TAG, "size: " + adapter.getCheckedItemsList1().size());
iCSC.onCheckedStateChanged(adapter.checkedItemsList1, ECO_FRAG_ID);
}
};
this inerface, the mainActivity implements it, and in the implemntation of the interface, i pass the list f the checked items from the second Fragment to the third
Fragment through a public method in the third fragmet that updates the list and then assign the list to the adapter, as follows:
#Override
public void onCheckedStateChanged(ArrayList<String> list, int id) {
// TODO Auto-generated method stub
switch (id) {
case 1:
((Logger_Settings_Frag) this.fragList.get(2)).updateTopicList(list);
break;
case 2:
break;
}
}
**updateTopicList in the third fragment**
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
updateTopicList in the third fragment
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
when i run that code, in the saveButton listener of the second fragment, the log.d message displays that the size of the list that should contain the items that was checked, is zero size?!
please have a look at the code and let me know what i am missing?
try this: Its a sample Project OneActivity with two Fragments:
public ArrayList myBeansList_frgnt1;
public ArrayList myBeansList_frgnt2;
by clicking the save button iterate the myBeansList_frgnt1 and checking the condition that any item is selected or not. if item is selected i am adding that item to myBeansList_frgnt2 .showing in fragment2.
MainActivity:
public class MainActivity extends FragmentActivity {
private FragmentManager mFragmentManager;
private MyFragment1 myFragment1;
public ArrayList<MyBean> myBeansList_frgnt1;
public ArrayList<MyBean> myBeansList_frgnt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
myBeansList_frgnt1 = new ArrayList<MyBean>();
myBeansList_frgnt2 = new ArrayList<MyBean>();
}
#Override
protected void onResume() {
super.onResume();
myFragment1 = new MyFragment1();
FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
mTransaction.replace(R.id.framid, myFragment1, "applock").commit();
}
}
MyBaseAdpter: maintaining the states in the MyBean object
#Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null);
holder.mTextView = (TextView) view.findViewById(R.id.textView1);
holder.mBox = (CheckBox) view.findViewById(R.id.checkBox1);
holder.mImageView = (ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final MyBean mBean = mBeansList.get(position);
holder.mBox.setOnCheckedChangeListener(null);
holder.mBox.setChecked(mBean.isChecked());
holder.mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mBean.setChecked(true);
} else {
mBean.setChecked(false);
}
}
});
// setting text and image
holder.mTextView.setText(mBean.getmName());
holder.mImageView.setImageResource(mBean.getmImgId());
return view;
}
private class ViewHolder {
TextView mTextView;
CheckBox mBox;
ImageView mImageView;
}
Fragment1:
public class MyFragment1 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
private Button mButton;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
mButton = (Button) view.findViewById(R.id.bttnid);
return view;
}
#Override
public void onResume() {
super.onResume();
final MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt1, getActivity());
mListView.setAdapter(myBaseAdpter);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int size = mActivity.myBeansList_frgnt1.size();
for (int i = 0; i < size; i++) {
MyBean mMyBean = mActivity.myBeansList_frgnt1.get(i);
if (mMyBean.isChecked()) {
mActivity.myBeansList_frgnt2.add(mMyBean);
}
}
}
});
}
}
Fragment2:
public class MyFragment2 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
return view;
}
#Override
public void onResume() {
super.onResume();
MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt2, getActivity());
mListView.setAdapter(myBaseAdpter);
}
}
MyBean:
public class MyBean {
private String mName;
private int mImgId;
private boolean isChecked;
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public int getmImgId() {
return mImgId;
}
public void setmImgId(int mImgId) {
this.mImgId = mImgId;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public MyBean() {
super();
// TODO Auto-generated constructor stub
}
}
This is my custom list adapter. I want to update the values in table using the update ImageButton in the list. On clicking it, the old values should be shown in a new activity and then the edited value must be stored in the database. However, I am unable to pass an intent inside the onClick() method.
Please suggest me a solution
public class CustomListAdapter extends BaseAdapter implements ListAdapter
{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
OnItemSelectedListener onItemSelectedListener;
public int pos;
String pass,pass2,edit,epass;
public CustomListAdapter(List list, Context context) {
this.list = (ArrayList<String>) list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
//pass2 = list.toString();
return list.get(pos);
}
//#Override
//public Long getItemId(int pos) {
//
// //just return 0 if your list items do not have an Id variable.
//}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_custom_list, null);
}
//Handle TextView and display string from your list
final TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
ImageButton editBtn = (ImageButton)view.findViewById(R.id.edit_btn);
//Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position);
pass = listItemText.getText().toString();
notifyDataSetChanged();
pass2 = pass.substring(0,pass.indexOf(' '));
System.out.println(pass2);
Moneydb.delete(pass2);
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
edit=listItemText.getText().toString();
epass = listItemText.getText().toString();
edit = epass.substring(0,epass.indexOf(' '));
Moneydb.edit(edit);
}
});
return view;
}
protected Context getContext() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return list.get(position).getId();
return 0;
}
public void clear() {
//CustomListAdapter collection = null;
// TODO Auto-generated method stub
list.clear();
notifyDataSetChanged();
}
I suggest you to assign and ContextMenu to your list view with two MenuItem, Edit and Delete and write associated code outside of adapter
or you can start Activity by :
Intent new_intent = new Intent(v.getRootView().getContext(),edit_activity.class);
new_intent.putExtra("Key","Value");
v.getRootView().getContext().startActivity(new_intent);
i think the first method is best ;)
I use https://github.com/bulletnoid/StaggeredGridView this library for make a pinterest style layout and use pulltorefresh on this layout. Also ı have a slide menu for choose different category and according to category which is user choose, refresh and refill the staggred again.
Pulltorefresh is work fine.
if user top of the layout and choose a category on slide menu it's work correctly. But if user bottom of the layout and choose a category on slide menu it's work not correctly .
the scenario, top of layout and select category on slidemenu and refill staggered layout. it's work correctly
the scenario, bottom of layout and select category on slidemenu and refill staggered layout. it's not work correctly
-->listviewAdapter
public void onItemClick(AdapterView<?> parent, View view, int position,
long arg3) {
// TODO Auto-generated method stub
switch (parent.getId()) {
case R.id.listView_sliding_menu:
smenu.toggle();
slidingMenuControl = true;
String categoryId = ((TextView) view.findViewById(R.id.categoryID))
.getText().toString();
parameters[0] = categoryId;
Toast.makeText(getApplicationContext(), categoryId,
Toast.LENGTH_LONG).show();
new PARSEJSONCATEGORYCONTENT().execute(parameters);
break;
default:
break;
}
}
-->parser
private class PARSEJSONCATEGORYCONTENT extends
AsyncTask<String[], Void, ArrayList<Utils>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
processDialoge();
}
protected ArrayList<Utils> doInBackground(String[]... params) {
String catId = params[0][0];
String startCount = params[0][5];
String count = params[0][6];
String urlCatContent = "http://212.58.8.109/webservice/api/content/cat/";
jArray = jsonParser.getJSONFromUrltoCategoryContent(urlCatContent,
Token, tokenValue, catId, startCount, count);
if (utilsArray == null) {
utilsArray = new ArrayList<Utils>();
} else if (slidingMenuControl == true) {
utilsArray.clear();
} else if (contentItemSelection != null) {
utilsArray.clear();
}
try {
// looping through All Contacts
for (int i = 0; i < jArray.length(); i++) {
JSONObject k = jArray.getJSONObject(i);
utils = new Utils();
// Storing each json item in variable
utils.imageUrl = k.getString("ipad_URL");
utils.imageWidth = k.getInt("ipad_width");
utils.imageHeight = k.getInt("ipad_height");
utils.categoryHeader = k.getString("contentHeader");
utils.contentDesc = k.getString("contentDesc");
utils.categoryContentId = k.getInt("id");
utils.contentTxt = k.getString("contentTxt");
Log.d("ipad_URL", utils.imageUrl);
utilsArray.add(utils);
}
String arrayLenght = Integer.toString(utilsArray.size());
Log.d("arrayLenght", arrayLenght);
} catch (JSONException e) {
e.printStackTrace();
}
return utilsArray;
}
protected void onPostExecute(ArrayList<Utils> utilsArray) {
staggeredAdapter.getMoreItemm(utilsArray);
// staggeredAdapter.setRefreshListener(false);
super.onPostExecute(utilsArray);
slidingMenuControl = false;
dialog.cancel();
}
}
-->BaseAdapter.java
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressLint("NewApi")
public class StaggeredAdapter extends BaseAdapter implements OnClickListener {
Typeface tf;
boolean refreshListener = false;
Utils utils;
private Context mContext;
private Application mAppContext;
private ArrayList<Utils> mUtilsArraylist = new ArrayList<Utils>();
public StaggeredAdapter(Context context, Application application) {
mContext = context;
mAppContext = application;
tf = Typeface.createFromAsset(mContext.getAssets(),
"font/Klavika-Medium.otf");
notifyDataSetChanged();
}
public void getMoreItemm(ArrayList<Utils> arrayList) {
mUtilsArraylist.clear();
mUtilsArraylist.addAll(arrayList);
this.notifyDataSetChanged();
}
public int getCount() {
return mUtilsArraylist == null ? 0 : mUtilsArraylist.size();
}
#Override
public Object getItem(int position) {
return mUtilsArraylist.get(position);
}
#Override
public long getItemId(int position) {
return mUtilsArraylist.indexOf(getItem(position));
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
utils = mUtilsArraylist.get(position);
if (convertView == null) {
Holder holder = new Holder();
view = View.inflate(mContext, R.layout.staggered_item, null);
holder.imgUrl_content = (STGVImageView) view
.findViewById(R.id.imgUrl_content);
holder.tv_info = (TextView) view.findViewById(R.id.contentHeader);
holder.tv_info.setTypeface(tf);
holder.tv_info2 = (TextView) view.findViewById(R.id.contentDesc);
holder.tv_info2.setTypeface(tf);
view.setTag(holder);
} else {
return convertView;
}
final Holder holder = (Holder) view.getTag();
holder.imgUrl_content.mHeight = utils.imageHeight;
holder.imgUrl_content.mWidth = utils.imageWidth;
holder.imgUrl_content.setOnClickListener(this);
ImageLoader imgLoader = new ImageLoader(mAppContext);
imgLoader.DisplayImage(utils.imageUrl, holder.imgUrl_content);
holder.tv_info.setText(utils.categoryHeader);
holder.tv_info.setOnClickListener(this);
holder.tv_info2.setText(utils.contentDesc);
holder.tv_info2.setOnClickListener(this);
return view;
}
class Holder {
public STGVImageView imgUrl_content;
public TextView tv_info;
public TextView tv_info2;
}
public boolean isRefreshListener() {
return refreshListener;
}
public void setRefreshListener(boolean refreshListener) {
this.refreshListener = refreshListener;
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.imgUrl_content:
sendDataItemContentActivity();
break;
case R.id.contentHeader:
sendDataItemContentActivity();
break;
case R.id.contentDesc:
sendDataItemContentActivity();
break;
default:
break;
}
}
public void sendDataItemContentActivity() {
Intent intent = new Intent(mContext, ItemContent.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("contentTxt", utils.contentTxt);
intent.putExtra("contentHeader", utils.categoryHeader);
intent.putExtra("contentİmageUrl", utils.imageUrl);
intent.putExtra("contentCategoryName", utils.categoryName);
Bundle animBundle = ActivityOptions.makeCustomAnimation(mContext,
R.anim.anim, R.anim.anim2).toBundle();
mContext.startActivity(intent, animBundle);
}
}
I guess i had a same problem with using the same pinterest style library with you. i solve my problem by put this
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter = new SearchSTGVAdapter(getActivity(), adsList, (Fragment)this);
ptrstgv.setAdapter(mAdapter);
}
which previously I put it in the onCreate method
For your information, I am implement this pinterest style in a view pager not a sliding menu
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.