I have an app which has a MainActivity.
If its first launch, it launches an activity which displays a intro slider and if its not, it launches a MainWeatherActivity.
Here is the code from the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstStart = PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(PREF_KEY_FIRST_START, true);
Log.i("MainActivity", "firstStart = " + Boolean.toString(firstStart));
if (firstStart) {
Intent i = new Intent(this, MainIntroActivity.class);
startActivityForResult(i, REQUEST_CODE_INTRO);
}
startActivity(new Intent(this, MainWeatherActivity.class));
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_INTRO) {
if (resultCode == RESULT_OK) {
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putBoolean(PREF_KEY_FIRST_START, false)
.apply();
} else {
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putBoolean(PREF_KEY_FIRST_START, true)
.apply();
//User cancelled the intro so we'll finish this activity too.
finish();
}
}
}
When I open the app for the first time , user is supposed to see the MainIntroActivity and then the MainWeatherActivity.
But instead this code directly launches the MainWeatherActivity and when I press the back button it launches the MainIntroActivity.
Where have I gone wrong and How do I fix this?
MainIntroActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("MainIntroActivity","onCreate");
addSlide(new SlideFragmentBuilder()
.backgroundColor(R.color.colorPrimary)
.buttonsColor(R.color.colorAccent)
.neededPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
.image(agency.tango.materialintroscreen.R.drawable.ic_next)
.title("title 3")
.description("Description 3")
.build(),
new MessageButtonBehaviour(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMessage("We provide solutions to make you love your work");
}
}, "Work with love"));
}
MainWeatherActivity
LocationManager mLocationManager;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_weather);
Log.i("MainActivity","onCreate");
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(MainWeatherActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainWeatherActivity.this,"Successful. Latitude ="+Double.toString(latitude)+" Longitude = "+Double.toString(longitude),Toast.LENGTH_SHORT).show();
Log.i("MainActivity","Lat = "+latitude+", lon = "+ longitude);
}else{
Toast.makeText(MainWeatherActivity.this, "No Permission. Grant Permission to continue", Toast.LENGTH_SHORT).show();
}
}
EDIT :
I forgot to mention that both IntroActivity and MainActivity has a noHistory=true in the manifest file..
Hope the question is clear...
The call for starting activities is asynchronous. The behaviour you are seeing might be because of that.
Move the second call to the onActivityResult and to the else of the first if.
if (firstStart) {
Intent i = new Intent(this, MainIntroActivity.class);
startActivityForResult(i, REQUEST_CODE_INTRO);
} else {
startActivity(new Intent(this, MainWeatherActivity.class));
}
finish();
try replacing following code:
if (firstStart) {
Intent i = new Intent(this, MainIntroActivity.class);
startActivityForResult(i, REQUEST_CODE_INTRO);
}else{
startActivity(new Intent(this, MainWeatherActivity.class));
finish();
}
Related
I added a variable that pass form the first activity to the second one.
I want to use the info that has accepted from the first activity, at the new activity, and will save it on new double variable, display it as permanent on a textView.
Now, it appears only when I am clicking on the regular button that start the new activity.
As first step, I guess, I need to remove - "startActivity(intent1);".
How should I move on from here?
Java code:
First Activity (Name : settings.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public void onClick (View v){
Intent intent = new Intent(settings.this, WaitressRecord.class);
startActivity(intent);
}
protected void onClickWait (View v) {
//--- Casting & Converting EditText "etSalaryWaitress" to Double "doubleSW".
btnWaitress =(Button)findViewById(R.id.btnWaitress);
etSalaryWaitress = (EditText) findViewById(R.id.etSalaryWaitress);
doubleSW = Double.parseDouble(etSalaryWaitress.getText().toString());
//---Casting Radio Button(s).
rbPercentage = (RadioButton)findViewById(R.id.rbPercentage);
rbShekel = (RadioButton)findViewById(R.id.rbShekel);
if (doubleSW < 100 ) {
if (rbPercentage.isChecked()) {
HafrashaP = 1 - (doubleSW / 100.0);
strHafPer = String.valueOf(HafrashaP);
Toast.makeText(settings.this, strHafPer, Toast.LENGTH_SHORT).show();
// start the SecondActivity
Intent intent1 = new Intent(this, WaitressRecord.class);
intent1.putExtra(Intent.EXTRA_TEXT, strHafPer);
startActivity(intent1);
} else if (rbShekel.isChecked()) {
HafrashaS = -doubleSW;
strHafShek = String.valueOf(HafrashaS);
Toast.makeText(settings.this, strHafShek, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(settings.this, "לא הוזנה סוג ההפרשה", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(settings.this, "מספר שגוי", Toast.LENGTH_SHORT).show();
}
}
New Activity: (Name : WaitressRecord.java)
public class WaitressRecord extends AppCompatActivity {
String strHafPer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waitress_record);
// get the text from MainActivity
Intent intent1 = getIntent();
strHafPer = intent1.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(strHafPer);
}
}
//First Activity
Intent intent= new Intent(this, SecondActivity.class);
Bundle extra = new Bundle();
mBundle.putString(VARIABLE_KEY, value);
intent.putExtras(mBundle);
startActivity(intent);
//on the second Acitivty
intent intent = getIntent();
Bundle bundleExtra;
//Null Checking
if (intent != null ) {
bundleExtra = getIntent().getExtras();
// Be sure your check your "VARIABLE KEY SAME AS in THE FIRST ACTIVITY
String resultString = extras.getString("VARIABLE_KEY");
}
I have 2 Activity.
FirstActivity with 1 textView and 1 button, and
MainActivity with 4 checkBoxes, 1 textView and 1 button.
First Activity is the first activity which app show to user.
Layouts of my activities
On the FirstActivity i want to check how many checboxes are checked in the textView.
On the MainActivity all working fine, we can select checkboxes and textView show how many is checked. Adittionaly, state of checkboxes and state of textView is save into SharedPreference.
Now i describe my problem, i dont know how to show currently numbers of checked boxes in 1st activity in my app after launch.
I tried to use onActivityResult but i think i do this wrong, and this my button2 with double intent must be also wrong.
What i should fix here and how ?
I paste here code of my 2 Activities:
FirstActivity :
public class FirstActivity extends AppCompatActivity {
private static final String SHARED_PREFS_NAME = "abc";
private Button b1;
private TextView tv2;
private int number;
public static final int REQUEST_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
b1 = (Button)findViewById(R.id.b1);
tv2 = (TextView)findViewById(R.id.tv2) ;
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
tv2.setText(""+number);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
}
MainActivity :
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int numberOfTrue;
private TextView tv1;
private CheckBox cb1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox cb2,cb3,cb4;
Button b2;
b2 = (Button)findViewById(R.id.b2);
tv1 = (TextView)findViewById(R.id.tv1);
cb1 = (CheckBox)findViewById(R.id.cb1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.cb2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.cb3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.cb4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
loadVariable();
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private void saveVariable(int numberOfTrue){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key2", numberOfTrue);
editor.commit();
}
private void loadVariable(){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
int number = sharedPref.getInt("key2", 0);
tv1.setText(""+number);
numberOfTrue=number;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cb1:
saveInSp("cb1",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb2:
saveInSp("cb2",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb3:
saveInSp("cb3",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb4:
saveInSp("cb4",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
}
saveVariable(numberOfTrue);
loadVariable();
}
}
This one if definitely wrong.
Intent intent = new Intent(MainActivity.this, FirstActivity.class);
intent.putExtra("number", numberOfTrue);
startActivityForResult(intent,1);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
You need to left only second part of code. Like this:
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
And start your MainActivity like this:
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE); // This change is important.
And then do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
}
}
This way you'll receive number from MainActivity when it'll be closed. But if you want to read this value on FirstActivity start (without going to MainActivity, you need to store checked number in shared preferences and then get value in onCreate() method of FirstActivity.
Write into SharedPreferences in onActivityResult to insure that only "saved" checks will be saved.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
And then you can load your checked number in onCreate method of FirstActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
}
Update
Here you'r trying to get number from intent in onActivityResult. That's wrong, this way you'll always have number = 0 (default value). On activity result doesn't fill data into intent. All your data is in data variable passed in method.
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
You need to leave only this:
if (requestCode == REQUEST_CODE) { //also you need to check if result is RESULT_OK
number = data.getExtras().getInt("number");
tv2.setText(""+number);
saveNumberToSharedPrefs(number);
}
FirstActivity
Store values :
Intent intent = new Intent(getBaseContext(), Activity.class);
intent.putExtra("ID", sessionId);
startActivity(intent);
SecondActivity
Fetching Values:
String s = getIntent().getStringExtra("ID");
public static final int REQUEST_CODE = 100;
change on FirstActivity.java
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
add onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
Log.d("TAG","------"+data.getExtras().getInt("number"));
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
}
}
}
change on MainActivity.java
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("TAG","------"+numberOfTrue);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});
I have few activity files that contains almost same code as shown below. Well i have not included onDestroy and finish() method in all of my activity files, before moving forward i want to be sure of the code posted below.
public class Three extends AppCompatActivity {
Button forwardB,backwardB,homeB;
TextView textView2,textView4,textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
//Place advertisement here
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
//
//find widget by Id
forwardB = (Button) findViewById(R.id.forwardB);
backwardB = (Button) findViewById(R.id.backwardB);
homeB = (Button) findViewById(R.id.homeB);
textView2= (TextView) findViewById(R.id.textView2);
textView4 = (TextView) findViewById(R.id.textView4);
textView5 = (TextView) findViewById(R.id.textView5);
textView5.setText("3/50");
//set text inside textView3 and textView4
textView2.setText("Apfel");textView4.setText("apple");
//set on click listener for forward,backward and home button
forwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Two.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
homeB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
backwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Four.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
After running the application i found a serious issue with data,it looks like android keeps data in background. How can i avoid this?
Everytime i run app and check the data it seems to be increasing.
Well this is my MainActivity.java:
public class MainActivity extends Activity {
Button btnflashcards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//create widget ids that are usable forw rest of the code
btnflashcards = (Button) findViewById(R.id.btnflashcards);
}
//on flash card button click
public void findFlashCards(View v){
Intent i = new Intent(this, FlashCardSelection.class);
startActivity(i);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
You will need to explicitly clear the application's user data every time you exit the aplication or at any point of time you want to during the use of your app.
Use this: ActivityManager's clearApplicationUserData() method
As per documentation this will:
Permits an application to erase its own data from disk. This is
equivalent to the user choosing to clear the app's data from within
the device settings UI. It erases all dynamic data associated with the
app -- its private data and data in its private area on external
storage -- but does not remove the installed application itself, nor
any OBB files.
Give something like this a shot
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle *) {
super.onCreate(*);
setContentView(R.layout.main);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
Hi I'm new in Android Development.
I have doing a lot of research .
Everything go rights however there is no any output sound from the text I entered.
Did I miss out any important part ?
The following bellow is the coding :
public class SpeechTextActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
inputText = (EditText) findViewById(R.id.edit_speechText);
speakButton = (Button) findViewById(R.id.btn_speechOut);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(SpeechTextActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(SpeechTextActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(SpeechTextActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}
Just now I test in my tablet it work! But in my phone not workable =(
Change the implements OnInitListener to TextToSpeech.OnInitListener.
Try to unplug the USB cable from your phone before testing. TTS is recognized to encountered some issues in debug mode.
I have an application in which multiple activities are shown in a certain order, which can change based on events in the current activity. I have a "master" activity which manages which activities are shown. Each ativity is started with startActivityForResult() with a requestCode unique to that activity.
When the activity finsishes, I set the resultCode to a value which will have meaning to the master activity. In the master activity's onActivityResult method, I have a switch (requestCode), which will tell me which activity has returned, and in each case block I work with the resultCode to determine which activity to start next.
The problem I'm having, is that at times, seemingly randomly, the application behaves quite erratically, showing activities out of sequence.
I've been unable to replicate the issue while debugging, so all the information I have looks good, but the end users are constantly complaining about the erratic behaviour.
How can I test to see where the problem is?
The code from the master activity's onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Settings.SCREEN_UPDATE:
ShowActivity(LoginActivity.class, Settings.SCREEN_LOGIN);
break;
case Settings.SCREEN_LOGIN:
if (resultCode == RESULT_OK) {
Settings.CurrentReport = new Report();
Settings.CurrentReport.setUserId(data.getIntExtra("userId", -1));
selectStore();
} else {
finish();
}
break;
case Settings.SCREEN_PRODUCT: // Coming back from the product selection screen
if (resultCode == RESULT_OK) {
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (resultCode == RESULT_CANCELED){
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
}
break;
case Settings.SCREEN_ACTION: // Coming back from the action screen, regardless of result, show options screen.
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
break;
case Settings.SCREEN_OPTIONS: // All choices return result_ok. Check the "mode" extra
String mode = data.getStringExtra("mode");
processOption(mode);
break;
case Settings.SCREEN_SESSION:
if (resultCode == RESULT_CANCELED) {
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
} else if (resultCode == RESULT_OK ){
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
}
break;
} // switch (requestCode)
} // protected void onActivityResult(int requestCode, int resultCode, Intent data) {
private void processOption(String mode) {
if (mode.equals("select")) {
ShowActivity(ProductActivity.class, Settings.SCREEN_PRODUCT);
} else if (mode.equals("repeat")) {
Settings.CurrentReport.repeatItem();
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (mode.equals("session")) {
ShowActivity(SessionActivity.class, Settings.SCREEN_SESSION);
} else { // mode equals "end"
confirmFinish();
}
}
private void ShowActivity(Class cls, int requestCode) {
Intent activity = new Intent(this, cls);
startActivityForResult(activity, requestCode);
}
Then, the code from one of the other activities handling the finish() event:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.options);
Button btn;
btn = (Button)findViewById(R.id.btnSelect);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "select");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnRepeat);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "repeat");
setResult(RESULT_OK, intent);
finish();
}
});
btn.setEnabled(Settings.CurrentReport.hasPreviousItem());
btn = (Button)findViewById(R.id.btnSession);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "session");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnEnd);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "end");
setResult(RESULT_OK, intent);
finish();
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Intent i = getIntent();
i.putExtra("mode", "end");
setResult(RESULT_OK, i);
finish();
break;
}
return super.onKeyDown(keyCode, event);
}
Im just guessing, but maybe Intent intent = getIntent(); is causing the problems. You could try to replace it with Intent intent = new Intent();
getIntent() returns the intent that started the current activity and shouldn't be used as a result.