Ok, this one is really tricky to me. The idea of this is a time log for EMS. You press a button by the action taken, and it logs the time for later use. I managed to figure out how to save the TextView into a string. Now, how on earth do I save the logTime1.setEnabled(false); so that on rotation or on leaving the activity, it restores it disabled? Eventually I will have another button beside it that will allow you to edit which will unlock the button. Here is the code.
public class TimeLog extends Activity{
boolean logTimeDis1=true;
Button logTime1;
String time1;
TextView ivTimeStamp;
int counter=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.time_log);
logTime1 = (Button) findViewById(R.id.logTime1);
ivTimeStamp = (TextView) findViewById(R.id.ivTimeStamp);
if(savedInstanceState != null) logTime1.setEnabled(savedInstanceState.getBoolean("logTimeDis1", true));
logTime1.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
time1 = new SimpleDateFormat("HH:mm", Locale.US).format(new Date());
ivTimeStamp.setText(time1);
logTime1.setEnabled(false);
logTimeDis1 = false;
return false;
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
counter++;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putString("ivTimeStamp", ivTimeStamp.getText().toString());
outState.putBoolean("logTimeDis1", logTimeDis1);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
ivTimeStamp.setText(savedInstanceState.getString("ivTimeStamp"));
}
}
So, in this line
if(savedInstanceState != null) logTime1.setEnabled(savedInstanceState.getBoolean("logTmeDis1", false));
you don't check if savedInstanceState contains logTmeDis1. Say, savedInstanceState is not null, but does not have logTmeDis1, you'll get false and your button locked. Actually, you don't have to check it in this case, just change false to true, and it should work correctly.
Related
Guys I am stuck in a problem with these two methods:-
When I change the orientation of device and set the text in edit text after retriving the text from bundle,it does't work.But the same code is working in onrestoreStoreInstante method.
Please have a look at my code:-
public class LifeCycleActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText user;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user=(EditText)findViewById(R.id.et_user);
if(savedInstanceState!=null){
String s =savedInstanceState.get("Key").toString();
user=(EditText)findViewById(R.id.et_user);
user.setText(savedInstanceState.get("Key").toString());
Toast.makeText(this, s,Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "onCreate",Toast.LENGTH_SHORT).show();
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(this, "onSaveInstanceState",Toast.LENGTH_SHORT).show();
outState.putString("Key", "Deepak");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//String s =savedInstanceState.get("Key").toString();
//user.setText(s);
Toast.makeText(this, "onRestoreInstanceState",Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart",Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "onResume",Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(this, "onPause",Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(this, "onStop",Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "onDEstroy",Toast.LENGTH_SHORT).show();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Toast.makeText(this, "onRestart",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(LifeCycleActivity.this,SecondActivity.class));
}
}
when I set the text in edit text in oncreate method after getting the value from Bundle,it doesn't work.But the same code works in onRestoreInstanceState() method.
According to me , it should work for oncreate also as we can get the Bundle class object there.
Please help me to sort out this problem..
EditText and most of other views have their own methods to save/restore their own data. So in general it's not necessary to save/restore them on your code.
You can see this here on the Android TextView source code (remember that EditText extends from TextView) on line 3546:
if (ss.text != null) {
setText(ss.text);
}
so the reason you can't set it onCreate and can do it onRestoreInstanceState it's because during your activity super.onRestoreInstanceState(savedInstanceState) the activity calls the EditText.onRestoreInstanceState and the EditText restore it self to the previous value.
You can see it happening on the Activity source code on line 940
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (mWindow != null) {
Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
if (windowState != null) {
mWindow.restoreHierarchyState(windowState);
}
}
}
hope it helps.
Overview
onSaveInstanceState() is used to put the data to bundle
onRestoreInstanceState() is used to set the data available in
bundle to your activity
So do as follows:
i Guess until the activity is created onorientation change the
bundle is not available, that's way you are not able to retrieve it
in oncreate
Let the activity create in oncreate
Then restore the instance in onRestoreInstanceState
Hope this helps !
I am integrating Game Circle SDK & Whisper Sync in my game. I have implemented the code, but it has caused an issue. When I load the game and get the game state from the WhisperSync and set my local variables, white patches are observed in some places randomly instead of the proper image. When I turn of GameCircle & Whisper Sync it runs fine.
My game is developed using Cocos2d Android.
Does any one encountered such issue?
I have attached the image for reference.
Some Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
CCGLSurfaceView _glSurfaceView = new CCGLSurfaceView(this);
setContentView(_glSurfaceView);
CCDirector.sharedDirector().attachInView(_glSurfaceView);
CCDirector.sharedDirector().setDisplayFPS(false);
CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
CCScene scene = IntroLayer.scene();
CCDirector.sharedDirector().runWithScene(scene);
}
#Override
public void onResume() {
super.onResume();
if (IS_AMAZON) {
AmazonGamesClient.initialize(this, callback, myGameFeatures);
AmazonGamesClient.getWhispersyncClient()
.setWhispersyncEventListener(
new WhispersyncEventListener() {
#Override
public void onAlreadySynchronized() {
// TODO Auto-generated method stub
super.onAlreadySynchronized();
System.out
.println("FA here onAlreadySynchronized");
loadGameScene();
}
#Override
public void onDataUploadedToCloud() {
// TODO Auto-generated method stub
super.onDataUploadedToCloud();
System.out
.println("FA here onDataUploadedToCloud");
}
#Override
public void onDiskWriteComplete() {
// TODO Auto-generated method stub
super.onDiskWriteComplete();
System.out
.println("FA here onDiskWriteComplete");
}
#Override
public void onFirstSynchronize() {
// TODO Auto-generated method stub
super.onFirstSynchronize();
System.out
.println("FA here onFirstSynchronize");
loadGameScene();
}
#Override
public void onNewCloudData() {
// TODO Auto-generated method stub
super.onNewCloudData();
System.out
.println("FA here onNewCloudData");
}
#Override
public void onSyncFailed(FailReason reason) {
// TODO Auto-generated method stub
super.onSyncFailed(reason);
System.out
.println("FA here onSyncFailed reason: "
+ reason.name());
}
#Override
public void onThrottled() {
// TODO Auto-generated method stub
super.onThrottled();
System.out.println("FA here onThrottled");
}
});
Log.i(TAG, "onResume: call initiateGetUserIdRequest");
PurchasingManager.initiateGetUserIdRequest();
Log.i(TAG, "onResume: call initiateItemDataRequest for skus: "
+ LAppInfo.getInstance().getList());
Set<String> skus = new HashSet<String>(LAppInfo.getInstance()
.getList());
PurchasingManager.initiateItemDataRequest(skus);
}
CCDirector.sharedDirector().resume();
}
private AmazonGamesCallback callback = new AmazonGamesCallback() {
#Override
public void onServiceNotReady(AmazonGamesStatus status) {
// unable to use service
System.out.println("FA here callback onServiceNotReady: "
+ status.name());
}
#Override
public void onServiceReady(AmazonGamesClient amazonGamesClient) {
System.out.println("FA here callback onServiceReady: ");
agsClient = amazonGamesClient;
}
};
private void loadGameScene() {
LoadData();
CCScene mainMenu = LevelMenuScene.scene();
CCDirector.sharedDirector().replaceScene(
CCFadeTransition.transition(0.5f, mainMenu));
}
Solved it by a work around by having a boolean variable and set it to true after the data is loaded in firstsync/alreadysync method. and loading the scene in the main thread instead of the callback of whispersync. Will be glad to know if some one find a proper solution.
hi i have a menu activity that contains 4 buttons when i press button one the second
activity is open and.i added a back button in second activity to come back to activity
one(menu)how would it perform through code can any one help
private ListView lv;
public static ArrayList<String> your_array_list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
lv = (ListView) findViewById(R.id.listView1);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, your_array_list );
lv.setAdapter(arrayAdapter);
try {
DisplayM.main();
} catch (Exception e) {
e.printStackTrace();
}
// if (ViewClass.theEnd)
// your_array_list.add(ViewClass.methods);
int lst = 0;
for(int i=0; i<lst; i++)
{
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
this is my listview activity
Use below code in your back button
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
YourActivity.this.finish();
}
});
Write below code on your activity :-
#Override
public void onBackPressed()
{
// TODO Auto-generated method stub
super.onBackPressed();
}
or
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
or
#Override
public void onBackPressed()
{
// TODO Auto-generated method stub
// if u want to go specific activity then use this code
Intent intent = new Intent(this, YourMainActivity.class);
startActivity(intent);
finish();
}
In your second Activity on your Back Button onClick simply finish() the current (second/third ...) activity. This is what the default back button also does
in pause button you have to just call finish() method and then after finishing current activity it return to parent activity
i try to stop my sound in pressing back or home put it not work pleaze help me
this is the code
the sound play but i want the method to stop in pressing back or home.
public class Youcha3 extends Activity {
MediaPlayer mysound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youcha3);
Button btsound=(Button)findViewById(R.id.dou3aa);
btsound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mysound=MediaPlayer.create(Youcha3.this, R.raw.dou3aa );
if (mysound.isPlaying()) {
mysound.pause();
mysound.release();
}
else{
mysound.start();
}
}
});
}
Try to add this code in your Activity.
#Override
protected void onStop() {
if (mysound != null && mysound.isPlaying()) {
mysound.stop();
}
super.onPause();
}
i think this may help you.
try this
// back button press
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (mysound != null && mysound.isPlaying()) {
mysound.stop();
}
super.onBackPressed();
}
// home button press
#Override
public void onAttachedToWindow() {
// TODO Auto-generated method stub
if (mysound != null && mysound.isPlaying()) {
mysound.stop();
}
super.onAttachedToWindow();
}
I am new in android. I write a program that ball moves via accelerometer sensor and this good works. I use Timer and schedule method for this(schedule(mTimerTask, delay,period);) I have two buttons in my screen and i want when user click in positive button, period and delay value increases and when clicked in negative button, these values decreases. I write this code but the changes values in onClick method not fix in onResume method. I know onResume method called as a part of the life cycle but i dont know how can i solve my problem! please help me :) thanks
public class MainActivity extends Activity {
float result=0;
BallView ball=null;
Handler redrawHandler=new Handler();
//
Timer mTimer;
TimerTask mTimerTask;
//
int mSrcWidth,mSrcHeight;
PointF mBallPos,mBallSpd;
//
Button positiveBtn;
Button negativeBtn;
//
int delay=10;
int period=10;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
positiveBtn=(Button)findViewById(R.id.positiveBtn);
negativeBtn=(Button)findViewById(R.id.negativeBtn);
Log.e("onclick", "in oncreate");
getWindow().setFlags(0xFFFFFFFF, LayoutParams.FLAG_FULLSCREEN|LayoutParams.FLAG_KEEP_SCREEN_ON);
final FrameLayout frame=(FrameLayout)findViewById(R.id.main_view);
//
Display display=getWindowManager().getDefaultDisplay();
mSrcWidth=display.getWidth();
mSrcHeight=display.getHeight();
mBallPos=new PointF();
mBallSpd=new PointF();
mBallPos.x=mSrcWidth/2;
mBallPos.y=mSrcHeight/2;
mBallSpd.x=0;
mBallSpd.y=0;
ball=new BallView(this,mBallPos.x,mBallPos.y,10);
frame.addView(ball);
//
ball.invalidate();
positiveBtn.setOnClickListener(onClickListener);
negativeBtn.setOnClickListener(onClickListener);
SensorManager sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(new SensorEventListener(){
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
//
mBallSpd.x=-event.values[0];
mBallSpd.y=event.values[1];
}
//
},sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0), SensorManager.SENSOR_DELAY_NORMAL);
Log.e("onclick", "in onsensor");
}
private OnClickListener onClickListener=new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.negativeBtn:
if(delay<=5&&period<=5)
delay=period=5;
else{
delay=delay-10;
period=period-10;
}
break;
case R.id.positiveBtn:
if(delay>=50&&period>=50)
delay=period=150;
else{
delay=delay+10;
period=period+10;
}
break;
}
Log.e("delay","="+ delay);
Log.e("period","="+ period);
}
} ;
#Override
public void onPause(){
mTimer.cancel();
mTimer=null;
mTimerTask=null;
super.onPause();
}
#Override
public void onResume(){
mTimer=new Timer();
mTimerTask=new TimerTask(){
public void run(){
//Log.e("in ", "onResume()");
//positiveBtn.setOnClickListener(onClickListener);
//negativeBtn.setOnClickListener(onClickListener);
mBallPos.x+=mBallSpd.x;
mBallPos.y+=mBallSpd.y;
if(mBallPos.x>=mSrcWidth)
mBallPos.x=mSrcWidth;
if(mBallPos.y>=mSrcHeight)
mBallPos.y=mSrcHeight;
if(mBallPos.x<=0)
mBallPos.x=0;
if(mBallPos.y<=0)
mBallPos.y=0;
ball.x=mBallPos.x;
ball.y=mBallPos.y;
redrawHandler.post(new Runnable(){
public void run() {
// TODO Auto-generated method stub
ball.invalidate();
}
});
}
};
mTimer.schedule(mTimerTask, delay,period);
super.onResume();
}
Implement onSaveInstanceState like so:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt("STATE_DELAY", delay);
savedInstanceState.putInt("STATE_PERIOD", period);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and then inside your onCreate try to restore them (if they have been set) like so:
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
delay = savedInstanceState.getInt("STATE_DELAY");
period = savedInstanceState.getInt("STATE_PERIOD");
}
And finally as I wrote in the comments of the question have a look at the Recreating an Activity training page.