savedInstanceState causing a crash while screen rotation - java

public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE="com.example.ferhat.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN="com.example.ferhat.geoquiz.answer_shown";
private static final String CHEATER="com.example.ferhat.geoquiz.cheated";
private Boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mIsCheater;
public static Intent newIntent(Context packageContext, boolean answerIsTrue){
Intent i=new Intent(packageContext,CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE,answerIsTrue);
return i;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
//Cevabı gösteriyor ve Kopya çekildi bilgisi veriliyor
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
mIsCheater=true;
setAnswerShownResult();
}
});
if(savedInstanceState!=null){
mIsCheater=savedInstanceState.getBoolean(CHEATER,false);
}
}
private void setAnswerShownResult(){
Intent data=new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN,mIsCheater);
setResult(RESULT_OK,data);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(CHEATER,mIsCheater);
}
}
I try to solve challenge in Anroid Programming, Big Nerds Ranch Guide (Chap.5)
Challenge asks me to keep Cheat data while rotation of screen and transaction between questions.Main Activity holds questions and CheatActivity has answers from Main activity. And i created BooleanArray to hold cheat data for questions.
Problem is ,i cheated for first question and then when i am in the CheatActivity(CheatPage) of other questions ,program crashes if i rotate the screen.
Error caused by this line savedInstanceState.putBoolean(CHEATER,mIsCheater);
i think i need to clear data from previous Cheat Data(BooleanArray already holding it) but i dont know how to do it.

public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE = "com.example.ferhat.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.example.ferhat.geoquiz.answer_shown";
public static final String EXTRA_CHEATED = "com.example.ferhat.geoquiz.cheated";
private static final String CHEATER = "com.example.ferhat.geoquiz.cheated";
private Boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mAnswerEverShown;
private Boolean twoStep=false;
//Yeni intent methodu yarattık Cevabı alıyor ve bu activity i başlatıyor
public static Intent newIntent(Context packageContext, boolean answerIsTrue, boolean checked) {
Intent i = new Intent(packageContext, CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
i.putExtra(EXTRA_CHEATED, checked);
return i;
}
private void setAnswerShownResult(Boolean isAnswerShown) {
Intent data = new Intent();
**if(mAnswerEverShown) {
isAnswerShown=mAnswerEverShown;
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}else {
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
twoStep=isAnswerShown;**
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
**mAnswerEverShown = getIntent().getBooleanExtra(EXTRA_CHEATED, false);**
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
//Cevabı gösteriyor ve Kopya çekildi bilgisi veriliyor
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
twoStep=true;
setAnswerShownResult(twoStep);
}
});
**if (savedInstanceState != null) {
setAnswerShownResult(savedInstanceState.getBoolean(CHEATER, false));
}
}
#Override
public void onSaveInstanceState (Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(CHEATER, twoStep);
}
}**
i found solution like for every situation.
first think i did; i get info from main activity
mAnswerEverShown = getIntent().getBooleanExtra(EXTRA_CHEATED, false);
And Then i changed setAnswerShownResult for two situation.If it is not cheated ever program sends current data(cheated or not).
i marked where i changed with *.

You need to putBoolean before callback the super method.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putBoolean(CHEATER,mIsCheater);
super.onSaveInstanceState(savedInstanceState);
}
if not the CHEATER won't be saved and you can't call it when resume activity

Related

Syntax to complete shared preferences for number of clicks count

Hi I just need a little bit of a helping hand in completing this shared preferences code I have.
Currently I have a class where I stored in the relevant code for SharedPreferences:
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String NUMBER_OF_CLICKS = "numberOfClicks";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs =
context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public void storeClicks(int count)
{
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, count);
editor.apply();
}
public int getNumberOfClicks(){
int clicksNumber = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
return clicksNumber;
}
}
I want to count the number of clicks for buttons jokes, poems and funnystories from the MainActivity class and the 'select another' button from the Content class. So if each button was clicked 4 times, the total click count should be 16.
I want to keep the number of clicks count even after the app is closed and re-open. It's just the syntax of the counting of the clicks I am unsure of. I think for main activity it is correct but I am unsure on how to store it for the Content class.
TO recap, count the number of clicks for all of those buttons mentioned and this number should be accessible and updated no matter which page the user is in.
Below is the Main Activity class:
public class MainActivity extends AppCompatActivity{
final Context context = this;
int clicksCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferencesManager.getInstance(context).storeClicks(clicksCount);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
}
Below is Content class:
public class Content extends AppCompatActivity{
Button backButton;
Button selectAnotherButton;
TextView contentText;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
int clicksCount = SharedPreferencesManager.getInstance(context).getNumberOfClicks();
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
finish();
}
});
}
}
Instead of having the two methods getNumberOfClicks() and storeClicks() in your SharedPreferencesManager, you could only have one like this:
public void increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
}
You call this on every click. No need for the activities to know about the clicks count.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(context);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
}
});
...
}
Also there's no need to store your context as a global variable because your activity is already a context itself, you can just use this or MainActivity.this for a context.

