I have a piece of code to delete an Item in database. I am calling the same code from two different activities. So to avoid code repetition, I want to shift the code to the Application object. The code in one of the activities looks like this:
private void deleteItem() {
AlertDialog.Builder alert = new AlertDialog.Builder(Activity1.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DbHelper db = new DbHelper(Activity1.this);
AsyncTask<Long, Void, Object> deleteTask = new AsyncTask<Long, Void, Object>() {
@Override
protected Object doInBackground(Long... params) {
db.deleteItem(params[0]);
return null;
}
@Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
Now to put it in application object, I changed the function to public, gave it two parameters for input: Context and rowID. But in the onPostExecute method of AsyncTask I have to close the activity. In the activity, I did this by finish(). How do I do it in this context? I have attached the code in application object also.
public void deleteItem(final Context context, final long rowID) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DbHelper db = new DbHelper(context);
AsyncTask<Long, Void, Object> deleteTask = new AsyncTask<Long, Void, Object>() {
@Override
protected Object doInBackground(Long... params) {
db.deleteItem(params[0]);
return null;
}
@Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
I think that what you are trying to do is fundamentally not a good idea.
Outside of the Activity code, there are no guarantees that the activity still exists – the memory manager may have cleaned it up, the user may have pressed Back etc.
The final design decision is up to you but I advise you to consider if this is really necessary.
A little redundancy is okay in my opinion if it leads to more program stability and reliability.