How to restore fragment state onTouchEvent - android

I have a fragment (ItemFragment) with a bunch of EditText, a spinner and datepicker. The user input will be saved in SQL database. The user input then displayed in a list fragment (ListFragment) using RecyclerView. When a user click on the item in the list, it will go to ItemFragment and restore the user input. I added onSaveInstanceState in ItemFragment. I'm pretty new to Android so please bear with me. So how do I restore ItemFragment state during RecylerView's onTouchEvent?
ItemFragment.java (not sure if this is the correct way to do this?)
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("unit", unit);
outState.putString("date", date);
outState.putString("note", Note);
}
ListFragment.java
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildLayoutPosition(child);
Item selectedItem = mItems.get(position);
//How do I restore ItemFragment here???
return true;
}
return false;
}
Edited added Item.java and full code of ItemFragment.java
Item.java
public class Item {
private Long id;
private String title;
private String quantity;
private String unit;
private String date;
private String Note;
public String getNote() {
return Note;
}
public void setNote(String Note) {
this.Note = Note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public static Item getItemfromCursor(Cursor cursor){
Item item = new Item();
item.setId(cursor.getLong(cursor.getColumnIndex(Constants.COLUMN_ID)));
item.setTitle(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_TITLE)));
item.setQuantity(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_QUANTITY)));
item.setUnit(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_UNIT)));
item.setNote(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_NOTE)));
item.setDate(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_DATE)));
return item;
}
}
ItemFragment.java
public class ItemFragment extends DialogFragment {
private View mRootView;
private Item currentItem = null;
private Toolbar mToolbar;
private String date;
private String Note;
private String title;
private String quantity;
private TextView dateText;
private TextView unitError;
private EditText itemEditText;
private EditText quantityEditText;
private EditText noteEditText;
private Spinner remSpinner;
private Spinner spinner;
private String unit;
private String reminder;
private int spinnerCount=0;
private int spinnerInitializedCount=0;
private int remSpinnerCount=0;
private int remSpinnerInitializedCount=0;
public ItemFragment() {
}
//create an instance of the fragment
public static ItemFragment newInstance(long id) {
ItemFragment fragment = new ItemFragment();
if (id > 0) {
Bundle bundle = new Bundle();
bundle.putLong("id", id);
fragment.setArguments(bundle);
}
return fragment;
}
//get id of an item
public void getCurrentItem() {
Bundle args = getArguments();
if (args != null && args.containsKey("id")) {
long id = args.getLong("id", 0);
if (id > 0) {
currentItem = ItemManager.newInstance(getActivity()).getItem(id);
}
}
}
//notify Activity that the fragment wants to place an item in the menu
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getCurrentItem();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add_item, container, false);
itemEditText=(EditText)mRootView.findViewById((R.id.add_item));
quantityEditText=(EditText)mRootView.findViewById(R.id.amount);
unitError = (TextView)mRootView.findViewById(R.id.unit_error);
noteEditText = (EditText)mRootView.findViewById(R.id.add_notes);
dateText = (TextView)mRootView.findViewById(R.id.date_selected);
//unit spinner code here
//reminder spinner here
spinner.setOnItemSelectedListener(spinnerListener);
remSpinner.setOnItemSelectedListener(spinnerListener);
spinnerCount=1;
remSpinnerCount=1;
return mRootView;
}
//spinner listener
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
if(spinnerInitializedCount<spinnerCount){
spinnerInitializedCount++;
} else {
//get selected unit
unit = parent.getItemAtPosition(position).toString();
}
break;
case R.id.reminder_list:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
//get selected reminder
reminder = parent.getItemAtPosition(position).toString();
break;
}
}}
public void onNothingSelected(AdapterView<?> parent) {
}
};
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_item, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.delete:
if(currentItem != null){
promptForDelete();
}
else{
makeToast("Cannot delete item that has not been saved");
}
break;
case R.id.save:
if(saveItem()){
makeToast(currentItem != null ? "Item updated" : "Item saved");
}
break;
}
return super.onOptionsItemSelected(item);
}
private void makeToast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private boolean saveItem(){
Note = noteEditText.getText().toString();
date = dateText.getText().toString();
title = itemEditText.getText().toString();
if(TextUtils.isEmpty(title)){
itemEditText.setError("Item is required");
return false;
}
quantity = quantityEditText.getText().toString();
if(TextUtils.isEmpty(quantity)){
quantityEditText.setError("Quantity is required");
return false;
}
if(unit.equals("None")){
unitError = (TextView)spinner.getSelectedView();
unitError.setError("");
unitError.setTextColor(Color.RED);
unitError.setTextSize(R.dimen.text_size_normal);
unitError.setText("Select a unit!");
return false;
}
if(currentItem != null){
currentItem.setTitle(title);
currentItem.setQuantity(quantity);
currentItem.setUnit(unit);
currentItem.setDate(date);
currentItem.setNote(Note);
ItemManager.newInstance(getActivity()).update(currentItem);
}
else {
Item item = new Item();
item.setTitle(title);
item.setQuantity(quantity);
item.setUnit(unit);
item.setDate(date);
item.setNote(Note);
ItemManager.newInstance(getActivity()).create(item);
}
return true;
}
private void populateFields(){
itemEditText.setText(currentItem.getTitle());
quantityEditText.setText(currentItem.getQuantity());
noteEditText.setText(currentItem.getNote());
dateText.setText(currentItem.getDate());
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("selunit", unit);
outState.putString("seldate", date);
outState.putString("note", Note);
}
public void promptForDelete(){
final String itemToBeDeleted = currentItem.getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete" + itemToBeDeleted + "?");
alertDialog.setMessage("Are you sure you want to delete " + itemToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ItemManager.newInstance(getActivity()).delete(currentItem);
makeToast(itemToBeDeleted + "deleted");
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
EDITED - added ItemListAdapter.java & ItemManager.java
ItemListAdapter.java
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder> {
private List<Item> mItems;
private Context mContext;
public ItemListAdapter(List<Item> items, Context context){
mItems = items;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(rowView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemx.setText(mItems.get(position).getTitle());
holder.quantity.setText(String.valueOf(mItems.get(position).getQuantity()));
holder.unit.setText(mItems.get(position).getUnit());
holder.note.setText(mItems.get(position).getNote());
holder.expDate.setText(mItems.get(position).getDate());
}
#Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView itemx;
public final TextView quantity;
public final TextView unit;
public final TextView note;
public final TextView expDate;
public ViewHolder(View itemView) {
super(itemView);
itemx = (TextView)itemView.findViewById(R.id.tv_item);
quantity = (TextView)itemView.findViewById(R.id.tv_quantity);
unit = (TextView)itemView.findViewById(R.id.tv_unit);
note = (TextView)itemView.findViewById(R.id.tv_note);
expDate = (TextView)itemView.findViewById(R.id.tv_exp_date);
}
}
public void promptForDelete(final int position){
String fieldToBeDeleted = mItems.get(position).getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Delete " + fieldToBeDeleted + " ?");
alertDialog.setMessage("Are you sure you want to delete the item " + fieldToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mItems.remove(position);
notifyItemRemoved(position);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
ItemManager.java
public class ItemManager{
private Context mContext;
private static ItemManager itemManagerInstance = null;
public static ItemManager newInstance(Context context){
if (itemManagerInstance == null){
itemManagerInstance = new ItemManager(context.getApplicationContext());
}
return itemManagerInstance;
}
private ItemManager(Context context){
this.mContext = context.getApplicationContext();
}
public long create(Item item){
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_TITLE, item.getTitle());
values.put(Constants.COLUMN_QUANTITY, item.getQuantity());
values.put(Constants.COLUMN_UNIT, item.getUnit());
values.put(Constants.COLUMN_EXPIRY_DATE, item.getDate());
values.put(Constants.COLUMN_NOTE, item.getNote());
Uri result = mContext.getContentResolver().insert(XContentProvider.ITEM_URI, values);
long id = Long.parseLong(result.getLastPathSegment());
return id;
}
public void update(Item item){
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_TITLE, item.getTitle());
values.put(Constants.COLUMN_QUANTITY, item.getQuantity());
values.put(Constants.COLUMN_UNIT, item.getUnit());
values.put(Constants.COLUMN_EXPIRY_DATE, item.getDate());
values.put(Constants.COLUMN_NOTE, item.getNote());
mContext.getContentResolver().update(XContentProvider.ITEM_URI, values, Constants.COLUMN_ID + " = " + item.getId(), null);
}
public void delete(Item item){
mContext.getContentResolver().delete(XContentProvider.ITEM_URI, Constants.COLUMN_ID + " = " + item.getId(), null);
}
public List<Item> getAllItems(){
List<Item> items = new ArrayList<Item>();
Cursor cursor = mContext.getContentResolver().query(XContentProvider.ITEM_URI, Constants.COLUMNS, null, null, null);
if (cursor != null){
cursor.moveToFirst();
while (!cursor.isAfterLast()){
items.add(Item.getItemfromCursor(cursor));
cursor.moveToNext();
}
cursor.close();
}
return items;
}
public Item getItem(Long id){
Item item;
Cursor cursor = mContext.getContentResolver().query(XContentProvider.ITEM_URI, Constants.COLUMNS, Constants.COLUMN_ID + " = " + id, null, null);
if (cursor != null){
cursor.moveToFirst();
item = Item.getItemfromCursor(cursor);
return item;
}
return null;
}
}

You probably need to use SharedPreferences or SQL database to save data .onSaveInstanceState is used for save state when fragment is possible to be destroyed.
Just pass id of item to ItemFragment and display data in it.
openFragment(new ItemFragment(item.getId()), "Add Item")
package com.airi.vcare;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class ItemFragment extends DialogFragment {
private View mRootView;
private Item currentItem = null;
private Toolbar mToolbar;
private String date;
private String Note;
private String title;
private String quantity;
private TextView dateText;
private TextView unitError;
private EditText itemEditText;
private EditText quantityEditText;
private EditText noteEditText;
private Spinner remSpinner;
private Spinner spinner;
private String unit;
private String reminder;
private int spinnerCount=0;
private int spinnerInitializedCount=0;
private int remSpinnerCount=0;
private int remSpinnerInitializedCount=0;
public ItemFragment() {
}
//create an instance of the fragment
public static ItemFragment newInstance(long id) {
ItemFragment fragment = new ItemFragment();
if (id > 0) {
Bundle bundle = new Bundle();
bundle.putLong("id", id);
fragment.setArguments(bundle);
}
return fragment;
}
//get id of an item
public void getCurrentItem() {
Bundle args = getArguments();
if (args != null && args.containsKey("id")) {
long id = args.getLong("id", 0);
if (id > 0) {
currentItem = ItemManager.newInstance(getActivity()).getItem(id);
}
}
}
//notify Activity that the fragment wants to place an item in the menu
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getCurrentItem();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add_item, container, false);
itemEditText=(EditText)mRootView.findViewById((R.id.add_item));
quantityEditText=(EditText)mRootView.findViewById(R.id.amount);
unitError = (TextView)mRootView.findViewById(R.id.unit_error);
noteEditText = (EditText)mRootView.findViewById(R.id.add_notes);
dateText = (TextView)mRootView.findViewById(R.id.date_selected);
//unit spinner code here
//reminder spinner here
spinner.setOnItemSelectedListener(spinnerListener);
remSpinner.setOnItemSelectedListener(spinnerListener);
spinnerCount=1;
remSpinnerCount=1;
//just display fields .
populateFields();
return mRootView;
}
//spinner listener
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
if(spinnerInitializedCount<spinnerCount){
spinnerInitializedCount++;
} else {
//get selected unit
unit = parent.getItemAtPosition(position).toString();
}
break;
case R.id.reminder_list:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
//get selected reminder
reminder = parent.getItemAtPosition(position).toString();
break;
}
}}
public void onNothingSelected(AdapterView<?> parent) {
}
};
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_item, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.delete:
if(currentItem != null){
promptForDelete();
}
else{
makeToast("Cannot delete item that has not been saved");
}
break;
case R.id.save:
if(saveItem()){
makeToast(currentItem != null ? "Item updated" : "Item saved");
}
break;
}
return super.onOptionsItemSelected(item);
}
private void makeToast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private boolean saveItem(){
Note = noteEditText.getText().toString();
date = dateText.getText().toString();
title = itemEditText.getText().toString();
if(TextUtils.isEmpty(title)){
itemEditText.setError("Item is required");
return false;
}
quantity = quantityEditText.getText().toString();
if(TextUtils.isEmpty(quantity)){
quantityEditText.setError("Quantity is required");
return false;
}
if(unit.equals("None")){
unitError = (TextView)spinner.getSelectedView();
unitError.setError("");
unitError.setTextColor(Color.RED);
unitError.setTextSize(R.dimen.text_size_normal);
unitError.setText("Select a unit!");
return false;
}
if(currentItem != null){
currentItem.setTitle(title);
currentItem.setQuantity(quantity);
currentItem.setUnit(unit);
currentItem.setDate(date);
currentItem.setNote(Note);
ItemManager.newInstance(getActivity()).update(currentItem);
}
else {
Item item = new Item();
item.setTitle(title);
item.setQuantity(quantity);
item.setUnit(unit);
item.setDate(date);
item.setNote(Note);
ItemManager.newInstance(getActivity()).create(item);
}
return true;
}
private void populateFields(){
itemEditText.setText(currentItem.getTitle());
quantityEditText.setText(currentItem.getQuantity());
noteEditText.setText(currentItem.getNote());
dateText.setText(currentItem.getDate());
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("selunit", unit);
outState.putString("seldate", date);
outState.putString("note", Note);
}
public void promptForDelete(){
final String itemToBeDeleted = currentItem.getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete" + itemToBeDeleted + "?");
alertDialog.setMessage("Are you sure you want to delete " + itemToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ItemManager.newInstance(getActivity()).delete(currentItem);
makeToast(itemToBeDeleted + "deleted");
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder> {
private List<Item> mItems;
private Context mContext;
public ItemListAdapter(List<Item> items, Context context){
mItems = items;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(rowView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemx.setText(mItems.get(position).getTitle());
holder.quantity.setText(String.valueOf(mItems.get(position).getQuantity()));
holder.unit.setText(mItems.get(position).getUnit());
holder.note.setText(mItems.get(position).getNote());
holder.expDate.setText(mItems.get(position).getDate());
holder.item.getParent().setOnClick(new OnClickListener(){
onclick(View view){
//todo here
openFragment(new ItemFragment(item.getId()), "Add Item")
}
})
}
#Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView itemx;
public final TextView quantity;
public final TextView unit;
public final TextView note;
public final TextView expDate;
public ViewHolder(View itemView) {
super(itemView);
itemx = (TextView)itemView.findViewById(R.id.tv_item);
quantity = (TextView)itemView.findViewById(R.id.tv_quantity);
unit = (TextView)itemView.findViewById(R.id.tv_unit);
note = (TextView)itemView.findViewById(R.id.tv_note);
expDate = (TextView)itemView.findViewById(R.id.tv_exp_date);
}
}
public void promptForDelete(final int position){
String fieldToBeDeleted = mItems.get(position).getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Delete " + fieldToBeDeleted + " ?");
alertDialog.setMessage("Are you sure you want to delete the item " + fieldToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mItems.remove(position);
notifyItemRemoved(position);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}

Related

How to call every object in adapter?

I have a list of array adapters that have the following layout which contains checkbox, textview increase, textview count, and textview decrease :
layout product adapter.
what the problem is how to call or implement clicklistener from ProdukActivity.java on each object that appears on the adapter. I just want to know how does it work with object in adapter so i can count the product price in every checkbox is checked.
Here is my adapter code :
public class ProductAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<ProductModel> productItems;
public ProductAdapter(Activity activity, List<ProductModel> productItems) {
this.activity = activity;
this.productItems = productItems;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int location) {
return productItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_produk, null);
CheckBox namaProduk = (CheckBox) convertView.findViewById(R.id.checkBox_productName);
TextView kurangProduk = (TextView) convertView.findViewById(R.id.decrease_product);
TextView hitungProduk = (TextView) convertView.findViewById(R.id.count_product);
TextView tambahProduk = (TextView) convertView.findViewById(R.id.increase_product);
TextView hargaProduk = (TextView) convertView.findViewById(R.id.product_price);
ProductModel produk = productItems.get(position);
namaProduk.setText(produk.getProduct_name());
hargaProduk.setText(produk.getProduct_price());
return convertView;
}
}
and here is my ProdukActivity.java :
public class ProdukLaundry extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
ActionBar actionBar;
ListView listProduk;
SwipeRefreshLayout swipeProduct;
List<ProductModel> productList = new ArrayList<ProductModel>();
ProductAdapter productAdapter;
int success;
AlertDialog.Builder dialog;
RadioButton radioReguler, radioExpress;
TextView tvTotal;
Button next;
String product_id, laundry_id, product_name, product_price, service_type;
private int offset = 0;
private static final String TAG = ProdukLaundry.class.getSimpleName();
private static String url_select = Server.URL + "selectproduk.php";
public static final String TAG_PRODUCT_ID = "product_id";
public static final String TAG_LAUNDRY_ID = "laundry_id";
public static final String TAG_PRODUCT_NAME = "product_name";
public static final String TAG_PRODUCT_PRICE = "product_price";
public static final String TAG_SERVICE_TYPE = "service_type";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
int countcheckBox = 0;
int totalCount = 0;
boolean regular = true;
boolean express = false;
boolean checkBox = false;
Transaction transaction;
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new ProductAdapter(ProdukLaundry.this, productList);
listProduk.setAdapter(productAdapter);
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRefresh() {
productList.clear();
productAdapter.notifyDataSetChanged();
callProduct();
}
public void onClick(View view){
switch (view.getId()){
case R.id.increase_product:
countcheckBox++;
changeCheckBox();
hitung();
break;
case R.id.decrease_product:
if (countcheckBox>0){
countcheckBox--;
changeCheckBox();
hitung();
}
break;
case R.id.button_next:
save();
break;
default:
break;
}
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio_regular:
if (checked) {
regular = true;
express = false;
hitung();
}
break;
case R.id.radio_express:
if (checked){
regular = false;
express = true;
hitung();
}
break;
}
}
public void changeCheckBox(){
tvTotal.setText(countcheckBox+"");
}
public void hitung(){
int totalCount = 0;
int expressCost = 20000;
int harga = Integer.parseInt(product_price);
if (checkBox){
if (express){
totalCount+=(harga+expressCost)*countcheckBox;
}else{
totalCount+=harga*countcheckBox;
}
}
this.totalCount = totalCount;
tvTotal.setText(this.totalCount+"");
}
private void save() {
if (tvTotal.getText().toString().equals("0")){
Toast.makeText(this, "Choose Service.",
Toast.LENGTH_SHORT).show();
return;
}
String transId = "variabel transaksi id";
String uid = "variabel produk id";
String type;
if (regular) {
type = "regular";
} else {
type = "express";
}
transaction = new Transaction(transId, uid, type);
if (checkBox) {
transaction.setCheckBox(String.valueOf(countcheckBox));
}
transaction.total = String.valueOf(totalCount);
/*Intent intent = new Intent(this, LocationActivity.class);
intent.putExtra("transaction", transaction);
startActivity(intent);*/
}
Add listener for every object like below, inside getView of adapter. And inside the listener, do your handling
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_produk, null);
final CheckBox namaProduk = (CheckBox) convertView.findViewById(R.id.checkBox_productName);
TextView kurangProduk = (TextView) convertView.findViewById(R.id.decrease_product);
TextView hitungProduk = (TextView) convertView.findViewById(R.id.count_product);
TextView tambahProduk = (TextView) convertView.findViewById(R.id.increase_product);
TextView hargaProduk = (TextView) convertView.findViewById(R.id.product_price);
ProductModel produk = productItems.get(position);
namaProduk.setText(produk.getProduct_name());
hargaProduk.setText(produk.getProduct_price());
namaProduk.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//check here
}
}
}
);
kurangProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
hitungProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
tambahProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
hargaProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
return convertView;
}

