I am trying to make an alertdialog for when the user presses the cardview to delete it. This is in my ProductAdapter code
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(????);
what would I put in the brackets where I have the ????
I have looked at examples on this site and the ones I have seen have used ActivityName.this inside the brackets. However this code is in the ProductAdapter code and I can't use ProductAdapter.this. (my main activity is called create.java fyi)
So what would go in there? Thanks
update
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
//this context we will use to inflate the layout
private Context mCtx;
private SearchableSpinner spinner;
//we are storing all the products in a list
private List<Product> productList;
private Activity create;
public ProductAdapter(Activity activity){
create = activity;
}
//getting the context and product list with constructor
public ProductAdapter(Activity activity, List<Product> productList) {
this.mCtx = mCtx;
create = activity;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, final int position) {
// //getting the product of the specified position
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(mCtx, R.layout.item_spinner_layout,
Product.getSpinnerItemsList());
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setAdapter(spinnerArrayAdapter);
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
mSpinnerSelectedItem.put(position, mPosition);
TextView mTextView = view.findViewById(R.id.mSpinnerText);
Toast.makeText(mCtx, "Selected Item: " + mTextView.getText().toString(), Toast.LENGTH_LONG).show();
Log.e("***************", "Selected Item: " + mTextView.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//binding the data with the viewholder views
if (mSpinnerSelectedItem.containsKey(position)) {
holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
}
holder.getView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
productList.remove(position);
notifyItemRemoved(position);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
SearchableSpinner spinner;
EditText editText;
TextView textView5;
CheckBox checkBox;
LinearLayout linearLayout;
View rootView;
public ProductViewHolder(View itemView) {
super(itemView);
spinner = itemView.findViewById(R.id.spinner);
editText = itemView.findViewById(R.id.editText);
textView5 = itemView.findViewById(R.id.textView5);
checkBox = itemView.findViewById(R.id.checkBox);
rootView = itemView.findViewById(R.id.linearLayout);
}
public View getView() {
return rootView;
}
}
}
Although AlertDialog.Builder() accepts a Context reference in its argument, it is better to pass an Activity reference to it, not applicationContext because of potential theme and window attachment problems. So, pass an Activity reference to your adapter and use it to build an AlertDialog.
public class ProductAdapter extends SomeAdapter {
private Activity create;
public ProductAdapter(Activity activity, List<Product> productList) {
create = activity;
this.productList = productList;
}
private void showAlertDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);
// ...
alertDialogBuilder.create().show();
}
}
You must pass context of ther activity there, check this link for more understanding.
Only pass the context of calling activity to your ProductAdapter class and use this
Related
I'm new to Programming and to Android and have please a question.
I have just easy app to insert, delete and update cars.
I create an interface to communicate the RecyclerAdapter to the Fragments.
Insert and delete cars work without problemes, however when I update the instance it will be not changed.
To make it more clearly,the user has a button "updateButtonOnRecyclerView" on RecyclerView and when he clicks it,he get the UpdateFragment where he can update the instance and finally he clicks the button "updateButtonOnFragment" to save the updates.
I hope that someone can help me. thanks a lot.
UpdateFragment
public class UpdateFragment extends Fragment {
private EditText modelUpdate;
private EditText colorUpdate;
private EditText dplUpdate;
private EditText priceUpdate;
private EditText descriptionUpdate;
private Button updateButtonOnFragment;
private MyViewModel myViewModel;
public UpdateFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_update, container, false);
modelUpdate=view.findViewById(R.id.input_model_update);
colorUpdate=view.findViewById(R.id.input_color_update);
priceUpdate=view.findViewById(R.id.input_price_update);
dplUpdate=view.findViewById(R.id.input_dpl_update);
descriptionUpdate=view.findViewById(R.id.input_description_update);
MyViewModel myViewModel= new ViewModelProvider(this).get(MyViewModel.class);
updateButtonOnFragment =view.findViewById(R.id.btnUpdate);
updateButtonOnFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String model=modelUpdate.getText().toString();
String color=colorUpdate.getText().toString();
String price=priceUpdate.getText().toString();
String dpl=dplUpdate.getText().toString();
String description=descriptionUpdate.getText().toString();
// create an instance of car
Car car = new Car();
car.setCarModel(model);
car.setCarColor(color);
car.setCarDescription(description);
car.setCarDpl(dpl);
car.setCarPrice(price);
myViewModel.updateCar(car);
MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new BaseFragment(),null).commit();
}
});
return view;
}
}
RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private List<Car>list;
private Context context;
private MyViewModel myViewModel;
private CarAdapterEvent carAdapterEvent;
//Constructor
public RecyclerAdapter(List<Car> list,Context context,CarAdapterEvent carAdapterEvent ) {
this.list = list;
this.context=context;
this.carAdapterEvent=carAdapterEvent;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.car_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
context=parent.getContext();
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Car car = list.get(position);
holder.tvModel.setText(car.getCarModel());
holder.tvColor.setText(car.getCarColor());
holder.tvDpl.setText(car.getCarDpl());
holder.tvDescription.setText(car.getCarDescription());
holder.tvPrice.setText(car.getCarPrice());
}
#Override
public int getItemCount() {
if(list !=null)
{
return list.size();
}
else return 0;
}
public void setData(List<Car>list){
this.list=list;
notifyDataSetChanged();
}
// generate ViewHolder
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvModel;
TextView tvColor;
TextView tvDpl;
TextView tvDescription;
TextView tvPrice;
Button btnDelete;
Button updateButtonOnRecyclerView;
// Constructor of ViewHolder
public MyViewHolder(#NonNull View itemView) {
super(itemView);
// Inflate the views
tvModel=itemView.findViewById(R.id.model);
tvColor=itemView.findViewById(R.id.color);
tvDescription=itemView.findViewById(R.id.description);
tvDpl=itemView.findViewById(R.id.dpl);
tvPrice=itemView.findViewById(R.id.price);
btnDelete=itemView.findViewById(R.id.btn_delete);
updateButtonOnRecyclerView =itemView.findViewById(R.id.btn_update);
// Listener for Delete button
btnDelete.setOnClickListener(this);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
carAdapterEvent.onDeleteClicked(list.get(position));
}
});
//Listener for update button
updateButtonOnRecyclerView.setOnClickListener(this);
updateButtonOnRecyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
carAdapterEvent.onUpdateClicked(list.get(position));
}
});
}
private void CreateAlertDialoge()
{
AlertDialog.Builder builder =new AlertDialog.Builder(context);
builder.setMessage("Are you sure to delete");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Car car = new Car();
int ID=list.get(getAdapterPosition()).getCarId();
car.setCarId(ID);
myViewModel.deleteCar(car);
MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new BaseFragment(),null).commit();
Toast.makeText(context, "Yes", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "no", Toast.LENGTH_SHORT).show();
}
});
builder.create();
builder.show();
}
#Override
public void onClick(View v) { }
}
}
Interface for communication
public interface CarAdapterEvent {
void onDeleteClicked(Car car);
void onUpdateClicked(Car car);
}
BaseFragment
public class BaseFragment extends Fragment implements CarAdapterEvent {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private List<Car>list=new ArrayList<>();
private MyViewModel myViewModel;
public RecyclerAdapter recyclerAdapter;
// Required empty public constructor
public BaseFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_base, container, false);
//Inflate recyclerView
recyclerView=view.findViewById(R.id.recyclerViewId);
// define and set LayoutManager
layoutManager= new GridLayoutManager(requireActivity(),2);
recyclerView.setLayoutManager(layoutManager);
//define and set RecyclerView Adapter
recyclerAdapter = new RecyclerAdapter(list, getContext(),this);
recyclerView.setAdapter(recyclerAdapter);
//observer
myViewModel= new ViewModelProvider(this).get(MyViewModel.class);
myViewModel.getGetAllCars().observe(getViewLifecycleOwner(), new Observer<List<Car>>() {
#Override
public void onChanged(List<Car> cars) {
recyclerAdapter.setData(cars);
}
});
return view;
}
#Override
public void onDeleteClicked(Car car) {
myViewModel.deleteCar(car);
MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new BaseFragment(),null).commit();
}
#Override
public void onUpdateClicked(Car car) {
myViewModel.updateCar(car);
MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new UpdateFragment(),null).commit();
}
}
product Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductViewHolder>{
private Context context;
private List<Product> listProducts;
private SqliteDatabase mDatabase;
public ProductAdapter(Context context, List<Product> listProducts) {
this.context = context;
this.listProducts = listProducts;
mDatabase = new SqliteDatabase(context);
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_list_layout, parent, false);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
final Product singleProduct = listProducts.get(position);
holder.name.setText(singleProduct.getName());
// holder.quantity.setText(singleProduct.getQuantity());
//when i call quantity(the ABOVE value) the application crashes and when i call only name the field the values gets displayed
holder.editProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTaskDialog(singleProduct);
}
});
holder.deleteProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabase.deleteProduct(singleProduct.getId());
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
});
}
#Override
public int getItemCount() {
return listProducts.size();
}
private void editTaskDialog(final Product product){
LayoutInflater inflater = LayoutInflater.from(context);
View subView = inflater.inflate(R.layout.add_product_layout, null);
final EditText nameField = (EditText)subView.findViewById(R.id.enter_name);
final EditText quantityField = (EditText)subView.findViewById(R.id.enter_quantity);
if(product != null){
nameField.setText(product.getName());
quantityField.setText(String.valueOf(product.getQuantity()));
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Edit product");
builder.setView(subView);
builder.create();
builder.setPositiveButton("EDIT PRODUCT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String name = nameField.getText().toString();
final String quantityStr = quantityField.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(quantityStr))
{
Toast.makeText(context, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
}
else
{
final int quantity = Integer.parseInt(quantityStr);
if(quantity<=0)
{
Toast.makeText(context,"input is less than or equal to zero",Toast.LENGTH_LONG).show();
}
else {
mDatabase.updateProduct(new Product(product.getId(), name, quantity));
//refresh the activity
((Activity)context).finish();
context.startActivity(((Activity)context).getIntent());
}
}
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Task cancelled", Toast.LENGTH_LONG).show();
}
});
builder.show();
}
}
product viewHolder
public class ProductViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView quantity;
public ImageView deleteProduct;
public ImageView editProduct;
public ProductViewHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.product_name);
deleteProduct = (ImageView)itemView.findViewById(R.id.delete_product);
editProduct = (ImageView)itemView.findViewById(R.id.edit_product);
quantity=(TextView)itemView.findViewById(R.id.product_name2);
}
}
Now the issue here is when is use holder.quantity.setText(singleProduct.getQuantity()) the application crashes.
I also wanted to add date picker dialog and want to display it in the recycler view so for date the code is same like holder.object.setText or something else and can we use a form for alert dialog like
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_dark);
dialog.setCancelable(true);
I have created the database file but the issue is mainly related to recycler view contents and if i wanted multiple holder is it possible to get the contents?
getQuantity() returns a int. So, Android is trying to search for a resource with id == getQuantity() leading to the crash (since you probably any resource with that id.
In other words, you are invoking TextView.setText(int resourceId) and not TextView.setText(String text)).
To fix, change this:
holder.quantity.setText(singleProduct.getQuantity());
To this:
holder.quantity.setText(String.valueOf(singleProduct.getQuantity()));
Hello how can I populate my ArrayList with an EditText and a button, the problem is that I don't know how from EditText I can initialize an object and then add It to my ArrayList
Thank you
//Main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView view = (ListView)findViewById(R.id.listview);
EditText edit = (EditText)findViewById(R.id.editText);
Button button = (Button)findViewById(R.id.button);
Todo eat = new Todo("Eat ");
Todo sleep = new Todo("Sleep");
ArrayList<Todo> todolist = new ArrayList<>();
todolist.add(eat);
todolist.add(sleep);
Todoadapter adapter = new Todoadapter(this,R.layout.custom_adapter_layout,todolist);
view.setAdapter(adapter);
}
}
// Object
public class Todo {
private String todo;
public Todo(String todo) {
this.todo = todo;
}
public String getTodo() {
return todo;
}
public void setTodo(String todo) {
this.todo = todo;
}
}
//ArrayAdapter
public class Todoadapter extends ArrayAdapter<Todo> {
private Context mcontext;
int mresource;
private List<Todo> objects = new ArrayList<>();
public Todoadapter(#NonNull Context context, int resource, #NonNull ArrayList<Todo> objects) {
super(context, resource, objects);
this.mresource = resource;
this.mcontext = context;
this.objects = objects;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String todo = getItem(position).getTodo();
LayoutInflater inflater = LayoutInflater.from(mcontext);
convertView = inflater.inflate(mresource, parent, false);
final CheckBox box = (CheckBox) convertView.findViewById(R.id.checkBox2);
box.setText(todo);
box.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(box.isChecked()){
//Delay to see animation
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
objects.remove(getItem(position)); //Your object list where you have the itens
notifyDataSetChanged(); //If you are using a recycler view.
}
},300); //adding 0.3 sec delay
}
}
});
return convertView;
}
}
First add listener for button either in XML or via java
activity_main
<Button ...
android:id="#+id/button"
android:onClick="addTodo"/>
In MainActivity.java
1.) Make adapter and list instance global to class
2.) Create addTodo method (keep it public and add View parameter)
3.) After click, fetch data from edittext, create a Todo instance and add it to list
4.) Notify the adapter to reflect the changes
public class MainActivity extends AppCompatActivity {
// 1
private ArrayList<Todo> todolist;
private Todoadapter adapter;
private EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView view = (ListView)findViewById(R.id.listview);
edit = (EditText)findViewById(R.id.editText);
Button button = (Button)findViewById(R.id.button);
Todo eat = new Todo("Eat ");
Todo sleep = new Todo("Sleep");
todolist = new ArrayList<>();
todolist.add(eat);
todolist.add(sleep);
adapter = new Todoadapter(this,R.layout.custom_adapter_layout,todolist);
view.setAdapter(adapter);
}
// 2
public void addTodo(View view){
// 3
todolist.add(new Todo(edit.getText().toString()));
// 4
adapter.notifyDataSetChanged();
}
}
buttonsetOnClickListener(new OnClickListener() {
public void onClick(View v) {
String data=edit.getText().toString();
if(data.isEmpty())
{
Toast.makeText(getApplicationContext(), "Please enter data", Toast.LENGTH_LONG).show();
return;
}
todolist.add(new Todo(data));
adapter.notifyDataSetChanged();
}
});
add above code in your onCreate, remember you have to validate edit text data before you add it to todolist otherwise app may crash.
I have a recycler view, with an ArrayList from custom objects.
Each row has a delete button, when clicked the item is deleted from the recyclerview.
Now the delete button works, and deletes the correct item from the arraylist, however when the items are displayed again in the list, only the bottom item is deleted, and the item which was really deleted from the list stays there.
Its really weird, and I cannot figure out why?
I manage the deleted item from the activity, here is the code of the activity:
public class ManageExerciseActivity extends AppCompatActivity {
private static final String TAG = "999.OffLimitsActivity";
private RecyclerView exerciseRecyclerView;
private ExerciseManageAdapter exerciseAdapter;
public ArrayList<Exercise> exerciseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_exercise);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ManageExerciseActivity.this, AddExerciseActivity.class);
startActivity(intent);
}
});
fab.setImageBitmap(textAsBitmap("ADD", 40, Color.WHITE));
exerciseList = new ArrayList<>();
getSupportActionBar().setTitle("Manage my exercises");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
exerciseRecyclerView = (RecyclerView) findViewById(R.id.exercise_manage_recycler_view);
exerciseAdapter = new ExerciseManageAdapter(exerciseList);
exerciseAdapter.setOnItemClickListener(new ExerciseManageAdapter.ClickListener() {
#Override
public void onItemClick(final int position, final View v) {
Log.d(TAG, "onItemClick pos = " + position);
// custom dialog
AlertDialog.Builder builder = new AlertDialog.Builder(ManageExerciseActivity.this);
builder.setMessage("Do you wish to delete this exercise?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String itemRemoved = exerciseList.get(position).getNameOfExercise();
exerciseList.remove(position);
exerciseAdapter.notifyDataSetChanged();
Snackbar.make(v, itemRemoved + " deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", null).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
builder.create();
builder.show();
}
});
exerciseRecyclerView.setAdapter(exerciseAdapter);
exerciseRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
and here is the adapter:
public class ExerciseManageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static ClickListener clickListener;
public ImageView exerciseItemIcon;
public TextView exerciseNameTextView;
public TextView exerciseDurationTextView;
public TextView exerciseTimesRemainingTextView;
public ImageView deleteImageView;
ArrayList<Exercise> exerciseArrayList = new ArrayList<>();
public ExerciseManageAdapter(ArrayList<Exercise> exerciseArrayList) {
this.exerciseArrayList = exerciseArrayList;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
class ExerciseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ExerciseViewHolder(View view) {
super(view);
// view.setOnClickListener(this);
exerciseNameTextView = (TextView)view.findViewById(R.id.exercise_manage_name_textView);
exerciseDurationTextView = (TextView)view.findViewById(R.id.exercise_manage_duration_textview);
exerciseTimesRemainingTextView = (TextView)view.findViewById(R.id.exercise_manage_times_remaining);
exerciseItemIcon = (ImageView)view.findViewById(R.id.exercise_manage_item_icon);
deleteImageView = (ImageView)view.findViewById(R.id.delete_exercise_button);
deleteImageView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
ExerciseManageAdapter.clickListener = clickListener;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return exerciseArrayList.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.exercise_manage_item_row, parent, false);
return new ExerciseViewHolder(itemView);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
ExerciseViewHolder exerciseViewHolder = (ExerciseViewHolder) holder;
exerciseNameTextView.setText(exerciseArrayList.get(position).getNameOfExercise());
exerciseDurationTextView.setText(exerciseArrayList.get(position).getDurationOfExercise());
exerciseTimesRemainingTextView.setText(exerciseArrayList.get(position).getTimesPerWeek() + " times a week");
exerciseItemIcon.setImageResource(exerciseArrayList.get(position).getExerciseIcon());
}
}
Thanks
try this.!
notifyItemRemoved(position);
notifyItemRangeChanged(position, mData.size());
SORRY FOR THIS CONFUSION:
UPDATED QUESTION:
I'm trying to remove a list item from the listview. when the item is clicked, the alertdialog is shown. If i click OK, then the selected item must be removed from the listview.
My Code goes below:
case R.id.lvinc:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Event ");
builder.setMessage("Delete this Event ?");
builder.setPositiveButton("Ok, Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try
{
???? //What code to delete the selected list item?
}catch(Exception e)
{
e.printStackTrace();
}
}
});
AlertDialog alert = builder.create();
alert.show();
displaylist();
break;
Any help is really appreciated and thanks in advance...
I tried to solve it and got one solution pls go through the code below:
listview.java
public class listview extends Activity implements OnItemClickListener{
ListView list;
ListAdapter adapter;
ArrayList<String> nameArray;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//xml should have an ListView element
nameArray = new ArrayList<String>();
nameArray.add("Item1");
nameArray.add("Item2");
nameArray.add("Item3");
nameArray.add("Item4");
nameArray.add("Item5");
list = (ListView) findViewById(R.id.listView);
list.setOnItemClickListener(listview.this);
adapter=new ListAdapter(listview.this, nameArray);
list.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
showDialog(arg2);
}
#Override
protected Dialog onCreateDialog(final int id) {
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete Event")
.setCancelable(true)
.setPositiveButton("Ok, Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
nameArray.remove(id);
adapter=new ListAdapter(listview.this, nameArray);
list.setAdapter(adapter);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
return super.onCreateDialog(id);
}
}
//Adapter Class
ListAdapter.java
public class ListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> name;
private static LayoutInflater inflater=null;
public ListAdapter(Activity a, ArrayList<String> nameArray) {
activity = a;
name = nameArray;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return name.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.list_item, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.title);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name.get(position));
return vi;
}
}
I don't know what kind of data you are using.
I imagine Cursor, database or List, feel free to tell us, so it will be easier to help.
This example is for a list:
protected void onListItemClick(View v, int pos, long id) {
Log.i(TAG, "onListItemClick id=" + id);
//Display your Dialog
(...)
builder.setPositiveButton("Ok, Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
myList.remove(pos);
myAdapter.notifyDataChanged();
}
});
}
You propably have some kind of Adapter, that you have feed with some kind of data.
Remove the item from that list, and notifyDataChanged to the ListView.
And finally: dialog.dismiss();
itemLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
indexClick = position;
}
}
if ((indexClick) == (position)) {
itemLayout.setBackgroundResource(R.drawable.tab_select);
}
otherwise put tab_unselected image.