This is My MainActivity
where I have defined dataRefresh
method that refreshes the adapter when data is inserted or deleted from the database
public class MainActivity extends AppCompatActivity {
EditText phone, name;
ListView list;
MyDatabase db;
CustomAdapter ad;
ArrayList<contact> cont;
Button add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=findViewById(R.id.list_item);
db=new MyDatabase(this);
cont=new ArrayList<>();
cont=db.showData();
ad=new CustomAdapter(this,cont;
list.setAdapter(ad);
}
public void dataRefresh(){
cont.clear();
cont.addAll(db.showData());
ad.notifyDataSetChanged();
}
above is a dataRefresh
method
This is My adapter class where I call the deletion method to delete data from the database
public class CustomAdapter extends ArrayAdapter {
ArrayList<contact> phnecontact;
MyDatabase db;
LinearLayout horizon;
Context context;
public CustomAdapter(@NonNull Context context, ArrayList<contact>
phonecontact) {
super(context,R.layout.customlayout,phonecontact);
this.context = context;
this.phnecontact = phonecontact;
}
public contact getItem(int position) {
return phnecontact.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@NonNull
@Override
public View getView(int position, View i, ViewGroup parent) {
View view =
LayoutInflater.from(context).inflate(R.layout.customlayout, parent,
false);
contact s1 = phnecontact.get(position);
db=new MyDatabase(context);
TextView name=view.findViewById(R.id.cmname);
horizont=view.findViewById(R.id.horizontal);
TextView number=view.findViewById(R.id.cmphone);
ImageView sms=view.findViewById(R.id.message);
ImageView call=view.findViewById(R.id.phone);
ImageView photo=view.findViewById(R.id.cmphoto);
number.setText(String.valueOf(s1.getPhone()));
name.setText(s1.getName());
horizont.setOnLongClickListener(v -> {
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle("Are you sure to delete");
builder.setPositiveButton("yes", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int i =db.Deletioncontact(s1.getPhone());
I want to call dataRefresh
method of Mainactivity after if condition
if(i==1)
{
Toast.makeText(context, "contact is deleted",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context, "contact not deleted",
Toast.LENGTH_SHORT).show();
}
}
});
If I call this method using an object of Mainactivity then my application is crashing