How to refresh the Recyclerview when Image is deleted?

In my app, I want to delete the images, which i have done, but every time I delete image, it doesn't refresh the recyclerView. But when I again open the folder then Recyclerview is refreshed..
I want to refresh Recyclerview when image is deleted
Here is my code for Deleting an image
#Override
protected void onExternalStoragePermissionGranted() {
super.onExternalStoragePermissionGranted();
storage = SimpleStorage.getExternalStorage();
checkForGalleryDirectories();
File galleryFiles = new File(path);
pathContainerView.removeAllViews();
pathContainerView.addView(createTitleView("Location: " + galleryFiles.getAbsolutePath()));
File[] files = galleryFiles.listFiles();
List<GalleryItem> galleryItems = new ArrayList<>();
String lastModifiedDate = "UNDEFINED";
SimpleDateFormat formatter = new SimpleDateFormat("E-MMM-yyyy");
if (files != null) {
this.adapter.clearGallery();
for (File file : files) {
if (file.isDirectory()) {
}
String formattedPicDate = formatter.format(lastMod);
if (lastModifiedDate != null && !lastModifiedDate.equals(formattedPicDate)) {
lastModifiedDate = formattedPicDate;
galleryItems.add(new Header(lastModifiedDate));
countgridsize++;
}
galleryItems.add(new Picture(file.getPath(), file.getName()));
}
}
}
this.adapter.setGalleryList(galleryItems);
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
final List<String> list = GalleryAdapter.list;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Toast.makeText(GalleryBrowserActivity.this, "Delete Successfully..", Toast.LENGTH_SHORT).show();
for (String fileNameStr : list) {
String[] parts = fileNameStr.split("/");
String part1 = parts[5]; // 004
String part2 = parts[6]; // 034556
storage.deleteFile(".AliRehman/" + part1, part2);
}
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(GalleryBrowserActivity.this);
builder.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return true;
My adapter Class
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context;
private final LayoutInflater layoutInflater;
private List<GalleryItem> galleryList = new ArrayList<>();
private OnItemClickListener mItemClickListener;
public static List<String> list;
public GalleryAdapter(Context context, LayoutInflater layoutInflater) {
this.context = context;
this.layoutInflater = layoutInflater;
}
public void setItemClickListener(OnItemClickListener listener) {
mItemClickListener = listener;
}
public void setGalleryList(List<GalleryItem> galleryList) {
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return this.galleryList.get(position).getItemType();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == GalleryItem.HEADER_TYPE) {
return new HeaderHolder(layoutInflater.inflate(R.layout.item_header, parent, false));
} else {
return new PictureHolder(layoutInflater.inflate(R.layout.item_picture, parent, false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
GalleryItem item = galleryList.get(position);
if(getItemViewType(position) == GalleryItem.HEADER_TYPE) {
bindHeaderHolder((HeaderHolder) holder, (Header) item);
}
else {
bindPictureHolder((PictureHolder) holder, (Picture) item);
}
}
private void bindPictureHolder(final PictureHolder holder, Picture picture) {
Glide.with(context).load(Uri.fromFile(new File(picture.getPath()))).into(holder.pictureThumbnail);
boolean itemselected=picture.getSelected();
if(itemselected)
{
Log.d("ViewVisiblePicture", String.valueOf(picture.getPath()));
holder.overlayView.setVisibility(View.VISIBLE);
}
else
holder.overlayView.setVisibility(View.GONE);
}
private void bindHeaderHolder(HeaderHolder holder, Header header) {
holder.headerTxt.setText(header.getName());
}
#Override
public int getItemCount() {
return this.galleryList.size();
}
public void clearGallery() {
this.galleryList.clear();
notifyDataSetChanged();
}
public class HeaderHolder extends RecyclerView.ViewHolder {
private TextView headerTxt;
public HeaderHolder(View itemView) {
super(itemView);
this.headerTxt = (TextView) itemView.findViewById(R.id.headerTxt);
}
}
public class PictureHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView pictureThumbnail;
public FrameLayout overlayView;
public PictureHolder pictureHolder;
private boolean[] thumbnailsselection;
public PictureHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
this.pictureThumbnail = (ImageView) itemView.findViewById(R.id.pictureThumbnail);
this.overlayView = (FrameLayout) itemView.findViewById(R.id.overlayView);
}
#Override
public boolean onLongClick(View view) {
list=new ArrayList<>();
if (mItemClickListener != null) {
mItemClickListener.onItemLongClick(getAdapterPosition());
this.overlayView.setVisibility(View.VISIBLE);
Picture model=(Picture) galleryList.get(getAdapterPosition());
//galleryList.get(getAdapterPosition());
model.setSelected(true);
list.add(model.getPath());
Log.d("Path1", model.getPath());
final int len = GalleryBrowserActivity.countgridsize;
int count = 0;
/* String selectImages = "";
for (int i = 0; i < len; i++) {
*//*if (pictureHolder..get(i).selection) {
count++;
selectImages = selectImages
+ pictureHolder.images.get(i).id + ",";
}*//*
this.overlayView.setVisibility(View.VISIBLE);
}
Log.d("Length", len+"");
if (count == 0) {
Toast.makeText(context,
"Please select at least one image",
Toast.LENGTH_LONG).show();
}*/
return true;
}
Log.d("hi","hello Image");
notifyDataSetChanged();
return false;
}
#Override
public void onClick(View v)
{
int position = getAdapterPosition();
Picture picture = (Picture) galleryList.get(position);
if(GalleryBrowserActivity.mActionMode!=null)
{
Log.d("Visiblilty","visible");
Picture model=(Picture) galleryList.get(getAdapterPosition());
if(model.getSelected()){
this.overlayView.setVisibility(View.GONE);
model.setSelected(false);
list.remove(model.getPath());
}else {
mItemClickListener.onItemClick(position, v, picture.getPath());
Toast.makeText(context, "visible" + picture.getPath(), Toast.LENGTH_LONG).show();
this.overlayView.setVisibility(View.VISIBLE);
model.setSelected(true);
list.add(model.getPath());
Log.d("Path2", model.getPath());
}
notifyDataSetChanged();
}
if (GalleryBrowserActivity.mActionMode==null) {
Log.d("Visible","invisible");
Toast.makeText(context,"invisible",Toast.LENGTH_LONG).show();
mItemClickListener.onItemClick(position, v, picture.getPath());
}
}
}
public interface OnItemClickListener
{
void onItemClick(int position, View v, String picturePath);
void onItemLongClick(int position);
}
}
I would suggest you to make below changes:
In GalleryAdapter :
From:
public static List<String> list;
To:
public static List< GalleryItem > list;
And add a function in your GalleryAdapter to remove items from your galleryList:
public void removeItem(GalleryItem item){
this.galleryList.remove(item);
notifyDataSetChanged();
}
And In PictureHolder:
#Override
public boolean onLongClick(View view) {
list=new ArrayList<>();
if (mItemClickListener != null) {
mItemClickListener.onItemLongClick(getAdapterPosition());
this.overlayView.setVisibility(View.VISIBLE);
GalleryItem model=(GalleryItem) galleryList.get(getAdapterPosition());
//galleryList.get(getAdapterPosition());
((Picture)model).setSelected(true);
list.add(model);
Log.d("Path1", ((Picture)model).getPath());
final int len = GalleryBrowserActivity.countgridsize;
int count = 0;
return true;
}
Log.d("hi","hello Image");
notifyDataSetChanged();
return false;
}
#Override
public void onClick(View v)
{
int position = getAdapterPosition();
GalleryItem picture = (GalleryItem) galleryList.get(position);
if(GalleryBrowserActivity.mActionMode!=null)
{
Log.d("Visiblilty","visible");
GalleryItem model=(GalleryItem) galleryList.get(getAdapterPosition());
if(model.getSelected()){
this.overlayView.setVisibility(View.GONE);
((Picture)model).setSelected(false);
list.remove(model);
}else {
mItemClickListener.onItemClick(position, v, picture.getPath());
Toast.makeText(context, "visible" + picture.getPath(), Toast.LENGTH_LONG).show();
this.overlayView.setVisibility(View.VISIBLE);
((Picture)model).setSelected(true);
list.add(model);
Log.d("Path2", model.getPath());
}
notifyDataSetChanged();
}
if (GalleryBrowserActivity.mActionMode==null) {
Log.d("Visible","invisible");
Toast.makeText(context,"invisible",Toast.LENGTH_LONG).show();
mItemClickListener.onItemClick(position, v, picture.getPath());
}
}
In the above code I am trying to update the list with selected GallryItem objects.
And While deleting item after the DialogInterface.BUTTON_POSITIVE is clicked, update the code like below:
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Toast.makeText(GalleryBrowserActivity.this, "Delete Successfully..", Toast.LENGTH_SHORT).show();
for (GalleryItem item : list) {
this.adapter.removeItem(item);
String fileNameStr = ((Picture)item).getPath();
String[] parts = fileNameStr.split("/");
String part1 = parts[5]; // 004
String part2 = parts[6]; // 034556
storage.deleteFile(".AliRehman/" + part1, part2);
}
break;
The above code will also update the galleryList inside adapter and notify the dataset change. Please let me know if you face any issue while implementing it.
you have to notify your adapter after you delete your image. like below.
arrayAdapter.notifyDataSetChanged();
in your example you have to write above line after you click Yes in your AlertDialog.
All you need to do is call notifyDataSetChanged() which will notify the RecyclerView to re-bin the views again, thereby deleting any item as necessary.
Just add a method in your adapter class,
mAdapter.notifyDataSetChanged();
If you know the position of the particular item which is getting deleted, then it is RECOMMENDED to use,
mAdapter.notifyItemChanged(position);
This will give you a nice animation effect while deleting the item.

