How to reset class variable to default value 0? - java

If anybody can tell me different way to do this, I would appreciate. How to reset class variable to 0, or default value? I use class variable cause I don't know another way to do this. After my game ends I place result in class variable, cause I have two rounds of my game, and after first round ends I add the result, and class variable is good for this cause even after I restart my game method it still holds my previous result. After second round is over I add that result to previous result and then close the activity and set text result as text to a button. But when I click New game, that button still holds that text, cause class variable still holds it. How to reset that class variable when I go on New game?
Here's my game code, some of it (100 points are start amount, and it gets lower in game progress):
public class Asocijacije extends Activity implements OnClickListener{
int brojPoenaAsocijacije = 100;
public static int brojPoenaUkupno;
Then I skip here a lot of code and here's where I add points. brojPoenaAsocijacije are points earned in that round:
brojPoenaUkupno = brojPoenaUkupno + brojPoenaAsocijacije;
Here's my main activity where I set points from my class variable to a button (where I added comment):
public class Izbor extends Activity implements OnClickListener{
Asocijacije poeni = new Asocijacije();
Button toploHladno, asocijacije, cigle, spojnice, nazad, poeniTH, poeniAso, poeniCigle, poeniSpojnice;
TextView naslov;
public boolean music;
MediaPlayer buttonClicks, buttonBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.izbor);
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
music = getPrefs.getBoolean("checkbox", true);
addListenerOnButton();
}
private void addListenerOnButton() {
buttonClicks = MediaPlayer.create(this, R.raw.click);
buttonBack = MediaPlayer.create(this, R.raw.button31);
Typeface naslovType = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
naslov = (TextView) findViewById(R.id.tvIzborNaslov);
toploHladno = (Button) findViewById(R.id.bIzbor1);
asocijacije = (Button) findViewById(R.id.bIzbor2);
cigle = (Button) findViewById(R.id.bIzbor3);
spojnice = (Button) findViewById(R.id.bIzbor4);
nazad = (Button) findViewById(R.id.bIzborNazad);
poeniTH = (Button) findViewById(R.id.bPoeniTH);
poeniAso = (Button) findViewById(R.id.bPoeniAso);
poeniCigle = (Button) findViewById(R.id.bPoeniCigle);
poeniSpojnice = (Button) findViewById(R.id.bPoeniSpojnice);
naslov.setTypeface(naslovType);
toploHladno.setTypeface(dugmad);
asocijacije.setTypeface(dugmad);
cigle.setTypeface(dugmad);
spojnice.setTypeface(dugmad);
nazad.setTypeface(dugmad);
poeniAso.setTypeface(dugmad);
toploHladno.setOnClickListener(this);
asocijacije.setOnClickListener(this);
cigle.setOnClickListener(this);
spojnice.setOnClickListener(this);
nazad.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
poeniAso.setText("" + poeni.brojPoenaUkupno); //I do it here
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bIzbor1:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.GAME"));
break;
case R.id.bIzbor2:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.ASOCIJACIJE"));
break;
case R.id.bIzbor3:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzbor4:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzborNazad:
if(music == true){
buttonBack.start();
}
poeniAso.setText("");
finish();
break;
}
}
}

Because I don't find the piece of code where you start the new game, I can only say:
Asocijacije.brojPoenaUkupno = 0;

Probably want to reset your state when you close the in-game activity.
#Override
protected void onDestroy() {
super.onDestroy();
Asocijacije.brojPoenaUkupno = 0;
//whatever other things need to be reset.
}

Related

Using a button with the code inside of a different class

I am trying to make an app and I have the code for a button inside of a different class. When I start my app and click the first button it brings me to a different layout where the button is located. But when I click this button it doesn't do anything, just the little click down animation.
First Button Code:
public class TextAdd extends AppCompatActivity {
public static EditText Text;
public static Button Set;
public static String[] Checkagainst = new String[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Text_Checker);
Text = (EditText) findViewById(R.id.LPN);
Set = (Button) findViewById(R.id.Set);
Set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Text_Value = Text.getText().toString();
if (!Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.add);
for (int i = 0; i < Checkagainst.length; i++) {
if (Checkagainst[i] == null) {
Checkagainst[i] = Text_Value;
break;
}
}
} else if (Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.have);
}
}
});
}
}
Second Button Code:
public class Have extends AppCompatActivity {
private Button HaveBack;
private TextView Have;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.have);
HaveBack = (Button) findViewById(R.id.HaveBack);
Have= (TextView) findViewById(R.id.Have);
String Text_Value= TextAdd.License.getText().toString();
String Extra = Text_Value + " is already part of Your license plates";
Have.setText(Extra);
HaveBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.Text_Checker);
}
});
}
}
Does anyone know what is wrong? If so can you please help me.
You should use setContentView() only once in your onCreate() method. Calling it multiple times is not correct. If you want to show a small layout above your current layout, you should use a Dialog and if you want to show a completely different layout above everything, you have to use Intents to go to another activity and do the rest of the work in that one.
besides, use lowercase letters at start of your variables' and objects' names and start Class names with Uppercase letters. That's the standard for knowing what is a class and what is an object. e.g.
Button firstButton, secondButton;