How to pass a boolean value between activities with intents [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 6 years ago.
public class StartActivity extends AppCompatActivity {
private boolean addition=true;
private boolean subtraction=false;
private boolean multiplication=false;
private boolean division=false;
public static final String ADDITION = "";
public static final String SUBTRACTION = "";
public static final String MULTIPLICATION= "";
public static final String DIVISION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
final Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
CheckBox additionCheckBox = (CheckBox)findViewById(R.id.additionCheckBox);
CheckBox multiplicationCheckBox = (CheckBox)findViewById(R.id.multiplicationCheckBox);
CheckBox divisionCheckBox = (CheckBox)findViewById(R.id.divisionCheckBox);
CheckBox subtractionCheckBox = (CheckBox)findViewById(R.id.subtractionCheckBox);
Button playButton = (Button)findViewById(R.id.playButton);
additionCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isChecked()){
addition = true;
}else{
addition = false;
}
}
});
multiplicationCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isChecked()){
multiplication = true;
}else{
multiplication= false;
}
}
});
subtractionCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isChecked()){
subtraction = true;
}else{
subtraction = false;
}
}
});
divisionCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isChecked()){
division = true;
}else{
division = false;
}
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!addition && !subtraction && !multiplication && !division){
final Dialog dialog = new Dialog(StartActivity.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("My custom dialog");
//set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.textView);
text.setText("Android custom dialog example!");
Button button = (Button) dialog.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
} else{
Intent i = new Intent(StartActivity.this, Main2Activity.class);
i.putExtra(ADDITION,addition);
i.putExtra(SUBTRACTION,subtraction);
i.putExtra(MULTIPLICATION,multiplication);
i.putExtra(DIVISION,division);
startActivity(i);
}
}
});
}
This is the starting activity and I am trying to sent to the next activity the 4 boolean variables one for each basic math operation to see which one the user has checked. but they are always false in the next activity and i dont know why. here is the next activity:
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
Intent i = getIntent();
Bundle b = i.getExtras();
boolean addition = b.getBoolean("ADDITION");
boolean subtraction = Boolean.getBoolean("SUBTRACTION");
boolean multiplication = b.getBoolean("MULTIPLICATION");
boolean division = b.getBoolean("DIVISION");
int operatorCounter =0;
TextView additionTextView = (TextView) findViewById(R.id.additionTextView);
TextView subtractionTextView = (TextView) findViewById(R.id.subtractionTextView);
TextView multiplicationTextView = (TextView) findViewById(R.id.multiplicationTextView);
TextView divisionTextView = (TextView) findViewById(R.id.divisionTextView);
if (addition) {
additionTextView.setText("addition:checked");
}else{
additionTextView.setText("addition:not checked");
}
if (subtraction) {
subtractionTextView.setText("subtraction:checked");
}else{
subtractionTextView.setText("subtraction:not checked");
}
if (multiplication) {
multiplicationTextView.setText("multiplication:checked");
}else{
multiplicationTextView.setText("multiplication:not checked");
}
if (division) {
divisionTextView.setText("division:checked");
}else{
divisionTextView.setText("division:not checked");
}
}
}
I am setting the text in the textbox to see if the value is passed correctly but is always false. Sorry for bad code I'm quite new in android, actually is the forth mini project in android and its school homework.
The problem I see are the id's:
public static final String ADDITION = "";
public static final String SUBTRACTION = "";
public static final String MULTIPLICATION= "";
public static final String DIVISION = "";
this should be something and different like:
public static final String ADDITION = "ADDITION";
public static final String SUBTRACTION = "SUBTRACTION";
public static final String MULTIPLICATION= "MULTIPLICATION";
public static final String DIVISION = "DIVISION";
and use the same values for retrieving the values in the other activity
Try this code for both sending and getting values.
Pass to first Activity:
Intent i = new Intent(getBaseContext(), NameOfActivity.class);
i.putExtra("my_boolean_key", myBooleanVariable);
startActivity(i);
Retrieve in Second Activity:
Bundle bundle = getIntent().getExtras();
boolean myBooleanVariable = bundle.getBoolean("my_boolean_key");
Its because you are not setting value in globle variable, so you need to set first globle variable value like this
public static final String ADDITION = "ADDITION";
public static final String SUBTRACTION = "SUBTRACTION";
public static final String MULTIPLICATION= "MULTIPLICATION";
public static final String DIVISION = "DIVISION";
then set it
Intent i = new Intent(StartActivity.this, Main2Activity.class);
i.putExtra(ADDITION,addition);
i.putExtra(SUBTRACTION,subtraction);
i.putExtra(MULTIPLICATION,multiplication);
i.putExtra(DIVISION,division);
startActivity(i);
than aceess value from another activity like this
boolean addition = getIntent().getExtras().getBoolean("ADDITION");
boolean sub = getIntent().getExtras().getBoolean("SUBTRACTION");
boolean mult = getIntent().getExtras().getBoolean("MULTIPLICATION");
boolean division = getIntent().getExtras().getBoolean("DIVISION");
Make sure you are using same key to Put and to Get data.
Also update
boolean subtraction = Boolean.getBoolean("SUBTRACTION");
To
boolean subtraction = b.getBoolean("SUBTRACTION");
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("BoolName", true);
startActivity(intent );
Retrieve boolean value from intent :
Boolean yourBool = getIntent().getExtras().getBoolean("BoolName");
I will use this post to show why a mcve is useful since this is a perfect example, I will use his code, cleaning the useless part and we will quickly find the problem, I don't deserve or ask for upvote but don't downvote either, if you are against this answer, comment and I will remove it if need.
So, let clean the code, I am only interested in the Intent creation here. So let clean the rest and keep the variables/constants used. To be minimal, we only need one boolean, let's keep the first putBoolean.
public class StartActivity extends AppCompatActivity {
private boolean addition=true;
public static final String ADDITION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Button playButton = (Button)findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(StartActivity.this, Main2Activity.class);
i.putExtra(ADDITION,addition);
startActivity(i);
}
});
Well, this is better. Fits on one screen and we see the problem directly.
Same thing with the recovering:
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent i = getIntent();
Bundle b = i.getExtras();
boolean addition = b.getBoolean("ADDITION");
}
}
Mmmh, could use StartActivity.ADDITION here ...
I hope code will help you
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("yourBoolName", true);
protected void onCreate(Bundle savedInstanceState) {
Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
}
Intent intt=new Intent(this,YourAcivity.class);
intt.putExtra("BooleanKey",true);
startActivity(intt);
protected void onCreate(Bundle savedInstanceState) {
Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
}

