Update a TextView on resuming main activity - android

Friends in this code provided below, i want to refresh my text view upon resume from play intent. But whenever i try to define my textview out of OnCreate but inside my main class (after static int score), my app crashes.
public class MainProjectActivity extends Activity {
/** Called when the activity is first created. */
static int Score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Display Scores
final TextView displayScores = (TextView)findViewById(R.id.scoreDisplay);
displayScores.setText("Your Score : "+ Score);
//Play Game button activity
Button gameButton = (Button)findViewById(R.id.PlayButton);
gameButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
startActivity(play);
}
});

I'd start with adding super.onResume();:
#Override
protected void onResume(){
super.onResume();
// The rest
}
I would also remove that:
final TextView displayScores = (TextView)findViewById(R.id.scoreDisplay);
displayScores.setText("Your Score : "+ Score);
from onCreate,and add it to onResume() since every time onCreate is called, onResume is called as well.
also change from public to protected onResume()

try this:
public class MainProjectActivity extends Activity {
/** Called when the activity is first created. */
TextView displayScores;
static int Score = 0;
#Override
protected void onResume(){
super.onResume();
// code to update the date here
displayScores.setText("Your Score : "+ Score);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Display Scores
displayScores = (TextView)findViewById(R.id.scoreDisplay);
displayScores.setText("Your Score : "+ Score);
//Play Game button activity
Button gameButton = (Button)findViewById(R.id.PlayButton);
gameButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
startActivity(play);
}
});

#Override
protected void onResume() {
// TODO Auto-generated method stub
displayScores.setText("Your Score : "+ Score);
super.onResume();
}

Related

how to make image invisble in first activity when navigating from second activity to first activity

I have two imageviews in firstActivity(MainActivity) when i click signIn image then it moves to SignUp Activity...
here when i click on signUp image then again it will come to MainActivity..and here i have to make firstName image invisible..
public class MainActivity extends Activity {
ImageView firstName,signIn ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstName =(ImageView)findViewById(R.id.imageView1);
signIn =(ImageView)findViewById(R.id.imageView2);
signIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),SignUp.class);
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
String mm ="5";
Intent i= getIntent(); String s = i.getStringExtra("PrevAct");
if (mm ==s) {
firstName.setVisibility(View.GONE);
}
}
public class SignUp extends Activity {
ImageView signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
signUp =(ImageView)findViewById(R.id.imageView3);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("PrevAct","5");
startActivity(intent);
}
});
}}
While you try to launch the MainActivity Activity again, ensure that you re-use the same instance and not a new one for application better performance.
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("PrevAct","SignUP");
startActivity(intent);
Use a variable to check if the screen is rendered from SignUpActivity.
Intent i= getIntent();
String s = i.getExtra("PrevAct","NO");
Based on the String Value, you can decide to show/hide.
Please note that View.Invisible only hides the view from screen. But still it gets loaded and takes the space on screen. This is a bad UI implementation.
Therefore use View.GONE instead.
Your Source Code modified as below
public class MainActivity extends Activity {
ImageView firstName,signIn ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstName =(ImageView)findViewById(R.id.imageView1);
signIn =(ImageView)findViewById(R.id.imageView2);
signIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),SignUp.class);
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
firstName = (ImageView)findViewById(R.id.textView1);
{
Intent i= getIntent();
if(i!=null){
String s = i.getExtra("PrevAct","NO");
if(s.equalsIgnoreCase("SignUP"))
firstName.setVisibility(View.GONE);
}
else
firstName.setVisibility(View.Visible);
}
}
public class SignUp extends Activity {
ImageView signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
signUp =(ImageView)findViewById(R.id.imageView3);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("PrevAct","SignUP");
startActivity(intent);
}
});
}}
By clicking signIn image, use startActivityForResult to start your activity for signing up.
In signing up activity, use setResult and finish to return to login activity.
When returning to first activity, make firstName image invisible or gone as you like in onActivityResult.

Extended class calling function that should not be inherited

i have following problem:
I've made a simple android app that adds 1 to an integer every 1000 ms using a handler, and then display this integer.
The problem is that when i start another activity the same thing happens, which would be fine, if that was intended. The mentioned function is not called in the new activity and yet it seems to be. Please look over my code and show me where it went wrong..
MainActivity:
public class MainActivity extends ActionBarActivity {
protected TextView text;
protected int position;
private Handler handler = new Handler();
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
position=0;
SetButtonCLickListener();
counter();
}
protected void SetButtonCLickListener() {
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SwitchActivity();
}
});
}
private void counter() {
handler.removeCallbacks(count);
handler.postDelayed(count, 1000);
}
private Runnable count = new Runnable() {
public void run() {
i++;
text.setText("Count: " + i);
handler.postDelayed(count, 1000);
}
};
protected void SwitchActivity() {
if (position == 1) {
finish();
} else {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
}
SecondActivity
public class MainActivity2 extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
text = (TextView) findViewById(R.id.text);
SetButtonCLickListener();
position=1;
}
}
MainActivity2 has an onCreate() method. In the onCreate() method, you call super.onCreate(), which triggers the MainActivity implementation of onCreate(). The MainActivity implementation of onCreate() is where you are starting your counter thing, via its call to the counter() method. Hence, when MainActivity2 starts up, its onCreate() calls MainActivity's onCreate(), which calls counter().
My guess is that MainActivity2 should inherit from Activity, not from MainActivity.