Android memory leak on device, not on emulator

I'm writing a game to help teach my son some phonics: it's my first attempt at programming in Java, although I've previously used other languages. The game has four activities: a splash screen which initializes an array of variables before you dismiss it; another to choose a user; a third to choose which level of the game to play; and a fourth to actually play the game.
My problem was that if you go in and out of the game activity repeatedly, that activity would eventually crash -- logcat showed an OOM error. Watching the heap size as I did this, and looking at a heap dump with MAT, it looked as though I was leaking the whole of the fourth activity -- GC was just not being triggered.
I've tried lots of things to track down and fix the leak -- most of which are, I'm sure improvements (e.g. getting rid of all non-static inner classes from that activity) without fixing the problem. However, I've just tried running the same thing on an emulator (same target and API as my device) and there's no leak -- heap size goes up and down, GC is regularly triggered, it doesn't crash.
So I was going to post the code for the activity on here and ask for help spotting what might be causing the leak, but I'm no longer sure that's the right question. Instead I'm wondering why it works on the emulator, but not the phone... Does anyone have any ideas?
IDE: Android Studio 2.1
Target: Android 6, API 23 (Minimum SDK 8)
Emulator: Android Studio
Device: Sony Xperia Z2 (Now running 6.0.1, but I had the same issue pre recent update, i.e. on API 22)
Code for the activity:
public class GameActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
//TTS Object
private static TextToSpeech myTTS;
//TTS status check code
private int MY_DATA_CHECK_CODE = 0;
//LevelChooser request code
public static Context gameContext;
private int level;
public static String user;
private Typeface chinacat;
public static Activity gameActivity = null;
private static int[] goldstars = {R.drawable.goldstar1, R.drawable.goldstar2, R.drawable.goldstar3};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gameActivity = this;
gameContext = this;
level = getIntent().getIntExtra("level", 1);
user = getIntent().getStringExtra("user");
chinacat = Typeface.createFromAsset(getAssets(), "fonts/chinrg__.ttf");
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
#Override
public void onStop() {
if (myTTS != null) {
myTTS.stop();
}
super.onStop();
}
#Override
public void onDestroy() {
if (myTTS != null) {
myTTS.shutdown();
}
Button ok_button = (Button) findViewById(R.id.button);
ok_button.setOnClickListener(null);
ImageView tickImageView = (ImageView) findViewById(R.id.tickImageView);
tickImageView.setOnClickListener(null);
super.onDestroy();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
myTTS = new TextToSpeech(this, this);
} else {
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
public void onInit(int initStatus) {
//if tts initialized, load layout and level and assign listeners for layout elements
if (initStatus == TextToSpeech.SUCCESS) {
myTTS.setLanguage(Locale.ENGLISH);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
PhonemeGroup levelGroup = MainActivity.gamelevel[level]; //set possible words
levelGroup.setSubset(); //randomize subset of possible words for actual test
PhonicsWord[] testSet = levelGroup.getSubset(); //fill array of test words
TextView[] targetView = new TextView[3]; //textviews for beginning, middle & end of word
targetView[0] = (TextView) findViewById(R.id.targetWord0);
targetView[1] = (TextView) findViewById(R.id.targetWord1);
targetView[2] = (TextView) findViewById(R.id.targetWord2);
TextView[] answersView = new TextView[3]; //textviews for possible user answer choices
answersView[0] = (TextView) findViewById(R.id.letter0);
answersView[1] = (TextView) findViewById(R.id.letter1);
answersView[2] = (TextView) findViewById(R.id.letter2);
//set first target word, image for word, and possible answers
testSet[0].setWord(levelGroup, targetView, answersView, imageView);
testSet[0].speakWord(myTTS);
//subset index is equal to array index for testSet, but visible to & settable by methods
levelGroup.setSubsetIndex(0);
for(int i=0; i<3; i++) {
answersView[i].setTypeface(chinacat);
}
TextView letter0 = (TextView) findViewById(R.id.letter0);
letter0.setOnClickListener(new LetterOnClickListener(testSet, levelGroup, targetView, answersView, 0) );
TextView letter1 = (TextView) findViewById(R.id.letter1);
letter1.setOnClickListener(new LetterOnClickListener(testSet, levelGroup, targetView, answersView, 1) );
TextView letter2 = (TextView) findViewById(R.id.letter2);
letter2.setOnClickListener(new LetterOnClickListener(testSet, levelGroup, targetView, answersView, 2) );
Button ok_button = (Button) findViewById(R.id.button);
ok_button.setOnClickListener(new OKButtonOnClickListener(testSet, levelGroup, targetView, level) );
ImageView tickImageView = (ImageView) findViewById(R.id.tickImageView);
tickImageView.setOnClickListener(new TickClick(myTTS, testSet, levelGroup, targetView, answersView, imageView) );
imageView.setOnClickListener(new WordImageClick(testSet, levelGroup) );
}
/*else if TODO*/
}
private static class WordImageClick implements View.OnClickListener {
//speaks the test word when the test image is clicked
PhonicsWord[] testSet;
PhonemeGroup levelGroup;
public WordImageClick(PhonicsWord[] testSet, PhonemeGroup levelGroup) {
this.testSet = testSet;
this.levelGroup = levelGroup;
}
#Override
public void onClick(View view) {
testSet[levelGroup.getSubsetIndex()].speakWord(myTTS);
}
}
private static class LetterOnClickListener implements View.OnClickListener {
PhonemeGroup levelGroup;
PhonicsWord currentWord;
PhonicsWord[] testSet;
TextView[] targetView;
TextView[] answersView;
int item;
int phonemeclicked;
public LetterOnClickListener(PhonicsWord[] testSet, PhonemeGroup levelGroup, TextView[] targetView, TextView[] answersView, int phonemeclicked) {
this.testSet = testSet;
this.levelGroup = levelGroup;
this.targetView = targetView;
this.answersView = answersView;
this.phonemeclicked = phonemeclicked;
}
#Override
public void onClick(View view) {
this.item = this.levelGroup.getSubsetIndex();
this.currentWord = this.testSet[item];
int i = currentWord.getOmit_index();
targetView[i].setText(answersView[phonemeclicked].getText());
}
}
private void crossClick(View view) {
view.setVisibility(View.INVISIBLE);
if(view.getTag()==4){
finish();
}
}
The static variable gameActivity is used so that when you've finished a level an external class can call GameActivity.gameActivity.finish() after it's displayed how many stars you've got for the level (it's also used to call GameActivity.gameActivity.findViewById in another external class).
public class ShowStarsWithDelay extends Handler {
public void handleMessage(Message msg) {
ImageView starView = (ImageView) ((LevelEndScreens) msg.obj).starView;
ImageView highscoreView = (ImageView) ((LevelEndScreens) msg.obj).highscoreView;
int num_currentstars = (int) ((LevelEndScreens) msg.obj).num_currentstars;
int num_finalstars = (int) ((LevelEndScreens) msg.obj).num_finalstars;
Boolean highscore = (Boolean) ((LevelEndScreens) msg.obj).highscore;
int[] goldstars = (int[])((LevelEndScreens) msg.obj).goldstars;
if(num_currentstars == num_finalstars) {
if(!highscore) {
starView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GameActivity.gameActivity.finish();
}
});
}
else {
highscoreView.setImageResource(R.drawable.highscore);
highscoreView.setVisibility(View.VISIBLE);
highscoreView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GameActivity.gameActivity.finish();
}
});
}
}
else {
starView.setImageResource(goldstars[num_currentstars++]);
Message message = new Message();
LevelEndScreens endScreens = new LevelEndScreens(starView, highscoreView, num_currentstars, num_finalstars, highscore, goldstars);
message.obj = endScreens;
this.sendMessageDelayed(message, 1000);
}
}
}
In general, you want to avoid having any static reference to a Context anywhere in your application (this includes Activity classes, of course). The only reference to a Context which MAY be acceptable is referencing the application context (as there is only one and it is always in memory while your app is alive anyway).
If you need a reference to the calling activity in one of your children, you'll need to pass the context as a parameter, or else use one of the child views methods to retrieve the context (such as getContext() for views and fragments).
More information that should help understand memory leaks and why this is important is here:
http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html
As an example, in your code for calling finish(), you could safely change it to this:
highscoreView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getContext() instanceof Activity) {
((Activity)v.getContext()).finish();
}
}
});
To sum up, in order to fix your memory leaks, you'll need to remove the static keyword for all of your Context fields.