How to remove an item in an SQL database? [duplicate]

This question already has answers here:
Deleting Row in SQLite in Android
(18 answers)
Closed 6 years ago.
I know there are lots of threads with more or less same topic but none of them covers my situation:
I have delete button that delete one item in a listView but when you close the app and reopen it the items reappears. I don't know how to fix this .
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final int DATABASE_VERSION = 1;
public static final String ITEMS_TABLE = "items";
private static DatabaseHelper instance = null;
public static DatabaseHelper getInstance(Context context) {
if(instance == null) {
instance = new DatabaseHelper(context);
}
return instance;
}
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE " + ITEMS_TABLE + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"description TEXT NOT NULL, " +
"completed INTEGER NOT NULL DEFAULT 0)";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
The button works fine but it does not delete permently I don't know if it is the code or if it is where I am placing it in my MainActivity if someone would please tell that would much appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "ToDoApp";
private ToDoListManager listManager;
private ToDoItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
adapter = new ToDoItemAdapter(
this,
listManager.getList()
);
todoList.setAdapter(adapter);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
adapter.swapItems(listManager.getList());
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
private LayoutInflater inflater;
public ToDoItemAdapter(
Context context,
List<ToDoItem> items
) {
super(context, -1, items);
this.context = context;
this.items = items;
this.inflater = LayoutInflater.from(context);
}
public void swapItems(List<ToDoItem> items) {
this.items = items;
notifyDataSetChanged();
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ItemViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
holder = new ItemViewHolder();
holder.itemDescription = (TextView) convertView.findViewById(R.id.item);
holder.itemState = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
}else {
holder = (ItemViewHolder) convertView.getTag();
}
holder.itemDescription.setText(items.get(position).getDescription());
holder.itemState.setChecked(items.get(position).isComplete());
holder.itemState.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) holder.itemState.getTag();
item.toggleComplete();
listManager.updateItem(item);
notifyDataSetChanged();
}
});
ImageButton deleteButton = (ImageButton) convertView.findViewById(R.id.delete_Button);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.remove(items.get(position));
notifyDataSetChanged();
}
});
holder.itemState.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ToDoItem item = (ToDoItem) holder.itemState.getTag();
item.toggleComplete();
listManager.updateItem(item);
notifyDataSetChanged();
}
});
return convertView;
}
}
public static class ItemViewHolder{
public TextView itemDescription;
public CheckBox itemState;
}
}
ToDoListManager.java
public class ToDoListManager {
private DatabaseHelper dbHelper;
public ToDoListManager(Context context) {
dbHelper = DatabaseHelper.getInstance(context);
}
public List<ToDoItem> getList() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM " + DatabaseHelper.ITEMS_TABLE,
null
);
List<ToDoItem> items = new ArrayList<>();
if(cursor.moveToFirst()) {
while(!cursor.isAfterLast()) {
ToDoItem item = new ToDoItem(
cursor.getString(cursor.getColumnIndex("description")),
cursor.getInt(cursor.getColumnIndex("completed")) != 0,
cursor.getLong(cursor.getColumnIndex("_id"))
);
items.add(item);
cursor.moveToNext();
}
}
cursor.close();
return items;
}
public void addItem(ToDoItem item) {
ContentValues newItem = new ContentValues();
newItem.put("description", item.getDescription());
newItem.put("completed", item.isComplete());
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.insert(DatabaseHelper.ITEMS_TABLE, null, newItem);
}
public void updateItem(ToDoItem item) {
ContentValues editItem = new ContentValues();
editItem.put("description", item.getDescription());
editItem.put("completed", item.isComplete());
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] args = new String[] { String.valueOf(item.getId()) };
db.update(DatabaseHelper.ITEMS_TABLE, editItem, "_id=?", args);
}
}
ToDoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
private long id;
public ToDoItem(String description, boolean isComplete) {
this(description, isComplete, -1);
}
public ToDoItem(String description,boolean isComplete,long id) {
this.description = description;
this.isComplete = isComplete;
this.id = id;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
public long getId() {return id;}
#Override
public String toString() {
return getDescription();
}
}
you just remove items in your adapter class that causes the item delete from the current listView. but you have not any function in your ToDoListManager.java that remove items from your database. deleting from a listView does not affect to your database items.
you can add this function to your ToDoListManager.java class
public void deleteItem(long itemId) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(DatabaseHelper.ITEMS_TABLE, "_id = ?",
new String[] { String.valueOf(itemId) });
}
and call it from your delete button's onClick, like this
ImageButton deleteButton = (ImageButton) convertView.findViewById(R.id.delete_Button);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long itemId = items.get(position).getId();
items.remove(items.get(position));
listManager.deleteItem(itemId);
notifyDataSetChanged();
}
});
Since you are fetching the data from data base and displaying it in listview,you need to delete the row from database too. make a method in you database adapter that looks some thing like this:
public boolean deleteItem(Long id) {
return Db.delete(DATABASE_TABLE,"_id="+id,null) > 0;
}
then on list view item delete,simply call this method and pass the row id as argument.

