Denis
Denis

Reputation: 1201

Go back to previous activity manually

Here's my code: Activity1 (main): Checks if the db has any rows. If not, load the main view. If it has at least 1 start Activity2

    int num = db.numOfRows();
    if(num==0){
        setContentView(R.layout.main);
    } else {
        startActivity(new Intent(this, Activity2.class));
    }

Activity 2: Loads the moreprojects view which populates table rows with db information.

        super.onCreate(savedInstanceState);
        setContentView(R.layout.moreprojects);
        populateRows();

non-activity dbhandler: contains all the database stuff (db mentioned in Activity1). Now, on Activity2 you can delete the rows which calls the method below. Within that if(num==0) I would like to have Activity2 call Activity1. Activity1 is the screen which allows for creating of projects.

public void deleteContact(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_blah, KEY_ID + " = ?",
            new String[] { String.valueOf(id) });
    int num = numOfRows();
    Log.d("Testing","Number of rows: "+num);

    if(num ==0){
        //go back to Activity1
    }
    db.close();
}

I hope this makes sense.

I've been trying multiple different things such as: creating a method in activity2 which does finish();... but that doesn't do anything. It just seems to reload Activity2.

Please help!

Upvotes: 1

Views: 951

Answers (4)

Mouna Cheikhna
Mouna Cheikhna

Reputation: 39678

Calling finish should go back since you opened activity2 using startActivity and not startActivityForResult :

public void deleteContact(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_blah, KEY_ID + " = ?",
            new String[] { String.valueOf(id) });
    int num = numOfRows();
    Log.d("Testing","Number of rows: "+num);

    if(num ==0){
        finish();
    }
    db.close();
}

this supposes that deleteContact is in Activity2

EDIT :

calling finish will only call Activity1's onResume method i guess
To go back to Activity1 and restart it you can :

finish();
startActivity(new Intent(this, Activity1.class));

check android's activity life cycle

Upvotes: 2

FoamyGuy
FoamyGuy

Reputation: 46856

finish();

should do the trick. If that is "reloading activity2" then I would add some log statements to both Activities that will print out your num variable. My guess is that somehow num is 0 in Activity2, but num is somehow being > 0 when Activity1 takes focus, which would then re-launch Activity2 because of your if statement.

Upvotes: 0

stefan bachert
stefan bachert

Reputation: 9624

Just call finish on your activity. Than is goes back to the caller

Upvotes: 0

DGomez
DGomez

Reputation: 1480

When you wanna finish Activity A and back to Activity 2 just call finish(); in A , and that will work

Upvotes: 0

Related Questions