How to delete custom listview row - java

I am trying to delete a row or any row while by clicking on my custom listview adapter which extends Baseadapter. I have found many solutions on Google but none of them worked for me.I am successfully generating a listview with the help of this class but can't delete a row or any row.
Here is my code
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.BaseAdapter;
import com.brl.loverfreedatingapp.R;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class WhoLikedMeAdapter extends BaseAdapter {
private Context context; //context
private ArrayList<String> masterID = new ArrayList<String>();
private ArrayList<String> slaveID = new ArrayList<String>();
private ArrayList<String> masterName = new ArrayList<String>();
private ArrayList<String> slaveName = new ArrayList<String>();
private ArrayList<String> slaveUrl = new ArrayList<String>();
public WhoLikedMeAdapter(Context context, ArrayList<String> masterID, ArrayList<String> slaveID, ArrayList<String> masterName, ArrayList<String> slaveName, ArrayList<String> slaveUrl) {
this.context = context;
this.masterID = masterID;
this.slaveID = slaveID;
this.masterName = masterName;
this.slaveName = slaveName;
this.slaveUrl = slaveUrl;
}
#Override
public int getCount() {
return masterID.size(); //returns total of items in the list
}
#Override
public Object getItem(int position) {
return masterID.get(position); //returns list item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// inflate the layout for each list row
if (convertView == null) {
convertView = LayoutInflater.from(context).
inflate(R.layout.wholikeme_row, parent, false);
}
CircleImageView profile_image = (CircleImageView) convertView.findViewById(R.id.profile_image);
TextView name = (TextView)convertView.findViewById(R.id.name);
ImageButton unlike = (ImageButton)convertView.findViewById(R.id.unlike);
ImageButton like = (ImageButton)convertView.findViewById(R.id.like);
name.setText(slaveName.get(position));
//--
if(slaveUrl.get(position).equals("")){
Picasso.with(context)
.load(R.drawable.image_placeholder)
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}else {
Picasso.with(context)
.load(slaveUrl.get(position))
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}
//-------------
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
unlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
// returns the view for the current row
return convertView;
}
}

Found the solution! I have to remove all the data in a row to remove a listview row. Previously I was trying with only 1 data (masterID).
masterID.remove(position);
slaveID.remove(position);
masterName.remove(position);
slaveName.remove(position);
slaveUrl.remove(position);
notifyDataSetChanged();

Related

How to know the index of the item of the list, on which the button was clicked

