How can I make this boolean variable change from False to True? - android

I have a boolean private field variable on my Main Activity that is set to False:
private boolean accountCreated = false;
When the acccount is created, I set it to true:
createAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameInput.getText().toString();
username = usernameInput.getText().toString();
age = Integer.parseInt(ageInput.getText().toString());
saveData();
openMainMenuActivity();
accountCreated = true;
}
});
but the boolean value isn't changing from false to true. The code shown above is located inside the MainActivity.java class and inside a public void method. I want this boolean value to change because if false the user can't play, if true the user will be able to play.

I guess you try to continue your game in openMainMenuActivity() method so try to move the accountCreated = true; before openMainMenuActivity();
Otherwise it's hard to tell without providing more of your code

openMainMenuActivity() method should work in that way
Intent i = new Intent(CurrentActivity.this, MainMenuActivity.class);
i.putExtra("isAccountCreated", accountCreated);
startActivity(i);
And in OtherActivity's simply should look like this
public class MainMenuActivity extends AppCompatActivity {
boolean aDifferentAccountCreatedBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
aDifferentAccountCreatedBoolean = getIntent().getBooleanExtra("isAccountCreated", false);
//Do stuff
}
}

It seems that openMainMenuActivity(); was resetting the value of the boolean. Instead of using openMainMenuActivity(); I opted to make a popup stating that the account was created successfully and simply dismissing the popup when the user presses X, hence going back to the openMainMenuActivity(); and the boolean value didn't reset. That made it work for me. Thanks to everyone for your answers!

Related

Android Studio doesn't break on field access

I have set to break on both read and write to a field, as shown below:
The problem is that the code never breaks when the field was access/modified when I know for a fact that the field was being accessed, and that breakpoints set in methods work as intended. How do I make it work?
Maybe you can try this: it's not a perfect solution, but a compromise one.
public class MainActivity extends Activity {
private boolean value = test();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (value) {
// do sth.
value = false;
}
}
private boolean test() {
return false;
}
}
create break point at return false line. But you may want to delete the extra code when the debugging is done.

getBooleanExtra() using only the default argument and not the one passed by putExtra()

Here's the code. In this part, the answerIsTrue variable should be initialized to true, which it rightly does (I debugged and checked) and is rightly also passed into putExtra() (again, I debugged and checked).
mCheatButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivity(i);
}
});
But coming to a different class, the variable mAnswerIsTrue gets assigned to false (probably due to the default argument) despite the argument being passed by putExtra() is true. Here's the code.
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
I debugged this line as well, and it does get assigned to false. What could be wrong?
Here's the complete CheatActivity class:
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true";
private Button mShowAnswerButton;
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
mShowAnswerButton = (Button)findViewById(R.id.showAnswerButton);
mShowAnswerButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if (mAnswerIsTrue){
mAnswerTextView.setText(R.id.true_button);
}else{
mAnswerTextView.setText(R.id.false_button);
}
}
});
}
}
Note: I'm a complete beginner, who just learnt debugging.
I cannot be sure, but my best guess that, getBooleanExtra() is not good. I suggest using simple getExtras and then getting your value.
i.putExtra(EXTRA_ANSWER_IS_TRUE, value);
Bundle args = MyActivity.getIntent().getExtras();
boolean istrue= args.getBoolean(EXTRA_ANSWER_IS_TRUE, false);
In your CheatActivity initialize mAnswerIsTrue in onCreate() like this:
private boolean mAnswerIsTrue = false; // default value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
}
for getting the data use the code
Boolean answertrue =getIntent().getExtras().getBoolean(CheatActivity.EXTRA_ANSWER_IS_TRUE);
in button click use the code
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = true;
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivity(i);
" Ctrl + B " to get in method in API. (android studio)
public boolean getBooleanExtra(String name, boolean defaultValue) {
return mExtras == null ? defaultValue :
mExtras.getBoolean(name, defaultValue);
}
defaultValue the value to be returned if no value of the desired
type is stored with the given name.
Every time you rotate your screen, you should call pullExtra method. I am learning Android as well, but it seems to me that everytime onCreate method is called, Android app forgets all information about intend.
My code for that parts looks like this:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, true );
if(savedInstanceState != null ){
mShownAnswer = savedInstanceState.getBoolean(KEY_IS_CHEATER, false);
setAnswerShownResult(mShownAnswer);
Log.i(TAG, String.format("IsACheater: %b", mShownAnswer) );
}
else{
setAnswerShownResult(false);
}
...
Use instead of .getBooleanExtra() the intent.extras.get().
So your code should be similar to this:
val mAnswerIsTrue = ((intent.extras.get("EXTRA_ANSWER_IS_TRUE")).toString()).toBoolean()
You need to cast, if you want to use the variable as an boolean.
If you want to put more extra, you need make a Bundle:
val extras = Bundle()
extras.putString("KEY_string", someString)
extras.putBoolean("KEY_boolean", someBoolean)
var intent = Intent(context,StartingActivity::class.java)
intent.putExtras(extras)

SharedPreferences.getBoolean returns true everytime