Issues in SharedPreference

I have one button in mainactivity when i click on button formactivty opened then after saved the data and i killed the app it display from main activity, it doesn't show welcome activity by using shared preference. any one can solve this one
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
FormActivty
public class Form extends Activity {
SharedPreferences sp;
public static String Filename= "LoginFile";
public static String key = "status";
EditText namee,emaill;
String Name,Email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
boolean res = sp.getBoolean(key,false);
if (res) {
setContentView(R.layout.welcom);
} else {
setContentView(R.layout.form);
}
}
public void save(View v) {
namee = (EditText)findViewById(R.id.name);
emaill = (EditText)findViewById(R.id.email);
Name = namee.getText().toString();
Email = emaill.getText().toString();
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(key,true);
ed.putString("k1",Name);
ed.putString("k2",Email);
ed.commit();
Intent i = new Intent(this,Welcome.class);
startActivity(i);
}
}
Welcome Activity
public class Welcome extends Activity {
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcom);
sp = getSharedPreferences(Form.Filename,MODE_PRIVATE);
TextView tv= (TextView)findViewById(R.id.text);
TextView tv1= (TextView)findViewById(R.id.text1);
String username,email;
Intent i = getIntent();
Bundle b = new Bundle();
b= i.getExtras();
username = sp.getString("k1","");
email = sp.getString("k2","");
tv.setText(username);
tv1.setText(email);
}
public void logout(View v) {
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(Form.key,false);
ed.commit();
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
On your MainActivity, under onCreate(), there should be a code that checks if your SharedPreference is empty. If it's empty, it should go to Form.class or it should not do anything since you have a button there in MainActivity. If not, then go to Welcome.class. You're almost there, just do some minor tweaks on your code and you'll get it.
public class MainActivity extends AppCompatActivity {
SharedPreferences sp;
public static String Filename= "LoginFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
String name = sp.getString("k1", "");
if(!name.isEmpty()){
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
}
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
If you'll notice on this code, every time the app is killed and you start it again, it'll check if sharedpreference is empty. If not, it will go directly to Welcome.class.

How to make the button loads the previous page in Android?

I have search a lot in different sites to solve this problem but I can't till now.
I have a simple app with 50 articles, two buttons, previous and next.
All works fine till the last article 50 where the problem is that the user can't choose the previous button 49, only can load from the beginning.
Here is my code: MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView meditCenterText;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
meditCenterText = (TextView) findViewById(R.id.editCenterText);
mStartButton = (Button) findViewById(R.id.startButton);
meditCenterText.setMovementMethod(new ScrollingMovementMethod());
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TextView = meditCenterText.getText().toString();
startStory(TextView);
}
});
}
private void startStory(String TextView) {
Intent intent = new Intent(this, StoryActivity.class);
intent.putExtra("TextView", TextView);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
meditCenterText.setText("..... ");
}}
StoryActivity.java
public class StoryActivity extends AppCompatActivity {
public static final String TAG = StoryActivity.class.getSimpleName();
private Story mStory = new Story();
private ImageView mImageView;
private TextView mTextView;
private Page mCurrentPage;
private String mName;
private Button mPreviousButton;
private Button mNextButton;
private ScrollView mScrollView;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story2);
//Intent intent = getIntent();
//mName = intent.getStringExtra(getString(R.string.key_name));
if(mName == null){
mName = "";
}
Log.d(TAG, mName);
mImageView = (ImageView)findViewById(R.id.storyImageView);
mTextView = (TextView)findViewById(R.id.storyTextView);
mPreviousButton = (Button)findViewById(R.id.previousButton);
mNextButton = (Button)findViewById(R.id.nextButton);
mTextView.setMovementMethod(new ScrollingMovementMethod());
loadPage(0);
}
private void loadPage(int choice){
mCurrentPage = mStory.getPage(choice);
Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
mImageView.setImageDrawable(drawable);
String pageText = mCurrentPage.getText();
//add the name if placeholder included.
//pageText = String.format(pageText,mName);
mTextView.setText(pageText);
if(mCurrentPage.isSingle()){
mPreviousButton.setVisibility(View.VISIBLE);
mNextButton.setText("Start From The Beginning");
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPreviousButton.setVisibility(View.VISIBLE);
loadPage(0);
}
});
}else{
mPreviousButton.setText(mCurrentPage.getChoices().getText1());
mNextButton.setText(mCurrentPage.getChoices().getText2());
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousPage = mCurrentPage.getChoices().getPreviousPage();
loadPage(previousPage);
}
});
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoices().getNextPage();
loadPage(nextPage);
}
});
}}
}
Thanks for help.
It's probably the logic in your Page class. Have a proper look at it, otherwise from the android side everything is alright. One last thing, you should probably use a ViewPager for your app instead of changing the text every time you load a new oage