So I am working on a list view, and I want to implement a delete button. But for some reason, whenever I press the delete button on any list item whatsoever, the last item in the list gets deleted automatically. I tried out almost everything, but I am unable to understand how I can know the index of the item where the button was clicked so I can easily just delete that particular item.
This is the code :
// full subtask adapter code
package com.example.taskmasterv3;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskAdapter extends ArrayAdapter<subtask> {
private final Context context;
private ArrayList<subtask> values;
public SubtaskAdapter(Context context, ArrayList<subtask> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.subtask_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvSubtaskName);
ImageView ivPri = convertView.findViewById(R.id.ivPri);
ImageView ivTime = convertView.findViewById(R.id.ivTime);
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).isPriHigh()) {
ivPri.setImageResource(R.drawable.priority_high);
} else if (values.get(position).isPriMed()) {
ivPri.setImageResource(R.drawable.priority_med);
} else if (values.get(position).isPriLow()) {
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).isTimeMore()) {
ivTime.setImageResource(R.drawable.time_symbol_more);
} else if (values.get(position).isTimeMed()) {
ivTime.setImageResource(R.drawable.time_symbol_med);
} else if (values.get(position).isTimeLess()) {
ivTime.setImageResource(R.drawable.time_symbol_less);
}
// Delete button for subtasks (NOT WORKING)
ivDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SubtaskAdapter.this.remove(SubtaskAdapter.this.getItem(position));
notifyDataSetChanged();
}
});
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(subtask newSubTask){
ArrayList<subtask> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
ivDelete.setOnClickListener(new View.OnClickListener() {
Change that to:
ivDelete.setOnClickListener(new View.OnClickListener() {
ivDelete.setTag(position);
public void onClick(View v) {
Change to:
public void onClick(View v) {
// int position = v.getTag();
int position = (Integer)v.getTag();
Try to use below code :
ivDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values .remove(position);
notifyDataSetChanged();
//SubtaskAdapter.this.remove(SubtaskAdapter.this.getItem(position));
//notifyDataSetChanged();
}
});

Click on one card view affected another card view value

When I create a custom card view in recycler view and click the increment button counter work properply. But when I crete another cardview then already created card counter value reset to 0. How to solve this issue?
Here's my Main Activity code
package com.example.muhasbaapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.example.muhasbaapp.CustomAdapter.ViewHolder.*;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter mAdapter,countAdapter;
private RecyclerView.LayoutManager layoutManager,layoutManager2;
private static RecyclerView recyclerView,recyclerView2;
private ImageView imageView;
public CustomModel customModel;
public static ArrayList<String> input = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView2=(RecyclerView)findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
recyclerView2.setHasFixedSize(true);
layoutManager2=new LinearLayoutManager(this);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView2.setItemAnimator(new DefaultItemAnimator());
mAdapter= new CustomAdapter(input);
recyclerView2.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { //add action2 kau kat sini
switch (item.getItemId()) {
case R.id.action_item_1:
openCustomDialoge();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openCustomDialoge() {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.user_generated_cards, null);
final EditText editText = (EditText) dialogView.findViewById(R.id.edt_comment);
Button button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
Button button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s=editText.getText().toString();
if (s.isEmpty()){
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
}else {
input.add(s);
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
dialogBuilder.setView(dialogView);
dialogBuilder.show();
}
}
And Here' my Adaptar Class code
package com.example.muhasbaapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
public ArrayList<String> values;
final CustomModel customMdl=new CustomModel();
final MainActivity mainActivity=new MainActivity();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tv;
public View layout;
public TextView counter_value;
public ImageView increment,decrement, deleted;
public int counter;
public ViewHolder(View v) {
super(v);
layout = v;
tv = (TextView) v.findViewById(R.id.textViewName);
counter_value=(TextView) v.findViewById(R.id.counter);
increment=(ImageView)v.findViewById(R.id.increment);
decrement=(ImageView)v.findViewById(R.id.decrement);
deleted=(ImageView)v.findViewById(R.id.delbtn);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
// Provide a suitable constructor (depends on the kind of dataset)
public CustomAdapter(ArrayList<String> myDataset) {
this.values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.custom_cards_layout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.tv.setText(name);
final int[] counter={0};
holder.deleted.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
}
});
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter[0] == 0) {
Toast.makeText(v.getContext(), "Can't add less than 0", Toast.LENGTH_SHORT).show();
} else {
counter[0] -= 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
}
});
holder.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.decrement.setEnabled(true);
counter[0] += 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
If anyone knows this problem please inform me.
Thanks in advance
Well, I'm seeing some bad practices in your code:
Adapters hosted in main activity must be not static, what do you think if try accessing via recyclerView.getAdapter()
Please remove the next one in your adapter
final MainActivity mainActivity = new MainActivity();
So the problem that you are having is inside your click listener.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = editText.getText().toString();
if (s.isEmpty()) {
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
} else {
input.add(s); // <-------------- HERE
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
You add the new item to the array, however, the adapter never knows that there is a new item has been added.
Access to the instanced adapter which has been attached to RecyclerView in onCreate() step and update their data.

How to refresh or update a fragment after deleting from the database

I am new to android development, and i'm trying to build a simple hymn book,
I'm using bottom navigation, i use fragments on each tab to display numbers and titles of each hymn.
In my favourite fragments i have a list of favourite songs displayed using recycler view fetch from the database.
I use on long click listener to delete songs from the favorite table in the database, but any time i delete a
song my favorite fragment doesn't get refreshed or undated with current items. Please, how can I refresh or update
my favourite fragment anytime i delete a song. thank you!
'''Favourite Adapter''
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.ViewHolder> {
private Context favContext;
private ArrayList<String> favNumbers = new ArrayList<>();
private ArrayList<String> favTitles = new ArrayList<>();
public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles) {
this.favContext = favContext;
this.favNumbers = favNumbers;
this.favTitles = favTitles;
}
#Override
public FavouriteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favourite_list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final FavouriteAdapter.ViewHolder holder, final int position) {
holder.textViewFavNum.setText(favNumbers.get(position));
holder.textViewFavTitle.setText(favTitles.get(position));
final String hymn_no = favNumbers.get(position);
holder.itemView.setTag(favNumbers.get(position));
holder.favParentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i;
i = new Intent(view.getContext(), Songs.class);
i.putExtra("numId", favNumbers.get(position));
i.putExtra("titleName", favTitles.get(position));
favContext.startActivity(i);
}
});
holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete from favorites?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
try{
SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);
favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");
Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
#Override
public int getItemCount() {
return favNumbers.size();
}
#Override
public long getItemId(int position){
return position;
}
#Override
public int getItemViewType(int position){
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewFavNum;
public TextView textViewFavTitle;
RelativeLayout favParentLayout;
public ViewHolder(View itemView) {
super(itemView);
textViewFavNum = (TextView) itemView.findViewById(R.id.textViewFavNum);
textViewFavTitle = (TextView) itemView.findViewById(R.id.textViewFavTitle);
favParentLayout = (RelativeLayout) itemView.findViewById(R.id.favParentLayout);
}
}
}
'''favourite fragment'''
import android.app.FragmentManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.logging.Handler;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {#link Fragment} subclass.
*/
public class Favourites extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<String> favSongNumbers = new ArrayList<>();
private ArrayList<String> favSongTitles = new ArrayList<>();
private TextView favMessage;
public Favourites() {
// Required empty public constructor
}
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(view == null) {
view = inflater.inflate(R.layout.fragment_favourites, container, false);
favMessage = (TextView) view.findViewById(R.id.favMessage);
recyclerView = (RecyclerView) view.findViewById(R.id.favRecyclerView);
// adapter.setHasStableIds(true);
Toast.makeText(this.getActivity(), "Long press to delete hymns from favorites", Toast.LENGTH_LONG).show();
initFavSongs();
}
return view;
}
private void initFavSongs(){
try{
favMessage.setText("");
SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);
Cursor c = favHymns.rawQuery("SELECT hymnNum, hymnTitle FROM favorites", null);
int hymnNumIndex = c.getColumnIndex("hymnNum");
int hymnTitleIndex = c.getColumnIndex("hymnTitle");
if(c.moveToFirst()) {
while (c != null) {
favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
favSongTitles.add(" " + c.getString(hymnTitleIndex));
c.moveToNext();
}
}else{
favMessage.setText("Oops!No favorite songs added yet.");
}
}catch (Exception e){
e.printStackTrace();
}
initRecyclerView();
}
private void initRecyclerView(){
adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
}
}
Pass a listener to the adapter and invoke it at the time of item delete from database. Then update your list and as well as your adapter.Like this way:
First create a listener:
public interface UpdateListener {
void onValueChangedListener();
}
Initialize the listener in Adapter class that comes from fragment.
private UpdateListener updateListener;
public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles,UpdateListener updateListener ) {
this.favContext = favContext;
this.favNumbers = favNumbers;
this.favTitles = favTitles;
this.updateListener=updateListener;
}
holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete from favorites?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
try{
SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);
favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");
Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
// when any item delete from database notify the fragment through this
// listener for updating your adapter
updateListener.onValueChangedListener();
}catch(Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
// this method is needed for updating your adapter
public void update(ArrayList<String> favNumbers, ArrayList<String> favTitles){
this.favNumbers = favNumbers;
this.favTitles = favTitles;
}
Implement the listener in your fragment and reinitialize your list.
public class Favourites extends Fragment implements UpdateListener {
private void initRecyclerView(){
// pass listener
adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles,this);
}
private void updateFavSongs(){
favSongNumbers.clear;
favSongTitles.clear;
try{
favMessage.setText("");
SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);
Cursor c = favHymns.rawQuery("SELECT hymnNum, hymnTitle FROM favorites", null);
int hymnNumIndex = c.getColumnIndex("hymnNum");
int hymnTitleIndex = c.getColumnIndex("hymnTitle");
if(c.moveToFirst()) {
while (c != null) {
favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
favSongTitles.add(" " + c.getString(hymnTitleIndex));
c.moveToNext();
}
}else{
favMessage.setText("Oops!No favorite songs added yet.");
}
}catch (Exception e){
e.printStackTrace();
}
adapter.update(favSongNumbers,favSongTitles);
adapter.notifyDataSetChanged()
}
#Override
public void onValueChangedListener(){
updateFavSongs();
}
}

Cannot make working ListView item delete action

I'm making some listview based app with ability to delete specific row with a button in it, like on screenshot below: Screenshot
Here are my classes:
MainActivity:
package com.example.patryk.notes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
LayoutInflater layoutInflater;
ArrayList<Item> itemList = new ArrayList<Item>();
ItemArrayAdapter itemArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemArrayAdapter = new ItemArrayAdapter(this, R.layout.list_item, itemList);
listView = (ListView) findViewById(R.id.item_list);
listView.setAdapter(itemArrayAdapter);
layoutInflater = getLayoutInflater();
ViewGroup footer = (ViewGroup) layoutInflater.inflate(R.layout.list_view_footer, listView, false);
listView.addFooterView(footer);
itemList.add(new Item("Item", 1));
}
public void addRow(View v) {
itemList.add(new Item("Item", itemList.size() + 1));
Log.d("add", "metoda add row");
itemArrayAdapter.notifyDataSetChanged();
}
}
ItemArrayAdapter
package com.example.patryk.notes;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by patryk on 04.01.2018.
*/
public class ItemArrayAdapter extends ArrayAdapter<Item> {
private int listItemLayout;
ImageButton deleteButton;
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Item item = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(listItemLayout,parent, false);
// viewHolder.item = (TextView) convertView.findViewById(R.id.row_item);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
deleteButton = (ImageButton) convertView.findViewById(R.id.xButtonID);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**here expected to do something**
}
});
return convertView;
}
private static class ViewHolder {
TextView item;
}
}
item
package com.example.patryk.notes;
/**
* Created by patryk on 04.01.2018.
*/
public class Item {
private String name;
private double value;
public Item(String name, double value) {
this.value = value;
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I've tried many ideas from Stack Overflow but always there has been my clue missing. Firstly I wanted to make delete action on OnclickListener method in ItemArrayAdapter class, but the problem was to access ArrayList "itemList" located in MainActivity class, so I couldn't perform itemList.remove(position).
On the other hand I wanted to make deleteRow method in MainActivity and attach it to delete button on ItemArrayAdapter class by adding android:onClick="deleteRow" tag, but that makes exception similar to that: IllegalStateException
I'd rather chose first idea, so I would like to know how to get access to this ArrayList within adapter class
cheers :)
Reference variable of ArrayList is send to the adapter class. So you can easily do this:
public class ItemArrayAdapter extends ArrayAdapter<Item> {
private int listItemLayout;
ImageButton deleteButton;
private ArrayList<Item> itemList;
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
this.itemList = itemList;
}
Then
deleteButton = (ImageButton) convertView.findViewById(R.id.xButtonID);
deleteButton.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) v.getTag();
itemList.remove(pos);
notifyDataSetChanged();
notifyDataSetInvalidated();
}
});
You don't need to access the MainActivity, item list is available in the constructor
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
}
You better assign to a variable and use it.
Like this
Private ArrayList <Item> itemList;
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
this.itemList = itemList
}
After remove please call notifytheDataSetChange method to refresh the list view.

Delete item from database and listview on button click

I'm trying to get an item deleted from both my custom listview and from the database on button click. I got so far but from the code below you are likely to see my error. When the first item is deleted the positions change however the idarray info is not updated. Please help!
History Adapter:
package uk.co.rascagneres.clocking_app;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Jacques on 08/08/2016.
*/
public class HistoryAdapter extends BaseAdapter implements ListAdapter{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public ArrayList<String> idArray = new ArrayList<String>();
DatabaseHandler db;
public HistoryAdapter (ArrayList<String> list, Context context, ArrayList<String> idArray, DatabaseHandler db){
this.list = list;
this.context = context;
this.idArray = idArray;
this.db = db;
}
#Override
public int getCount(){
return list.size();
}
#Override
public Object getItem(int pos){
return list.get(pos);
}
#Override
public long getItemId(int pos){
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.history_list, null);
}
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(list.get(position));
System.out.println(idArray.get(position));
System.out.print(idArray);
db.deleteRowID(Integer.parseInt(idArray.get(position)));
list.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
HistoryFragment:
package uk.co.rascagneres.clocking_app;
import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Jacques on 03/08/2016.
*/
public class HistoryFragment extends Fragment {
DatabaseHandler db;
View myView;
ArrayList<String> historyArray = new ArrayList<String>();
ArrayList<String> idArray = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.history_layout, container, false);
db = new DatabaseHandler(getActivity());
ArrayList<String> list = insertData();
HistoryAdapter adapter = new HistoryAdapter(list, getActivity(), idArray, db);
ListView lView = (ListView)myView.findViewById(R.id.listView);
lView.setAdapter(adapter);
return myView;
}
public ArrayList<String> insertData(){
Cursor c = db.getAllData();
ArrayList<String> list = new ArrayList<String>();
while(c.moveToNext()) {
int id = c.getInt(0);
long in = c.getLong(1);
long out = c.getLong(2);
String outTime;
if(out == 0){
outTime = "N/A";
}else{
outTime = ClockingFragment.getDate(out, "HH:mm");
}
String date = ClockingFragment.getDate(in, "EEE, MMM d");
String inTime = ClockingFragment.getDate(in, "HH:mm");
historyArray.add(date + "\n Clocked In: " + inTime + "\n Clocked Out: " + outTime + "\n");
idArray.add(String.valueOf(id));
}
if (historyArray.isEmpty()){
historyArray.add("No History Available!");
}
return historyArray;
}
public ArrayList<String> getIdArray(){
System.out.println(idArray);
return idArray;
}
}
Section of Database Handler:
public void deleteRowID(int ID)
{
SQLiteDatabase db = this.getWritableDatabase();
String IDString = String.valueOf(ID);
try
{
db.delete(TABLE_NAME, "ID = ?", new String[] { IDString });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}

Categories

Resources