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.
Related
My application contains two activities :
First activity contains :
1.different types of modes
2.intensity
3.CCT
Inside of the if condition not going control.if am selecting the seekbar the it should return true.if it is true means should move to next activity.
can any one help me
mColorTemp = (SeekBar) findViewById(R.id.intensity1);
mScheduler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean swichAction=false;
if(mColorTemp.isSelected()==true){
swichAction=true;
Intent intent = new Intent(mContext, SchedulerActivity.class);
intent.putExtra("swichAction",swichAction);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
Along with this i have button named as Scheduler.
Now am not selecting anyone from first activity and press on the scheduler then it will move to the second activity.In the second activity should show labeled switch on to auto.
If am selecting anyone from first activity then should turn to Manual
Second Activity contains :
Labeled switch in that text contains Auto/Manual
Can any one please help me how to do it.
You can't use mColorTemp.isSelected() to do that. Instead, you has to plug a listener on value changed. If value is changed by user, manual mode can be activated.
mColorTemp.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mManualActivated = true;
}
}
Then, you can use Extras to pass variables from an Activity to another.
How to "put"
Intent intent = new Intent(mContext, SchedulerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
intent.putExtra("extra_mode", mManualActivated);
startActivity(intent);
Then, to retrieve the value, add this in the SchedulerActivity.onCreate() :
Boolean manualActivated = false;
Bundle extras = getIntent().getExtras();
if(extras != null) {
manualActivated = extras.getBoolean("extra_mode");
}
I'm struggling to allow the users to leave my app using the back button after logout.
My HomeActivity checks that the user has a sessionID. if they don't it will redirect them to the login page. upon successful login the homepage is displayed showing the sessionID and a logout button.
Clicking on the button removes the session ID and displays a message to the user to that effect. Pressing the back button at this point takes the user to the login page, and I can't get off it by pressing back - I can login and press back to leave the app, but I can't quit using the back button after logout.
Any Ideas?
HomeActivity
public class HomeActivity extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
protected void onStart(){
super.onStart();
/*
* Check if a session ID exists - if it does then display the home screen
* If the session ID does not exist then redirect the user to the login page.
*/
String sessionId = Session.getSessionId(getApplicationContext());
if (StringUtils.isBlank(sessionId)){
navigateToLoginActivity();
}
// Display the Home Screen
setContentView(R.layout.home);
TextView tv = (TextView)findViewById(R.id.welcome);
tv.setText(sessionId);
}
public void logout(View view){
navigateToLogoutActivity();
}
public void navigateToLoginActivity(){
Intent loginIntent = new Intent(getApplicationContext(),LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
public void navigateToLogoutActivity(){
Intent logoutIntent = new Intent(getApplicationContext(),LogoutActivity.class);
logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(logoutIntent);
}
}
LoginActivity
public class LoginActivity extends Activity {
EditText nfcET;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
nfcET = (EditText)findViewById(R.id.nfckey);
}
public void login(View view){
String nfckey = nfcET.getText().toString();
RequestParams params = new RequestParams();
params.put("nfckey", nfckey);
invokeWS(params);
}
public void invokeWS(RequestParams params){
// REMOVED WEBSERVICE CODE - calls webservice and retrieves a sessionID which is saved in a SharedPreference, it calls navigateToHomeActivity upon successful login
}
public void navigatetoHomeActivity(){
Intent homeIntent = new Intent(getApplicationContext(),HomeActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
}
LogoutActivity
public class LogoutActivity extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Session.removeSessionId(getApplicationContext());
if (!StringUtils.isBlank(Session.getSessionId(getApplicationContext()))){
//TODO - Handle the case that the session was not removed!
} else {
setContentView(R.layout.logout);
}
}
}
This is the part where you are having difficulties:
if (StringUtils.isBlank(sessionId)){
navigateToLoginActivity();
}
Whenever you need to go out of the app by clicking the back button, it's the home page which will always be visited last. And because homepage will always check if you are logged in or not, and redirect you to the login page in case of the latter, you are really stuck and real time ;)
override the key down event:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode){
case KeyEvent.KEYCODE_BACK:
// do something here
// Here you can put your boolean variable
isOutOfApp = true;
return true;
}
return super.onKeyDown(keyCode, event);
}
and here can do:
if (StringUtils.isBlank(sessionId)){
if(isOutOfApp) {
// show a confirmation message
// and out of the app
} else {
navigateToLoginActivity();
}
}
To get out of the loop, ask the LoginActivity to log you in and return whether or not it was successful using startActivtyForResult like this:
In HomeActivity:
Change the navigateToLoginActivity to look like this:
public void navigateToLoginActivity(){
Intent loginIntent = new Intent(getApplicationContext(),LoginActivity.class);
startActivityForResult(loginIntent, REQ_LOG_IN);
}
In LoginActivity:
Add this to your onCreate:
setResult(RESULT_CANCELED);
Alter your navigatetoHomeActivity to this:
public void navigatetoHomeActivity(){
setResult(RESULT_OK);
finish();
}
Back in HomeActviity:
Move this block to onResume() (because onActivityResult is called before onResume)
/*
* Check if a session ID exists - if it does then display the home screen
* If the session ID does not exist then redirect the user to the login page.
*/
String sessionId = Session.getSessionId(getApplicationContext());
if (StringUtils.isBlank(sessionId)){
navigateToLoginActivity();
}
Add this method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_LOGIN && resultCode == RESULT_CANCELED){
finish();
}
}
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.
I have a requirement of having a activity as dialog (Not an Alert dialog, instead a progress dialog). There are no ui components in this activity since this activity does server interaction, based on server response next activities are started. Only a progress dialog with cancel button needs to be shown in this activity. Now the problem is when ever this activity is launched just before progress dialog is displayed a small black rectanagle is visible for a second or more, also when this activity is finished this is visible. How to get rid of this ? or is there any better way of haveing a progress dialog as activity ?
-Thanks & regards,
Manju
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityAsDialogActivity.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
String str ="Hellow World";
txtView = (TextView)findViewById(R.id.txtview);
this.setFinishOnTouchOutside(false);
txtView.setText(R.string.select_dialog);
ActivityAsDialogActivity.this.setTitle(R.string.app_name);
mProgressHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mProgress >= MAX_PROGRESS) {
mProgressDialog.dismiss();
Intent intent = new Intent(ActivityAsDialogActivity.this, ActivityOne.class);
startActivity(intent);
finish();
} else {
mProgress++;
mProgressDialog.incrementProgressBy(1);
mProgressHandler.sendEmptyMessageDelayed(0, 100);
}
}
};//end of handler
showDialog(DIALOG_PROGRESS);
mProgressDialog.setProgress(0);
mProgressHandler.sendEmptyMessage(0);
}//end of onCreate()
#Override
public void onBackPressed(){
Log.d("Manju ==>"," back key pressed");
finish();
}
#Override
public void finish(){
Log.d("Manju ==>", " inside finish()");
super.finish();
}
In Creating Global Dialog, I used a transparent activity with a dialog inside. I think you can do the same thing. I do not recall facing the problem you are facing, and it worked perfectly.
Check it out
Android 2.1 via eclipse
I have an activity that opens a dialog themed activity via checkbox onChecked function
Im creating this new dialog themed activity with an Intent.
Problem is, how do i dismiss the dialog themed activity once i finish with it? (the way it stands now, i have to send a new intent in order to go back to the previous activity via click of a button)
Any help would be greatly apprieciated!
Code snippet:
Main activity:
cbReminder.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
Intent intent = new Intent(getApplicationContext(), DateTimeDialog.class);
startActivity(intent);
}
}
});
Dialog themed activity:
public void onClick(View v) {
if (v.getId() == R.id.b_datetime_save)
{
}
else if (v.getId() == R.id.b_datetime_cancel)
{
finish();
Intent intent = new Intent(getApplicationContext(), MakeNoteActivity.class);
startActivity(intent);
}
}
As you specified, the intent was indeed not needed to return to the previous activity and should be removed.
To uncheck the checkbox after returning from the dialog, you can use startActivityForResult and set a callback for when you return.
Open your dialog like this:
Intent intent = new Intent( getApplicationContext(), DateTimeDialog.class );
startActivityForResult( intent, UNIQUE_IDENTIFIER );
Then add a callback to that same activity:
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data )
{
if ( requestCode == UNIQUE_IDENTIFIER )
{
cbReminder.setChecked( false );
}
}
The UNIQUE_IDENTIFIER can be any number that uniquely identifies this dialog. Let me know if you have any more questions.