I made a class for handling important data changes such as App Purchase Status and other stuff .
For this goal I have created a class which does the setting and reading of the values. but the problem is whenever I call the appIsPurchased() method, the result is true while it hasen't been changed since app installation and its first initial launch.
This is my code:
/**
* Created by neemasa on 5/29/14.
* This class handles more crucial data values within app.
*/
public class AppCore {
private SharedPreferences settings;
private String keyPurchase = "app_purchased";
private Context context;
public AppCore(Context context){
this.context = context;
settings = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setAppInPurchasedMode(String status){
if (status.equals("successful")){
settings.edit().putBoolean(keyPurchase, true).commit();
}else if (status.equals("failed")){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
}
Question 1st: is there something wrong with my code? if there is then why appIsPurchased() always return true?
Question 2nd: do all values in the shared preferences are true by default?
Meanwhile when I use this class in my code the toast "Purchased!" runs even when app is running for the first time.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCore appCore = new AppCore(getApplicationContext());
if (appCore.appIsPurchased()){
Toast.makeText(getApplicationContext(),"Purchased!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"Not Purchased!",Toast.LENGTH_SHORT).show();
}
}
Actually there is a problem in your code!! thats why its always showing purchased!!
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
in this lines if the keyPurchased tag if not used , u are passing true value by default
so when u call
if (appCore.appIsPurchased()){
it always return a true value.. The solution is that make sure that the preference values are set before u call them.. hope this helps
Found It, the problem is that I was thinking
settings.getBoolean(keyPurchase,false)
returns the value of keyPurchased variable but the fact is it only returns the variable itself not its value so I fixed the problem by changing the method of my class to this:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase,false);
}
you are setting the default value to true, so either your sharedpreference does not contains an entry for key_purchased or setAppInPurchasedMode is never called or is called wit status successful. On the minor side, your
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
can be implemented like:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase, false);
}
about setAppInPurchasedMode, if I were in you I would change the way you compare status, this way:
public void setAppInPurchasedMode(String status){
if ("successful".equals(status)){
settings.edit().putBoolean(keyPurchase, true).commit();
} else if ("failed".equals(status)){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
the difference is that if status is null, the way you implemented will crash your application with NPE. With my implementation you'll get false, because "successful" instanceof null is always false, and instanceof is the first check for equals
For those still having a problem, remember to apply the changes to your preferences.
private SharedPreferences sharedPreferences ;
private SharedPreferences.Editor sharedPreferencesEditor;
sharedPreferencesEditor.putBoolean("myVariable", false);
sharedPreferencesEditor.apply();

The application may be doing too much work on its main thread......Skipped 96 frames

I am new to Android Development.
I recently created a slideshow live wallpaper which would change the image in every a few seconds depending on the user's selection. I also added the login, create password, etc. as learning purpose.
I have not seen this message before until I just updated the Eclipse. I am not if it has to do with Eclipse or my codes.
This app crashes on my Galaxy Note 2 sometimes. There must be something wrong with the codes, but I can't figure out what causes it....
I read about Asyntask, but I don't know how to approach it.
Could you someone please help me on this?
Thank you.
prefs class:
public class prefs extends PreferenceActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences mSharedPreferences;
private CheckBoxPreference pref_checkbox;
protected static final String TAG = null;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(main_activity.SHARED_PREFS_NAME);
addPreferencesFromResource(R.xml.wallpaper_settings);
getPreferenceManager().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
I have a bunch of these codes for different buttons just right below the above Oncreate.
Is it the cause of the frame skipping problems or anything wrong with them?
Preference button1 = (Preference)findPreference("button1");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
//code for login_password
return true;
}
});
Preference button2 = (Preference)findPreference("button2");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
//code for create_password
return true;
}
});
Preference button3 = (Preference)findPreference("button3");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
//code for reset_password
return true;
}
});
So on....
Edit: fixed errors.
I had a similar issue when I started with Android development. The app crashed everytime I called drawBitmap, or something like rotate an image. I had to move everything that manipulated images to an asynctask, and the app worked well after. Perhaps this is a solution for you as well?

Password protecting my app

I am very new to JAVA and android development and am trying to password protect my app.
I have tried to make it so that whenever a user presses the submit button it will start a new activity if the password is correct.
so far i have the following code:
for my button:
<Button
android:id="#+id/button_enterpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_enterpassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="262dp"
android:onClick="openMenu"
android:textSize="60sp"
android:text="#string/button_confirm"
/>
for my activity:
// This is the method called when the user presses the button
public void openMenu(View view) {
MyMethods compareText = new MyMethods();
boolean same = compareText.compareText();
if(same = true){
MyMethods openActivity = new MyMethods();
openActivity.callActivity();
}
}}
for my MyMethods class:
public class MyMethods extends Activity {
public void callActivity() {
Intent intent = new Intent(this , MainMenu.class);
startActivity(intent);
}
public boolean compareText() {
boolean same = false;
//assigning the name sumbitButton to the button from the UI
//Button sumbitButton = (Button) findViewById(R.id.button_enterpassword);
//Defines when the user has selected the button
// sumbitButton.setOnClickListener(new View.OnClickListener() {
//public void onClick(View v){
//assigning the name passwordEditText to the text inside the textbox
EditText passwordEditText = (EditText)
findViewById(R.id.text_enterpassword);
if(passwordEditText.getText().toString().equals("Test")){
same = true;
}
return same;
}
}
However whenever I press the button my program just crashes.
Cheers for your help!
There are a couple of points to notice:
MyMethods is extending Activity, but the way you're using it is unorthodox.
In openMenu(), your comparison is wrong, you're missing one = in
if (same = true) { //<---------- should be if (same == true) or if (same)
Remove your callActivity() and compareText() from MyMethods, and declare them in the class you will use them, that is in the class where you have openMenu(). I'd also rename compareText() to isPasswordValid(), to make it more clear.
Rewrite openMenu() to:
public void openMenu(View view) {
if (isPasswordValid()) {
callActivity();
}
}
You can also rewrite compareText():
public boolean isPasswordValid() {
EditText passwordEditText = (EditText) findViewById(R.id.text_enterpassword);
return passwordEditText.getText().toString().equals("Test");
}
Also, since you're launching another activity, make sure it's declared in AndroidManifest.

Categories

Resources