Press a Button just one time

I'm trying to press the first button just one time. This button usually return a random card but I want it just one time. Then the button should be inactive. How can I do that?
That's my code:
public class GameActivity extends Activity {
Boolean buttonPressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final Button background = (Button) findViewById(R.id.A);
Resources res = getResources();
final TypedArray Deck = res.obtainTypedArray(R.array.Deck);
final Random random = new Random();
if (!buttonPressed){
buttonPressed = true;
background.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Genrate a random index in the range
int randomInt = random.nextInt(Deck.length()-1);
// Generate the drawableID from the randomInt
int drawableID = Deck.getResourceId(randomInt, -1);
background.setBackgroundResource(drawableID);
}
});
you can disable your button with (place it inside your onClick)
background.setEnabled(false);
and you also might initialize your button to true in onCreate method
If the player has an action to do next, the simpler way is to deactivate the button when is pressed first time and after in the next action activated again.
You can do this adding
background.setEnabled(false);
in your anonymous class listener and after add
background.setEnabled(true);
in player's next action.

How to create a scoreboard with a textview, 2 variables and a button in java for Android

I know this is a simpleton question, but I am not going to school for java, just learning it online.
how to a have a textview with an initial value of 0. and then everytime you press a button it ads 25 points to the score board.
At first I wanted the button press to add a random number between 42-57 to the score board.
And then how to do convert that int or long to a string to make it fit into a textview and keep the current score, and then add a new score.
EDIT: ok so someone said I should post the code so here it is.. where do i put this..
TextView txv182 = (TextView) findViewById(R.id.welcome);
txv182.setText(toString(finalScore));
Because when I do it, I get an error: The method toString() in the type Object is not applicable for the arguments (int)
public class MainActivity extends Activity {
// Create the Chartboost object
private Chartboost cb;
MediaPlayer mp = new MediaPlayer();
SoundPool sp;
int counter;
int db1 = 0;
Button bdub1;
TextView txv182;
int finalScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv182 = (TextView) findViewById(R.id.welcome);
finalScore = 100;
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
db1 = sp.load(this, R.raw.snd1, 1);
bdub1 = (Button) findViewById(R.id.b4DUB1);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (db1 != 0)
sp.play(db1, 1, 1, 0, 0, 1);
txv182.setText(finalScore);
}
});
First you need to store your score to certain integer variable say score and set it to any initial value you want and use.
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(toString(score));
you do not need to initialize the textview with value just in onclick() of button do score+=25and add text to your textview as above.
hope this helps
It's actually like this..
pernts+=25;
txv182.setText(String.valueOf(pernts));
in android, after the
public class MainActivity extends Activity {
but before..
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i wrote..
int pernts;
String strI;
so then after the above #Override majigy, i wrote..
strI = "" + pernts;
pernts = 0;
because when i wrote it like.. int pernts = 0; it never worked, forcing me to add final and what not..
any way.. How to convert an integer value to string? anSwered the question..
and so the end was like this
pernts+=25;
txv182.setText(String.valueOf(pernts));
i figured out you have to add a value to the int variable not the string.. i kept wanting to add 25 and i was getting 25252525252525.., instead of 25 50 75 100.. kinda cool actually.. separating the logic of how to "add" 25 .. anyway thanks.. SOF!
30 minutes later... found this.. How can I generate random number in specific range in Android?
..
import android.app.Activity;
public class InsMenu extends Activity {
static TextView txv182;
static int pernts;
Button bdub1;
public static void addPernts() {
int min = 37;
int max = 77;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
pernts+=i1;
txv182.setText(String.valueOf(pernts));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.BLAHBLAH);
bdub1 = (Button) findViewById(R.id.b4DUB1);
txv182 = (TextView) findViewById(R.id.welcome);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPernts();
}
--- i created my first objekt thanks to this too.. http://www.tutorialspoint.com/java/java_methods.htm ..

How to reload an activity with previous state saved?

I have a game activity and using an sqlite database I populate some buttons, randomly without repetition, and when the game gets finished I popup an alert dialog with OK button an some info. Now, I need when I press OK, to close that popup and in that game activity reload some other data to my buttons, without repetition. This I need to happen twice. I do this in my other game but that popup does not have OK button, it pops up for 3 seconds and using handler closes and my activity reloads with new data without repetition, and that works like a charm. In this game, only OK button is a difference, and it does not work. And I need that OK button. Two problems I have with this.
I successfuly reload my activity but with repetition, which tells me that my activity loads from scratch.
When the activity loads for the second time, when I press back button I can see previous game activity, which again tells me that I get one activity loaded twice. I only need it once with new data every time.
Also, my counter does not work, cause after second load, I get 3rd, 4th and so on.
Here are my game and popup activity:
public class ToploHladno extends Activity implements View.OnClickListener{
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, bIzlaz, bDalje;
String mButtonText1, mButtonText2, mButtonText3, mButtonText4, mButtonText5, mButtonText6,
mButtonText7, mButtonText8, mButtonText9, mButtonText10, opis, odgovorNormalized;
MediaPlayer buttonClicks, buttonFinal, buttonBack;
public boolean music;
final Context context = this;
Editable ukucanRezultat;
String tacanRezultat, ukucanRezultatVelikaSlova;
int brojPoena;
int counter = 0;
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
addListenerOnButton();
nextQuestion();
}
private void addListenerOnButton() {
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
bIzlaz = (Button) findViewById(R.id.bIzlaz);
bDalje = (Button) findViewById(R.id.bDalje);
}
public void nextQuestion() {
counter++;
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{
mDbHelper.open();
Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
mButtonText1 = c.getString(2);
mButtonText2 = c.getString(3);
mButtonText3 = c.getString(4);
mButtonText4 = c.getString(5);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
if(counter < 3){
b1.setText("30 poena");
b2.setText("25 poena");
b3.setText("22 poena");
b4.setText("20 poena");
}else{
finish();
}
}
finally{
mDbHelper.close();
}
}
Popup:
public class Popup_opis extends Activity implements OnClickListener{
TextView tvOpis;
int brojPoenaPrimljeno;
Button OK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_opis);
initVariables();
}
private void initVariables() {
OK = (Button) findViewById(R.id.bOK);
tvOpis = (TextView) findViewById(R.id.tvOpis);
OK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
Intent intent = new Intent(Popup_opis.this, ToploHladno.class);
//intent.putExtra("myMethod", "nextQuestion"); //I tried also this
startActivity(intent);
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
If I understand you correctly, you are restarting your ToploHladno Activity from your Popup_opis Activity using an Intent. If the ToploHladno Activity hasn't been finished, which I don't think it has been, then no need for Intent. You can call invalidate() on the Views that you want to be repopulated in onResume() after calling setText() on them or whatever changes you need to make to those Views
#Override
public void onResume()
{
// change your Buttons however you need in here then say you have btn1
btn1.invalidate();
}
Your first Activity isn't being finished so you don't need or probably even want to start it with an Intent. You will just return to it after closing your Dialog Activity and onResume() will be called so you can do what you need in there. This will keep you from redrawing the whole Layout by not creating a new instance of your Activity.Let me know if this works for what you need or not
Invalidate
startActivityForResult() example:
Intent intent = new Intent(ToploHladno .this, Popup_opis .class);
intent.putExtra("counter", counter);
startActivityForResult( intent, 0 ); //second param is a request code. You will need this later
then in pop up activity
public class Popup_opis extends Activity implements OnClickListener{
TextView tvOpis;
int brojPoenaPrimljeno;
Button OK;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_opis);
//Get intent
Intent recIntent = getIntent();
counter = recIntent.getIntExtra("counter"); //get counter variable from previous activity
OK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
counter++;
Intent intent = new Intent(Popup_opis.this, ToploHladno.class);
intent.putExtra("counter", counter); //SEND BACK COUNTER
setResult(RESULT_OK, intent); // send result
finish();
then in your previous activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// would use REQUEST CODE sent earlier if more than one activity sends back intents here
if (resultCode == RESULT_OK)
{
counter = data.getInteExtra("counter", 0); // get updated counter variable
}
}
More about startActivityForResult in Docs

Categories