How to wire up a delete button to delete one item on a listview?

I know there are lots of threads with more or less same topic but none of them covers my situation:
I am trying to get my delete button to delete one row on the list view and the delete button appear in each row I got this part to work but I can't get it to work in my Main Activity. The code keeps breaking every time I put this part in my code:
ImageButton removeButton = (ImageButton) findViewById(R.id.btnDel);
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRemoveButtonClick();
}
private void onRemoveButtonClick() {
ToDoItem item = (ToDoItem) v.getTag();
notifyDataSetChanged();
}
my MainActivity works fine without this bit of code. I don't know if it is the code or if it is where I am placing it in my MainActivity if someone would please tell that would much appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(this, listManager.getList());
todoList.setAdapter(adapter);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Add item to list
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
Log.i(LOG_TAG, input.getText().toString());
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int Which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(Context context, List<ToDoItem> items){
super(context,-1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
textView.setText(items.get(position).getDescription());
checkBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
ToDoListManager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if (json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit =savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
ToDoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem (String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return description;
}
}
enter image description here
1.) Add a button to your to_do_item_layout first
2.) Now add this code to add a button to each item
Button btn = (Button) convertView.findViewById(R.id.my_btn);
3.) Add a listener to it
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.remove(items.get(position));
}
});

checkbox in listview to select and delete

