I have a problem with my code about back button. I've tried a lot of answers here in this site.
I have the mainActivity that calls a second activity with startActivityforResult. This second activity starts bluetooth and show a list of the bonded devices, but if I press the backbutton it stops the app with an error.
public class Main extends Activity implements OnSeekBarChangeListener{
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String address = data.getExtras().getString(BondedDevices.DEVICE_ADDRESS);
if (resultCode==Activity.RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Finalizando dispositivos pareados", Toast.LENGTH_SHORT).show();
return;
}
switch (requestCode) {
case DISPOSITIVOS_PAREADOS:
if(resultCode==Activity.RESULT_OK){
mConnectThread = new ConnectThread(address);
mConnectThread.start();
estado = EST_CONECTADO; //informa que esta conectado
atualizaEstado();
break;
}
return;
}
}
But when I am in the second activity, and try to back to the mainactivity just pressing the back button, I get an error on main activity and my app return an error:
public class BondedDevices extends ListActivity {
....
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(D) Log.e(TAG, "+++ ON BACK PRESSED +++");
setResult(Activity.RESULT_CANCELED);
this.finish();
}
or like this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
return true;
}
}
return false;
}
I have tried a lot of different code, but it still doesn't work. Please someone help me. Thank you.
you should call super.onBackPressed();
like this
#Override
public void onBackPressed() {
super.onBackPressed();
if(D) Log.e(TAG, "+++ ON BACK PRESSED +++");
setResult(Activity.RESULT_CANCELED);
this.finish();
}
When you return from the second Activity, you have not set an Intent as the data for the result in the back button case, yet the first thing you do before checking the value of resultCode for RESULT_CANCELED is try to obtain the address from the Intent, which is null so this will cause a NullPointerException.
You need to reorder the lines in your onActivityResult() to look more like this:
if (resultCode==Activity.RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Finalizando dispositivos pareados", Toast.LENGTH_SHORT).show();
return;
}
//Do this after checking for cancel
String address = data.getExtras().getString(BondedDevices.DEVICE_ADDRESS);
/* The rest of the existing code */
Also, you should NOT override BOTH the onBackPressed() and onKeyDown(), stick with one of them. You're only causing confusion about which code path gets called first. Even in the case where the result is set with a blank Intent, you will still get a NullPointerException in your existing code because the extras bundle of that Intent will still be null.
Related
I'm trying to get result back from an activity i'm starting. the problem is the setResult isn't working as it should :
wortinfo_editsave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
Intent intent = new Intent();
boolean neu = extras.getBoolean("neu");
if(neu)
{
db.insert_word(wortinfo_wort.getText().toString(),wortinfo_bedeutung.getText().toString(),wortinfo_beispiel.getText().toString(),wortinfo_type.getSelectedItem().toString(),0);
intent.putExtra("res",0);
setResult(100, intent);
finish();
}
else
{
db.update_word(edit_id,wortinfo_wort.getText().toString(),wortinfo_bedeutung.getText().toString(),wortinfo_beispiel.getText().toString(),wortinfo_type.getSelectedItem().toString(),0);
intent.putExtra("res",1);
setResult(100,intent);
finish();
}
}
}
});
i've traced the program multiple times and all conditions are working correctly but only in one instance(first one, neu==true), setResult causes onActivityResult() to be called. i also have another block of code that tries to set the result and finish the activity but all it does is close the activity without returning any result. i've also tried changing 100 to RESULT_OK or other random numbers but it hasn't worked:
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.edit_wort:
...
case R.id.delete_wort:
db.delete_wort(wortinfo_wort.getText().toString(), wortinfo_bedeutung.getText().toString());
Intent intent = new Intent();
intent.putExtra("res",2);
setResult(100,intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
i've read all the other questions about this but its a bit different since a part of the code isn't working while the if block above it works just fine.
I am having an activity with custom list view. In my list view there are two types of items, with different layout. On items there is a switch and when I turn off the switch I go to Activity A, and when I turn on the switch I go to Activity B.
Here is my code:
Switch enable = (Switch) rowView.findViewById(R.id.enable);
enable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Intent intentChange = new Intent(getContext(), ActivityA.class);
intentChange.putExtra(PROPERTY, "test1");
((Activity)getContext()).startActivityForResult(intentChange, 100);
} else {
Intent newIntent=newIntent(getContext(),ActivityB.class);
((Activity)getContext()).startActivityForResult(newIntent, 200);
}
}
});
In each of these activities I call this:
Intent changedIntent=new Intent();
changedLimitIntent.putExtra("changed",changed);
changedLimitIntent.putExtra("changedDesc","desc);
setResult(Activity.RESULT_OK,changedIntent);
finish();
In my activity with custom adapter I have this code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == ActivityA.REQUEST_CODE) {
....
} else if (requestCode == ActivityB.REQUEST_CODE) {
.....
}
}
}
This work OK for me, however, when I receive the result from Activity A or Activity B on the activity with custom list view, and when I click back button is how I have this activity as many times I wait for result from other activities on back stack. I don't know what the problem is. I don't like to have my activity as many times I wait for result from other activities.
I hope I was clear with my question.
Try this to launch new activity. Hope it will help you.
Activity_A.this.finish();
Intent intentSettings = new Intent(Activity_A.this, Activity_B.class);
intentSettings.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intentSettings);
So, I am currently trying to edit the Snake game that android's api provides. I am trying to make it so that after pressing menu->settings->resume, it would resume the game. However, instead of going all the way to resume, after I press settings, it quits and resumes from there. I am using Intents to resume the program.
public boolean onOptionsSelected(MenuItem menu){
switch(menu.getItemId()){
case R.id.settings:
Intent prefActivity = new Intent(this,MyPreferences.class);
startActivityForResult(prefActivity, KEY_RESUME_RESULT);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch(requestCode){
case KEY_RESUME_RESULT:
if(resultCode==RESULT_OK){
if(mSnakeView.getMode() == SnakeView.PAUSE)
this.mSnakeView.setMode(SnakeView.RUNNING);
}
}
}
This is in MyPreferences.class
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.snake_preferences);
resume = (Preference)findPreference(getString(R.string.key_resume));
onPreferenceTreeClick(this.getPreferenceScreen(),resume);
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferencescreen,Preference preference){
super.onPreferenceTreeClick(preferencescreen,preference);
Intent intent = new Intent();
if(preference == resume){
setResult(Activity.RESULT_OK,intent);
finish();
}
return true;
}
You're explicity calling the method that resumes the game inside onCreate(), which is probably why the game is resuming as soon as you launch settings. I'd suggest not using the method and instead setting up a click listener for your preference:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.snake_preferences);
resume = (Preference)findPreference(getString(R.string.key_resume));
resume.setOnPreferenceClickListener (new Preference.OnPreferenceClickListener()
{
#Override
public void onPreferenceClick(Preference preference)
{
setResult(Activity.RESULT_OK,intent);
finish();
}
});
}
Also, based on your code onOptionsSelected() doesn't explicitly pause the game (however the UI should be paused considering that onPause() will be called), you might want to look into that.
I want to pass a request code to a searchable activity, like startActivityForResult. But onSearchRequested and startSearch cannot be passed it. In below example, I assume that after pressing a menu icon, a Search dialog will be shown at the top of window and I will send the request code and query to the searchable activity.
private static final int SEARCH_REQUEST_CODE = 100;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case SEARCH_REQUEST_CODE:
// Something to do after finishing the searchable activity
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
// ...
case 2:
onSearchRequested(); // I want to pass SEARCH_REQUEST_CODE here!
return true;
// ...
}
}
I have read a tutorial of Search Interface in API Guides ( https://developer.android.com/guide/topics/search/search-dialog.html ) and the API reference. But, I cannot find out how to do this.
I have three Activities - A B and C, of which B is a Tab Activity.
Activity A is launched first, and B is launched from A. I finish Activity A when B is launched using this code
public void onStop() {
super.onStop();
this.finish();
}
Now I want to launch Activity C when back key is pressed in B.
I tried overriding back key using this code
#Override
public void onBackPressed() { this.getParent().onBackPressed();
}
This doesn't Help as the Parent Activity is finished while launching the Child Activity. What actually happens when I press back key is that the Activity exits to the Home screen.
I tried overriding the back key and setting an Intent to it
#Override
public void onBackPressed() {
Intent backIntent = new Intent();
backIntent.setClass(this, main.class);
startActivity(backIntent);
}
This also doesn't help me.
What could be a possible solution to this problem, How can I launch Activity C when back key is pressed ?
First you should not finish the activity A when Activity A stops this is completely wrong approach instead of it you have to finish activity when you start activity B.
For example
Intent i = new Intent(this, B.class);
startActivity(i);
finish();
Now you want to start the activity C when user press the back button so use the below code.
#Override
public void onBackPressed() {
Intent backIntent = new Intent(this, C.class);
startActivity(backIntent);
super.onBackPressed();
}
You have to override onKeyDown
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_BACK)
{
//Do your code here
}
return super.onKeyDown(keyCode, event);
}
}
This will be called when user pressed Device Hard Back Button.
To navigate to next activity:
StartActivity(new Intent(getApplicationContext(),main.class));
Override the below method and import event.....
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_BACK)
{
//Write your intent or other code here
}
return super.onKeyDown(keyCode, event);
}