I'm making a todo app and when an item is marked as finished an image should be displayed in front of the list item. But images are not visible in the list view even if the item status in the database is changed as finished.
This is my adapter class.
public class ToDoAdapter extends ArrayAdapter {
private Context context;
private int resource;
List<ToDoModel> todos;
public ToDoAdapter(#NonNull Context context, int resource, #NonNull List<ToDoModel> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.todos = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//Inflate card view
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(resource, parent, false);
TextView title = row.findViewById(R.id.title);
TextView description = row.findViewById(R.id.txtDescription);
ImageView img = (ImageView)row.findViewById(R.id.img_done);
img.setVisibility(View.VISIBLE);
//Set data in card view
ToDoModel todo = todos.get(position);
title.setText(todo.getTitle());
description.setText(todo.getDescription());
//Show done image
if(todo.getFinished() > 0){
img.setVisibility(View.VISIBLE);
}
return row;
}
}
This is MainActivity.
public class MainActivity extends AppCompatActivity {
private ListView todoList;
private TextView countTxt;
private Button addTodo;
private List<ToDoModel> toDos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todoList = (ListView)findViewById(R.id.listViewToDo);
countTxt = (TextView)findViewById(R.id.txtCount);
addTodo = (Button)findViewById(R.id.btnAdd);
toDos = new ArrayList<>();
addTodo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Go to next activity
startActivity(new Intent(getApplicationContext(), AddToDO.class));
}
});
}
#Override
protected void onResume() {
super.onResume();
DBHandler dbh = new DBHandler(getApplicationContext());
//Set count
int count = dbh.getCountTODO();
countTxt.setText("You have " + count + " TODOs");
//Save list
toDos = dbh.getAllToDos();
//Set adapter to list
ToDoAdapter toDoAdapter = new ToDoAdapter(getApplicationContext(), R.layout.todo_cardview, toDos);
todoList.setAdapter(toDoAdapter);
//Add click listener to list element
todoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get clicked item
ToDoModel todo = toDos.get(position);
//Dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(todo.getTitle());
builder.setMessage(todo.getDescription());
//Buttons
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbh.deleteItem(todo.getId());
Toast.makeText(getApplicationContext(), "ToDo Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setPositiveButton("Finished", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
long time = System.currentTimeMillis();
//Update status
dbh.updateFinished(todo.getId(), time);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, AddToDO.class);
intent.putExtra("id", todo.getId());
intent.putExtra("title", todo.getTitle());
intent.putExtra("description", todo.getDescription());
intent.putExtra("finished", todo.getFinished());
startActivity(intent);
}
});
builder.show();
}
});
}
}
Use Glide or Picasso Library to Displaying Image with any other Shape.
Glide Example:
Glide.with(mContext).load(responseList.getLogoUrl()).apply(RequestOptions.circleCropTransform()).into(holder.imageName);
Picasso Example:
Picasso.get().load(clsobjname.getLogoUrl())
.into(viewHolder.imagename);
Related
i have some problems with updating fragment view after item deleted. So i have one fragment which one showing all items added from another activity. And when im trying to delete item it's not updating view so i should restart fragment to see updated fragment.
There is my fragment
public class MyGarageFragment extends Fragment {
FloatingActionButton fab;
RecyclerView mRecyclerView;
DatabaseHelper databaseHelper;
RVAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_my_garage, null);
mRecyclerView = v.findViewById(R.id.recyclerView);
databaseHelper = new DatabaseHelper(getContext());
showRecord();
fab = v.findViewById(R.id.addFabButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// startActivity(new Intent(getContext(), AddRecordActivity.class));
Intent intent = new Intent(getContext(), AddAutoActivity.class);
intent.putExtra("editMode",false);
startActivity(intent);
}
});
return v;
}
private void showRecord() {
adapter = new RVAdapter(getContext(),databaseHelper.getAllData(Constants.C_ADD_TIMESTAMP + " DESC"));
mRecyclerView.setAdapter(adapter);
}
#Override
public void onResume(){
super.onResume();
showRecord();
}
also my Recyclerview Adapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.Holder> {
private Context context;
private ArrayList<Model> arrayList;
DatabaseHelper databaseHelper;
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_my_garage,parent,false);
return new Holder(view);
}
public RVAdapter(Context context, ArrayList<Model> arrayList) {
this.context = context;
this.arrayList = arrayList;
databaseHelper = new DatabaseHelper(context);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
Model model = arrayList.get(position);
String id = model.getId();
String image = model.getImage();
String name = model.getName();
String age = model.getAge();
String phone = model.getPhone();
String addTimeStamp = model.getAddTimeStamp();
String updateTimeStamp = model.getUpdateTimeStamp();
holder.profileIv.setImageURI(Uri.parse(image));
holder.name.setText(name);
holder.age.setText(age);
holder.phone.setText(phone);
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(context, holder.editButton);
popupMenu.inflate(R.menu.popup_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
editDialog(
""+position,
""+id,
""+name,
""+age,
""+phone,
""+image,
""+addTimeStamp,
""+updateTimeStamp
);
break;
case R.id.action_delete:
deleteDialog(""+id);
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"item " + id, Toast.LENGTH_SHORT).show();
}
});
}
private void deleteDialog(String id) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure?");
builder.setCancelable(false);
builder.setIcon(R.drawable.ic_baseline_delete_24);
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteInfo(id);
((MyGarageFragment)context).onResume();
Toast.makeText(context, "Delete Success!", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
private void editDialog(String position, String id, String name, String age, String phone, String image, String addTimeStamp, String updateTimeStamp) {
Intent intent = new Intent(context, EditAutoActivity.class);
intent.putExtra("ID",id);
intent.putExtra("NAME",name);
intent.putExtra("AGE",age);
intent.putExtra("PHONE",phone);
intent.putExtra("IMAGE",image);
intent.putExtra("ADD_TIMESTAMP",addTimeStamp);
intent.putExtra("UPDATE_TIMESTAMP",updateTimeStamp);
intent.putExtra("editMode",true);
context.startActivity(intent);
}
#Override
public int getItemCount() {
return arrayList.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView profileIv;
TextView name,age,phone;
ImageView editButton;
public Holder (#NonNull View itemView){
super(itemView);
profileIv = itemView.findViewById(R.id.profileIv);
name = itemView.findViewById(R.id.name);
age = itemView.findViewById(R.id.age);
phone = itemView.findViewById(R.id.phone);
editButton = itemView.findViewById(R.id.editBtn);
}
}
}
so what should i do in deleteDialog to delete cardview item and refresh ui?
private void deleteDialog(String id) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure?");
builder.setCancelable(false);
builder.setIcon(R.drawable.ic_baseline_delete_24);
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteInfo(id);
((MyGarageFragment)context).onResume();
Toast.makeText(context, "Delete Success!", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});
I have kind of to-do app. In profile activity, there are 2 tabs.
To-do and Done. In Tab 1, user can check as "done" of their "to-do". In this case, I want to update TAB 2's recyclerview.
I tried several things, but didn't work. Here is TAB 1 codes, it's almost same as TAB 2.
TAB 1 Class
public class Tab_Profile_1 extends Fragment {
private RecyclerView recyclerView_tab_todo;
private List<Model_ListItem> itemList;
private Adapter_Profile_ToDo adapter_profile_toDo;
SharedPreferences mSharedPref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_tab_1, container, false);
//TO-DO
//
recyclerView_tab_todo = view.findViewById(R.id.recyclerView_tab_todo);
//
fetchUserToDo();
return view;
}
public void fetchUserToDo() {
itemList = new ArrayList<>();
//First Settings
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchUserToDo(session_user_id);
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
itemList = response.body();
adapter_profile_toDo = new Adapter_Profile_ToDo(getContext(), itemList);
recyclerView_tab_todo.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView_tab_todo.setLayoutManager(layoutManager);
recyclerView_tab_todo.setAdapter(adapter_profile_toDo);
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}}
TAB 1 RecyclerView Adapter
public class Adapter_Profile_ToDo extends RecyclerView.Adapter {
private Context context;
private List<Model_ListItem> itemList;
private String url_extension_images = URL_Extension.url_extension_images;
SharedPreferences mSharedPref;
ProgressDialog progressDialog;
View view;
public Adapter_Profile_ToDo(Context context, List<Model_ListItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(context).load(url_extension_images + itemList.get(position).getItem_image()).into(holder.imageView_profile_todo);
holder.textView_profile_todo_name.setText(itemList.get(position).getItem_name());
holder.textView_profile_todo_desc.setText(itemList.get(position).getItem_description());
holder.layout_profile_todo_detail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//detail
}
});
holder.layout_profile_todo_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getRootView().getContext(), R.style.AlertStyle);
builder.setTitle("\"" + itemList.get(position).getItem_name() + "\"" + "\n");
builder.setIcon(R.drawable.ic_bookmark);
builder.setPositiveButton("YAPTIM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
addDone("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNegativeButton("SİL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
deleteUserToDo("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNeutralButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView_profile_todo;
TextView textView_profile_todo_name, textView_profile_todo_desc;
LinearLayout layout_profile_todo_detail, layout_profile_todo_add;
public ViewHolder(View itemView) {
super(itemView);
imageView_profile_todo = itemView.findViewById(R.id.imageView_profile_todo);
textView_profile_todo_name = itemView.findViewById(R.id.textView_profile_todo_name);
textView_profile_todo_desc = itemView.findViewById(R.id.textView_profile_todo_desc);
layout_profile_todo_detail = itemView.findViewById(R.id.layout_profile_todo_detail);
layout_profile_todo_add = itemView.findViewById(R.id.layout_profile_todo_add);
}
}
public void deleteUserToDo(final String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = api_service.deleteUserToDo(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Silindi!", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
});
}
public void addDone(String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service apiService = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = apiService.addDone(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Eklendi", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
}
});
}
public void showProgressDialog() {
progressDialog = new ProgressDialog(view.getRootView().getContext());
progressDialog.setMessage("Yükleniyor");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
If i'm reading this correctly, you have two tabs and a backend database that stores the to do items and their state? To get the second list to update, you just need to do the same thing that you're doing in your first list, and update the adapter's data set and notify that the data set changed. How you trigger this action in your second tab is really the question.
You can either use an interface and have your adapter notify your activity that recycler view 1 had an action on it, and you can then tell adapter 2 to update its data. You can either pass back the data and only notify one row, or you could notify the entire data set. If you're doing this all service based, you could just reload the recycler view from the service and it will have the new data.
I think all you need to figure out is how you want to notify tab 2 that it needs to update its data. My recommendation is:
public interface AdapterInterface
{
void itemCompleted(Item hereIsTheItemThatNeedsToBeAddedTo2);
}
Then inside your adapter have a property with getters/setters such as:
private AdapterInterface adapterInterfaceListener;
Inside your Fragment/Activity implement AdapterInterface and implement the itemCompleted function.
And then set your adapter.setAdapterInterfaceLisetener to that function that you implemented. Then inside your adapter when the user clicks the checkbook to mark it as done, you can call the adapterInterfaceListener.itemCompleted() function, and it will send that information to your Fragment/Activity. From there you can give that new data to adapter2, or recall the API, however you want to get the new data.
Does this help?
I have a list that I saved in sharedpreferences I want to delete an item from the listview when the user longclicks so on the long click the app prompts you with a question to delete or not when you confirm it deletes it. This works but when i come back to the activity the list still contains that item that has been deleted
This is the code for the onCreateView. tinyDB is sharedprefrences.Thank you
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab_secondsemester, container, false);
btnAddNew = (Button)rootView.findViewById(R.id.btnAddNewYearOneSecondSemester);
listView = (ListView)rootView.findViewById(R.id.listViewSubjectsMyCoursesSecondSemester);
tinyDB = new TinyDB(getContext());
storedList = new ArrayList<>(tinyDB.getListString("storedList"));
generalList = new ArrayList<>();
spinnerValues = new ArrayList<>();
getActivity().setTitle("Year One");
setHasOptionsMenu(true);
btnAddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext(),R.style.DialogeTheme);
// Setting Dialog Title
alertDialog.setTitle("Add new");
// Setting Dialog Message
String getUsername = tinyDB.getString("Username");
alertDialog.setMessage("Hello "+ getUsername + ", please write the new subject");
final EditText input = new EditText(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setTextColor(Color.parseColor("#f06292"));
alertDialog.setView(input);
alertDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String getSubjectInput = input.getText().toString();
storedList.add(getSubjectInput);
tinyDB.putListString("storedList", storedList);
arrayAdapter.notifyDataSetChanged();
}
});
alertDialog.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.create();
alertDialog.show();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, final int i, long l) {
new SweetAlertDialog(getContext(), SweetAlertDialog.WARNING_TYPE)
.setTitleText("Delete")
.setContentText("Are you sure you want to delete this course")
.setConfirmText("YES")
.setCancelText("NO")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
storedList.remove(i);
arrayAdapter.notifyDataSetChanged();
tinyDB.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
arrayAdapter.notifyDataSetChanged();
}
});
sweetAlertDialog.dismiss();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
}
})
.show();
return true;
}
});
arrayAdapter = new CustomListAdapter(getContext(),storedList);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
return rootView;
}
Use this when the user deletes it
public void removeAt(int position) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
}
mDataset is the array/list in which you save all the data for the adapter
I'm currently using the Parse API for Android, and I currently have a Array of Strings in my application. I currently have a ListView with all of my Strings. Inside my app inside the ListView itself I have implemented a setOnItemLongClickListener with a Dialog. I want to delete a the selected ListView item's string from Parse.
Image of the Database Row
NotesFragment.java
public class NotesFragment extends Fragment {
ParseUser user;
ListView notesList;
private FloatingActionButton FAB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
notesList = (ListView) rootView.findViewById(R.id.lv_contact);
user = ParseUser.getCurrentUser();
FAB = (FloatingActionButton) rootView.findViewById(R.id.fab);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), AddNoteActivity.class);
getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
startActivity(intent);
}
});
final ArrayList<ParseObject> list1 = (ArrayList) user.getList("notes");
ArrayAdapter<ParseObject> arrayAdapter;
arrayAdapter = new ArrayAdapter<ParseObject>(getContext(), android.R.layout.simple_list_item_1, list1);
RelativeLayout emptyView = (RelativeLayout) rootView.findViewById(R.id.empty);
if (list1 == null) {
emptyView.setVisibility(View.VISIBLE);
} else {
notesList.setAdapter(arrayAdapter);
emptyView.setVisibility(View.INVISIBLE);
}
notesList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(getContext())
.setTitle("Are you sure you want to Delete?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ArrayList<String> toRemove = new ArrayList<>();
toRemove.add("Hey");
ParseUser.getCurrentUser().removeAll("checklistDat", toRemove);
ParseUser.getCurrentUser().saveInBackground();
ParseUser.getCurrentUser().deleteInBackground();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
return true;
}
});
return rootView;
}
}
I was able to fix this by doing this
NotesFragment.java
public class NotesFragment extends Fragment {
ParseUser user;
ListView notesList;
ProgressBar mPB;
private FloatingActionButton FAB;
ArrayList<ParseObject> list1 = (ArrayList) ParseUser.getCurrentUser().getList("notes");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
mPB = (ProgressBar) rootView.findViewById(R.id.progress_bar);
mPB.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mPB.setVisibility(View.GONE);
}
}, 3500);
notesList = (ListView) rootView.findViewById(R.id.lv_contact);
user = ParseUser.getCurrentUser();
FAB = (FloatingActionButton) rootView.findViewById(R.id.fab);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), AddNoteActivity.class);
getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
startActivity(intent);
}
});
final ArrayAdapter<ParseObject> arrayAdapter;
arrayAdapter = new ArrayAdapter<ParseObject>(getContext(), android.R.layout.simple_list_item_1, list1);
final RelativeLayout emptyView = (RelativeLayout) rootView.findViewById(R.id.empty);
if (list1 == null) {
emptyView.setVisibility(View.VISIBLE);
mPB.setVisibility(View.GONE);
} else {
notesList.setAdapter(arrayAdapter);
emptyView.setVisibility(View.INVISIBLE);
}
notesList.setLongClickable(true);
notesList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new android.app.AlertDialog.Builder(getContext())
.setTitle("Delete?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
list1.remove(position);
ParseUser.getCurrentUser().remove("notes");
ParseUser.getCurrentUser().put("notes", list1);
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getContext(), "Deleted", Toast.LENGTH_SHORT).show();
if (list1.toString().equals("[]")) {
emptyView.setVisibility(View.VISIBLE);
mPB.setVisibility(View.GONE);
} else {
notesList.setAdapter(arrayAdapter);
emptyView.setVisibility(View.INVISIBLE);
}
}
});
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
return true;
}
});
return rootView;
}
}