This is my code I have one list view in the fragment which read sms using cursor I have set check box in adapter and I have 3 buttons outside the list view in main layout I need the followings
1.When I click one button it display checkbox in the list
2.when I select and scroll the list selected items wont disappears
3.select all button to select all in the list 4.delete button to delete the selected item remaining messages instantly updated.
public class TabFragment extends Fragment
{
ListView mlistView;
ArrayList<Message> sms = new ArrayList<Message>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_sms, container, false);
mlistView = (ListView) view.findViewById(R.id.SMSList);
Button sdel=(Button)view.findViewById(R.id.sdelete);
populateMessageList();
sdel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
public void populateMessageList() {
fetchInboxMessages();
if (fetchInboxMessages() != null) {
mlistView.setAdapter(new datalist(getActivity().getApplicationContext(),this));
}
}
public ArrayList<Message> fetchInboxMessages() {
Uri muriSms = Uri.parse("content://sms/inbox");
Cursor mcursor = getActivity().getContentResolver().query(muriSms,
new String[] { "_id", "address", "date", "body" }, null, null,
null);
mcursor.moveToFirst();
while (mcursor.moveToNext()) {
Message mMessage = new Message();
mMessage.setmAddress(mcursor.getString(mcursor
.getColumnIndex("address")));
mMessage.setmBody(mcursor.getString(mcursor.getColumnIndex("body")));
mMessage.setmDate(mcursor.getString(mcursor.getColumnIndex("date")));
sms.add(mMessage);
}
return sms;
}
class datalist extends BaseAdapter {
LayoutInflater inflater = null;
Boolean selected;
Boolean[] checkboxstate;
public datalist(Context applicationContext, TabFragment tabFragment) {
inflater = LayoutInflater.from(applicationContext);
} public datalist(Context applicationContext, int simple_list_item_multiple_choice, ArrayList<Message> sms) {
}
#Override
public int getCount() {
return sms.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row;
row = inflater.inflate(R.layout.sms_adapter, parent, false);
ImageView img1 = (ImageView) row.findViewById(R.id.icon2);
TextView txt1 = (TextView) row.findViewById(R.id.text1);
TextView txt2 = (TextView) row.findViewById(R.id.text2);
CheckBox cb=(CheckBox)row.findViewById(R.id.check);
Long timestamp = Long.parseLong(sms.get(position).getmDate());
Calendar mcalendar = Calendar.getInstance();
mcalendar.setTimeInMillis(timestamp);
DateFormat mformatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
txt1.setText(sms.get(position).getmBody());
txt2.setText("Sent by" + sms.get(position).getmAddress() + "\n" + mformatter.format(mcalendar.getTime()));
/* if(selected==false)
cb.setVisibility(row.GONE);
else*/
cb.setVisibility(row.VISIBLE);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sms.get(position).setSelected(isChecked);
if(isChecked){
buttonView.setSelected(true);
}else {
buttonView.setSelected(false);
}
}
});
return row;
}
}
public class Message {
private String mAddress;
private String mBody;
private String mDate;
private int icon;
boolean selected;
public void setmAddress(String mAddress) {
this.mAddress = mAddress;
}
public void setmBody(String mBody) {
this.mBody = mBody;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmBody() {
return mBody;
}
public String getmAddress() {
return mAddress;
}
public String getmDate() {
return mDate;
}
public boolean isSelected() {
return selected;
}
public int getIcon(){
return icon;} public void setSelected(boolean selected) {
this.selected = selected;
}}}

Categories

Resources