nck
nck

Reputation: 2221

How can I reload an activity from a listview to update information of a database?

I'm trying to implement something like this:

example

I have a main class with a layout from where I get some data from the database and plot it as shown in the image (with another layout complex_list):

public class main_class extends Activity{
DatabaseHelper myDB;
ListView list;
protected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
myDB=new DatabaseHelper(this);
list = (ListView) findViewById(R.id.list);
Cursor res = myDB.getAllData();
    if (res.getCount()==0){
        Toast.makeText(this,R.string.nothing_found,Toast.LENGTH_LONG).show();
    }
else{
...
list.setAdapter(new listAdapter(..., this.getBaseContext()));
}

I've a class to implement the BaseAdapter:

class listAdapter extends BaseAdapter {
public View getView(final int position, View convertView, final ViewGroup parent) {

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
    View row;
    row = inflater.inflate(R.layout.complex_list, parent, false);
    ...
Delete = (Button) row.findViewById(R.id.delete_entry_list);
...
    Delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            deleteEntry(id[position]);
            Intent refresh = new Intent(context, main_class.class);
            refresh.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //I've added this line because otherwise I get an error an the app crashes.
            context.startActivity(refresh);
            //((Activity)context).finish();
        }
    });
    return (row);
}
public void deleteEntry (  int id){
    DatabaseHelper myDB = new DatabaseHelper(context);
    myDB.deleteData(Integer.toString(id));
}

What I'm trying to do is refreshing the whole activity once the delete button is pressed to see an updated version of the database.

What I've written does work, but when I press the return button in the phone it returns to the old image of the database instead of going to the menu from where I accessed to this activity.

I've been researching similar questions and the only solution I've found is to add the line which is commented:

//((Activity)context).finish();

But it makes my app crash with this error:

java.lang.ClassCastException: android.app.ContextImpl cannot be cast to android.app.Activity

Could anyone give me a hint of what I'm doing wrong or if there is an easier way to this?

Upvotes: 1

Views: 80

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191711

ClassCastException: android.app.ContextImpl cannot be cast to android.app.Activity

Probably starts from

list.setAdapter(new listAdapter(..., this.getBaseContext()));

You should use this in place of this.getBaseContext() there as Activity extends Context

Upvotes: 1

Related Questions