Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android switching activities

I have 2 activities. One called Login and another called ListDeals. Login has a form with a submit button which, when pressed, should switch our activity to ListDeals. This works.

However, in Logcat I don't get a message saying that the activity has started. Also, when in ListDeals, if the user presses the back button, both activities should be killed. I looked around and this is what I came up with:

public class Login extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_screen);

    Button submit=(Button)findViewById(R.id.submit);
    submit.setOnClickListener(onSubmit);
}

private View.OnClickListener onSubmit=new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        Intent myIntent=new Intent(view.getContext(),ListDeals.class );
        startActivityForResult(myIntent,0);

    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.login_screen, menu);
    return true;
}

@Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
    if(resultCode==2) {
        finish();
    } 
}

}

public class ListDeals extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.deals_list);
        System.out.println("starting activity");
    }

    @Override
    protected void onDestroy() {
        System.out.println("dude");
        setResult(2);
        super.onDestroy();


    }

    protected void onStop(){
        setResult(2);
        super.onStop();

    }

}

However, when I press the back button, It takes me back to the Login activity which is not what I want.

like image 363
Teererai Marange Avatar asked Jul 11 '12 21:07

Teererai Marange


1 Answers

In your click handler, onSubmit, just finish your login activity, like this. That way, it won't be on the activity stack, and as a result, pressing back from your other activity will bring the user back to where they started.

private View.OnClickListener onSubmit=new View.OnClickListener()
{
    @Override
    public void onClick(View view)
    {
        Intent myIntent=new Intent(view.getContext(),ListDeals.class);
        startActivity(myIntent);
        finish();
    }
};

Also, to address you second question, use the Log class methods, such as Log.i or Log.d for debug messages, those will show up in logcat.

like image 169
wsanville Avatar answered Sep 21 '22 04:09

wsanville