Reset countdown timer in Android when switching between activities

Here I have 3 activities: A, B, and C. From Activity A When I click a button it will goes to Activity B. When Activity B loads the countdown timer will start. Again, when I click a button in Activity B it will go to Activity C. Here I Need a Help.
When Activity C starts I need the countdown timer from Activity B to resume.
Again I switch over from Activity C to Activity B the countdown timer should be resumed from Activity C.
Activity A
public class MainActivity extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.actone);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, Act_Two.class);
startActivity(intent);
}
});
}
}
Activity B
public class Act_Two extends Activity{
Button button;
public TextView textView1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.act_two);
textView1=(TextView) findViewById(R.id.textView1);
MyCount counter = new MyCount(61000,1000);
counter.start();
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.acttwo);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, Act_Three.class);
startActivity(intent);
}
});
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
//iFallApp app1 = new iFallApp();
#Override
public void onFinish() {
// TODO Auto-generated method stub
setContentView(R.layout.activity_main);
//textView1.setText("done");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
textView1.setText(Long.toString(millisUntilFinished/1000));
}
}
}
While switching between the activities, try to pass the current count down time with the help of Bundle.
You should save a value of your CountDownTimer in Activty B and stop the CountDownTimer (using the cancel() method) in Activty B's onPause and start that CountDownTimer with saved value in onResume of Activty B. something like (assuming this is an Activity B code):
#Override
public void onPause() {
// turning off the timer
isWihesCountUpdateTimerNeeded = false;
if (wihesCountUpdateTimer!=null)
wihesCountUpdateTimer.cancel();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
// resuming the timer
isWihesCountUpdateTimerNeeded = true;
totalWishesCount = SharedPrefsHelper.getTotalWishesCount(getActivity());
startWihesCountUpdateTimer();
}
// the timer increases some wishes count
private boolean isWihesCountUpdateTimerNeeded;
private CountDownTimer wihesCountUpdateTimer;
protected static final int wihesCountUpdateTimerDuration=5000;
protected int totalWishesCount;
private void startWihesCountUpdateTimer() {
wihesCountUpdateTimer = null;
if (!isWihesCountUpdateTimerNeeded)
return;
final int duration = wihesCountUpdateTimerDuration;
//Log.i(this, "startWihesCountUpdateTimer() duration: "+duration);
wihesCountUpdateTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisUntilFinished) {}
#Override
public void onFinish() {
totalWishesCount++;
SharedPrefsHelper.saveTotalWishesCount(getActivity(), totalWishesCount);
startWihesCountUpdateTimer();
}
}.start();
}

Keeping activity

How to keep the button activity on background/pause or something like this when i press the physical back button . I want this activity to set on when i press again the button.(to show me what did i paint in last activity);
MainActivity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSave=(Button)findViewById(R.id.buttonDraw);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(MainActivity.this,ButtonDraw.class));
}
});
}
ButtonDraw :
public class ButtonDraw extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(com.example.myfirstapp.R.layout.paintingfile);
BlackPixel blackPixel;
blackPixel = new BlackPixel(this);
setContentView(blackPixel);
blackPixel.requestFocus();
}
}
In your MainActivity include this method:-
#Override
public void onBackPressed() {
startActivity(new Intent(this,ButtonDraw.class));
finish(); // this line depends on you whether you want to finish the MainActivity or not.
}
The above method gives you control over the back button of android.

onRestoreInstanceState does not get called?

I am having a simple code where i want to know when does onRestoreInstanceState get called during program execution in android?
Please help me out.
Thanks in advance.
My first Activity is as follows
public class AbcActivity extends Activity {
Button b1;
EditText ed1;
Bundle b = new Bundle();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v("Tag", "inside oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.button1);
ed1 = (EditText) findViewById(R.id.editText1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.v("Tag", "inside onsave instance state");
outState.putString("key", ed1.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.v("Tag", "inside on restore instance state");
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
Log.v("tag", "inside if");
String str = savedInstanceState.getString("key");
ed1.setText("" + str);
}
}
}
my second activity code is as follows
public class SecondActivity extends Activity {
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v("Tag", "inside 2 oncreate");
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
back = (Button) findViewById(R.id.button1);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
AbcActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.v("Tag", "inside 2 onsave instance state");
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.v("Tag", "inside 2 on restore instance state");
super.onRestoreInstanceState(savedInstanceState);
}
}
As the documentation states:
This method is called after onStart() when the activity is being re-initialized from a previously saved state
...
This method is called between onStart() and onPostCreate(Bundle)
This is the case when your Activity is re-created after being killed by the system or after a configuration change, and it saved its state in onSaveInstanceState(Bundle) - which is always called before an Activity is killed.

Categories

Resources