Use a string (from input) in another class

I have a class in which a string is taken from an input. I want to use the value of the input in a second class.
public class Incontrare extends ActionBarActivity {
public static String nome1=null;
public String variabileNome;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incontrare);
Button button1 = (Button) findViewById(R.id.button1Nome);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
alertDia(); //takes the input from variabileNome
nome1 = variabileNome;
TextView textv1 = (TextView) findViewById(R.id.textView1);
textv1.setText(nome1);
}
});
public static String getNome1() {return nome1;}
}
}
And the second class:
public class IncontrarePersona1 extends ActionBarActivity {
String nome1=Incontrare.getNome1();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incontrare_persona1);
b1=(Button)findViewById(R.id.play);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String toPrint = "There is " + nome1;
Toast.makeText(getApplicationContext(), toPrint, Toast.LENGTH_SHORT).show();
}
});
}
I tried the second class also in this way:
public class IncontrarePersona1 extends ActionBarActivity {
String nome1=Incontrare.getNome1();
public static String no1;
b1=(Button)findViewById(R.id.play);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Incontrare no1= new Incontrare();
String n1= no1.nome1;
String toPrint = "There is " + nome1;
Toast.makeText(getApplicationContext(), toPrint, Toast.LENGTH_SHORT).show();
}
});
}
Where is the mistake? Why do I get always null?
Any help is appreciated. Thanks :)
If you are jumping from activity to another use Bundle.
Bundle example -
Set value
Intent i = new Intent();
i.setClass(this, IncontrarePersona1.class);
i.putExtra("text", "some text");
startActivity(i);
Get Value:
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String data= extras.getString("text");
//data is your param
}
Otherwise use static class with static variables as Will McG said.
I think the issue is that when the second Activity is brought into focus, the data in the previous Activity is lost.
Create a separate class to hold your static variables that both Activitys can access.
Edit:
Another method I use for passing data is the SharedPreferences if I'm worried about the entire application losing focus.

Categories