Error in Shared Preferences, ImageView disappears - java

I Programm a Quiz App it starts with the Main Activity (Quiz Activity). I already set up that if the highscore is over 10, an ImageView will be shown permanently in Menu2 Activity. That works very fine also on restart of the app, the only problem is that if the user reachs a highscore of for example 11 the picture will not immediately be shown, It will shown if the user hits directly after for example a score of 3 It will permanently show. How can I set up that the picture will be shown when the highscore is reached?
Quiz Activity java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Randromizes the row of the questions
QuestionLibrary q = new QuestionLibrary();
System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
q.shuffle();
System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
mQuestionLibrary.shuffle();
//End randomizer
//We need this for the NAVIGATION DRAWER
mToolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Able to see the Navigation Burger "Button"
NavigationView mNavigationView = (NavigationView) findViewById(R.id.nv1);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case(R.id.nav_stats): //If nav stats selected Activity 2 will show up
Intent accountActivity = new Intent(getApplicationContext(),Menu2.class);
startActivity(accountActivity);
}
return true;
}
});
//Initialise
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
updateQuestion(); //New question appears
//Start of Button Listener1 -> if true, next question appears +score +1[] Else menu 2 will show
mButtonChoice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (mButtonChoice1.getText() == mAnswer) {
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optional...
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
});
//End of Button Listener1
//Start of Button Listener2
mButtonChoice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (mButtonChoice2.getText() == mAnswer) {
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optional...
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Oh... wrong your score is 0", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
});
//End of Button Listener2
//Start of Button Listener3
mButtonChoice3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (mButtonChoice3.getText() == mAnswer) {
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optional...
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Come on, that was not so hard...", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
});
//End of Button Listener3
}
private void updateQuestion() {
//If the max. number of questions is reached, menu2 will be open if not a new quiz selection appears
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
mQuestionNumber++;
}
else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
private void updateScore ( int point){
mScoreView.setText("" + mScore);
//Shared preferences = a variabe (mScore) gets saved and call up in another activity
SharedPreferences mypref =getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if(mScore> highScore){
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("currentscore", mScore);
editor.apply();
}
}
#Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
public boolean onOptionsItemSelected (MenuItem item){
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Menu 2:
public class Menu2 extends AppCompatActivity {
private DrawerLayout mDrawerLayout2;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private Button popup;
private PopupWindow popupWindow;private LayoutInflater layoutInflater; //Alows to add a new layout in our window
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);
TextView txtScore = (TextView) findViewById(R.id.textScore2);
TextView txtHighScore = (TextView) findViewById(R.id.textHighScore);
ImageView imgTrophyView1 = (ImageView) findViewById(R.id.trophy1);
ImageView imgTrophyView2 = (ImageView) findViewById(R.id.trophy2);
Button bttPOPUP = (Button) findViewById(R.id.enablePOPUP);
Intent intent = getIntent();
int mScore = intent.getIntExtra("score", 0);
txtScore.setText("Your score is: " + mScore);
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (highScore >= mScore)
txtHighScore.setText("High score: " + highScore);
else {
txtHighScore.setText("New highscore: " + mScore);
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.commit();
}
if (highScore >= 10) {
imgTrophyView1.setVisibility(View.VISIBLE);
bttPOPUP.setVisibility(View.VISIBLE);
}
if (highScore >= 20) {
imgTrophyView2.setVisibility(View.VISIBLE);
}
popup = (Button)findViewById(R.id.enablePOPUP);
popup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutInflater =(LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup)layoutInflater.inflate(R.layout.popup_menu2_1,null);
popupWindow = new PopupWindow(container,1000,980,true); //400,400=popUp size, true = makes that we can close the pop up by simply click out of the window
popupWindow.showAtLocation(mDrawerLayout2, Gravity.CENTER, 0, 0);
mDrawerLayout2.setAlpha((float) 0.1);
container.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent motionEvent ){
mDrawerLayout2.setAlpha((float) 1);
popupWindow.dismiss();
return true;
}
});
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
mDrawerLayout2.setAlpha((float) 1);
popupWindow.dismiss();
}
});
}
});
mToolbar = (Toolbar)findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout2 = (DrawerLayout) findViewById(R.id.drawerLayout2);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout2, R.string.open, R.string.close);
mDrawerLayout2.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView = (NavigationView) findViewById(nv2);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case(R.id.nav_home2):
Intent accountActivity2 = new Intent(getApplicationContext(),QuizActivity.class);
startActivity(accountActivity2);
}
return true;
}
});}
public void onClick(View view) {
Intent intent = new Intent(Menu2.this, QuizActivity.class);
startActivity(intent);
}
#Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Please edit this line
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
to
SharedPreferences mypref = getPreferences("MyPreferences",MODE_PRIVATE);

Related

Override, SuppressLint onCreate(Bundle)' is already defined in 'My project'

In my MainActivity shows like that, I am pretty developer yet, How to replace or solve it, I tried many as know but unfortunately getting error "is already defined"
In my MainActivity shows like that, I am pretty developer yet, How to replace or solve it, I tried many as know but unfortunately getting error "is already defined"
How can I solve this code to going right?
BottomNavigationView bottomNavigation;
public Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadLocale();
setContentView(R.layout.fragment_main);
//change actionbar title, if you dont change it will be according to your systems default language/english
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getResources().getString(R.string.app_name));
Button changeLang = findViewById(R.id.changeMyLang);
changeLang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//show AlertDialog to display list of language, one can be selected
showChangeLanguageDialog();
}
});
}
private void showChangeLanguageDialog() {
//array of languages to display in alert dialog
final String[] listItems = {"English", "O'zbek"};
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Choose Language...");
mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//English
setLocale("en");
recreate();
} else if (i == 1) {
//O'zbek
setLocale("uz");
recreate();
}
//dismiss alert dialog when language selected
dialogInterface.dismiss();
}
});
AlertDialog mDialog =mBuilder.create();
//show alert dialog
mDialog.show();
}
DrawerLayout drawer;
ImageView imageView1;
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(MenuItem menuItem) {
String str = "";
switch (menuItem.getItemId()) {
case R.id.navigation_home:
toolbar.setTitle(getString(R.string.app_name));
MainActivity.this.openFragment(MainFragment.newInstance(str, str, MainActivity.this));
return true;
case R.id.navigation_map:
toolbar.setTitle("Workouts");
MainActivity.this.openFragment(Fragment_Workout.newInstance(str, str));
return true;
case R.id.navigation_walk:
toolbar.setTitle("Walk & Step");
MainActivity.this.openFragment(Fragment_Walk_and_Step.newInstance(str, str));
return true;
case R.id.navigation_news:
toolbar.setTitle("Reminders");
MainActivity.this.openFragment(Fragment_Reminder.newInstance(str, str));
return true;
default:
return false;
}
}
};
NavigationView navigationView;
Toolbar toolbar;
#SuppressLint("ResourceType")
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (VERSION.SDK_INT > 21) {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
}
setContentView((int) R.layout.activity_main);
// StepDetectionServiceHelper.startAllIfEnabled(true, MainActivity.this);
this.navigationView = (NavigationView) findViewById(R.id.nav_views);
// bottomNavigation.setItemIconTintList(null);
this.imageView1 = (ImageView) findViewById(R.id.setting);
this.imageView1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// MainActivity.this.startActivity(new Intent(MainActivity.this, Setting_Activity.class));
}
});
if (VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(Integer.MIN_VALUE);
// window.setStatusBarColor(Color.parseColor("#EF5050"));
}
this.toolbar = initToolbar();
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
this.drawer = drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this, drawerLayout, this.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
this.drawer.addDrawerListener(actionBarDrawerToggle);
this.drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
public void onDrawerClosed(View view) {
}
public void onDrawerOpened(View view) {
}
});
actionBarDrawerToggle.syncState();
this.navigationView.setNavigationItemSelectedListener(this);
String str = "#ffffff";
// this.toolbar.setTitleTextColor(Color.parseColor(str));
// this.toolbar.getNavigationIcon().setColorFilter(Color.parseColor(str), Mode.MULTIPLY);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
this.bottomNavigation = bottomNavigationView;
bottomNavigationView.setOnNavigationItemSelectedListener(this.navigationItemSelectedListener);
String str2 = "";
// MainActivity mainActivity = null;
openFragment(MainFragment.newInstance(str2, str2, this));
}
public void openFragment(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
}
public void loadFragmentworkout(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
toolbar.setTitle("workout");
bottomNavigation.setSelectedItemId(R.id.navigation_map);
}
public void loadFragment_water(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
toolbar.setTitle("Walk & Step");
bottomNavigation.setSelectedItemId(R.id.navigation_walk);
}
private Toolbar initToolbar() {
Toolbar toolbar2 = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar2);
return toolbar2;
}
public boolean onNavigationItemSelected(MenuItem menuItem) {
int itemId = menuItem.getItemId();
String str = "android.intent.extra.TEXT";
String str2 = "android.intent.extra.SUBJECT";
if (itemId == R.id.nav_rateus) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
} else if (itemId == R.id.nav_share) {
Intent intent2 = new Intent("android.intent.action.SEND");
intent2.setType("text/plain");
StringBuilder sb3 = new StringBuilder();
sb3.append("Best Free Sog'liq Bu Sport app download now.\n Thank You!\n https://play.google.com/store/apps/details?id=" + getPackageName());
sb3.append(getApplicationContext().getPackageName());
String sb4 = sb3.toString();
intent2.putExtra(str2, "Share App");
intent2.putExtra(str, sb4);
startActivity(Intent.createChooser(intent2, "Share via"));
} else if (itemId == R.id.nav_privacy) {
Uri uri = Uri.parse("https://the-life-bloga.blogspot.com/2020/01/blog-post.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_telegram) {
Uri uri = Uri.parse("https://the-life-bloga.blogspot.com/2020/01/blog-post.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_instagram) {
Uri uri = Uri.parse("https://www.instagram.com/sanatismoilov_official");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_facebook) {
Uri uri = Uri.parse("https://www.facebook.com/Nodirovich98");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_about) {
Uri uri = Uri.parse("https://msto.me/sanat_ismoilov");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_covid) {
Uri uri = Uri.parse("https://coronavirus.uz/uz");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
this.drawer.closeDrawer((int) GravityCompat.START);
return true;
}
public void onBackPressed() {
StepDetectionServiceHelper.stopAllIfNotRequired(this.getApplicationContext());
// StepDetectionServiceHelper.startAllIfEnabled(true, MainActivity.this);
}
public void setLocale(String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
//save data to shared preferences
SharedPreferences.Editor editor = getSharedPreferences("Setting", MODE_PRIVATE).edit();
editor.putString("My_Lang", lang);
editor.apply();
}
// load language saved in shared prefences
public void loadLocale() {
SharedPreferences prefs = getSharedPreferences("Setting", Activity.MODE_PRIVATE);
String language = prefs.getString("My_Lang", "");
setLocale(language);`
}
}```

Exit App When Pressed Back Button after Login, but OnPressedBack keep Coming Back to First Page

I have 3 activity the first one is LandingActivity. This is the launcher activity when you open the app and not logged in, the second is SignInActivity and the third is HomeActivity, this activity is launched when you're already logged in and open the app.
Here's the code:
LandingActivity
public class LandingActivity extends AppCompatActivity {
private FirebaseAuth auth;
private Button btnSignIn, btnSignUp;
TextView textSlogan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
//Init Firebase Auth
auth = FirebaseAuth.getInstance();
//Check if Already Session
if (auth.getCurrentUser() != null){
startActivity(new Intent(LandingActivity.this, HomeActivity.class));
}
textSlogan = (TextView)findViewById(R.id.textSlogan);
Typeface face = Typeface.createFromAsset(getAssets(),"fonts/NABILA.TTF");
textSlogan.setTypeface(face);
btnSignIn = (Button)findViewById(R.id.main_sign_in_button);
btnSignUp = (Button)findViewById(R.id.main_sign_up_button);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LandingActivity.this, SignInActivity.class));
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LandingActivity.this, SignUpActivity.class));
}
});
}
}
SignInActivity
public class SignInActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignIn, btnResetPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase Auth Instance
auth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_sign_in);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignIn = (Button) findViewById(R.id.action_sign_in_button);
btnResetPassword = (Button) findViewById(R.id.intent_reset_password_button);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter Email Address", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter Password", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//Authenticate User
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(SignInActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
//There was an Error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(SignInActivity.this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show();
}
} else {
Intent intent = new Intent(SignInActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
btnResetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignInActivity.this, ResetPasswordActivity.class));
}
});
}
}
HomeActivity
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authStateListener;
private ProgressBar progressBar;
private long backPressedTime;
private Toast backToast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
//Get Firebase Auth Instance
auth = FirebaseAuth.getInstance();
//Get Current User
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (user == null) {
//User Auth State is Changed - User is Null
//Launch Login Activity
startActivity(new Intent(HomeActivity.this, LandingActivity.class));
finish();
}
}
};
}
#Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()){
backToast.cancel();
super.onBackPressed();
} else {
backToast = Toast.makeText(getBaseContext(), "Press Back again to Exit", Toast.LENGTH_SHORT);
backToast.show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
progressBar.setVisibility(View.VISIBLE);
switch (id) {
case R.id.action_edit_password:
startActivity(new Intent(HomeActivity.this, ChangePasswordActivity.class));
progressBar.setVisibility(View.GONE);
break;
case R.id.action_sign_out:
auth.signOut();
progressBar.setVisibility(View.GONE);
Toast.makeText(this, "Signed Out", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(HomeActivity.this, LandingActivity.class));
}
return super.onOptionsItemSelected(menuItem);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
auth.getCurrentUser();
startActivity(new Intent(HomeActivity.this, HomeActivity.class));
} else if (id == R.id.nav_app_received) {
} else if (id == R.id.nav_app_submitted) {
} else if (id == R.id.nav_tutorial) {
startActivity(new Intent(HomeActivity.this, TutorialActivity.class));
} else if (id == R.id.nav_about_us) {
startActivity(new Intent(HomeActivity.this, AboutUsActivity.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I've tried onBackPressed() method to exit the app if back button pressed, but it still comes back to the LandingActivity instead of exiting the app. So, how to exit the app when back button is pressed but the user did not log out.
After startActivity() methods in your LandingPage activity use the method finish(). An excellent explanation of the finish method is given here

Change the color of a button temporary

I programmed a quiz, now I want that every time the correct answer/button(mButtonChoice) is pressed the background of the button will be colored green, later it will be set as default.
So the correct buttons should be "colored" green and then later as before. How do I can manage to do that?
QuizActicity (Here are the questions and the choices):-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now!");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
}
As a Java developer you should get used to use the online documentation of the components you use.
When you look at the API description of Androids Button class (https://developer.android.com/reference/android/widget/Button.html) you might find that it inherits the method setBackgroundColor(int color) from Androids View class (https://developer.android.com/reference/android/view/View.html#setBackgroundColor(int))
Then you only need to call that method at the two correct places in your program.
Setting the "background color" for a Button is a little bit tricky. By default, every Button has a background managed by the Android system that includes things like rounded corners, colors only within a certain area, etc. If you simply call setBackgroundColor(), you will lose all of that sophisticated behavior and be left with a flat rectangle.
I assume you're extending from AppCompatActivity here. If not, this answer won't work.
To change a Button's background color while still keeping the rounded shape and the ripple effect, use ViewCompat.setBackgroundTintList() as follows:
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
int color = ContextCompat.getColor(this, R.color.yourColorResourceHere);
ColorStateList tintList = ColorStateList.valueOf(color);
ViewCompat.setBackgroundTintList(dialogButton, tintList);

App crashes when implementing mute button [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I programmed a quiz now I set up a mediaplayer under the FOR-query, that every time the user hits a correct answer the sound will be played. Now in the same Activity I want that bttOFF will mute the sound of the Activity how can I do that? I set up an onClickListener with mp.setVolume(0,0); But the app crashes on restart. Thanks for looking! :D
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
final MediaPlayer mp = new MediaPlayer();
//Dialog 1
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//end Dialog 1
//Dialog 2
createDialog2();
Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
dialogButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.show();
}
});
closeButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
}
});
//end Dialog 2
Button bttON = (Button)findViewById(R.id.bttON);
bttON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.setVolume(0,0);
}
});
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
private void createDialog2() {
dialog2 = new Dialog(this);
dialog2.setTitle("Settings");
dialog2.setContentView(R.layout.popup_menu1_2);
closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
}
Logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at shapy.appz.QuizActivity.onCreate(QuizActivity.java:96)
your get to findViewById fro your closeButton and closeButton2
As shown in the documentation for the MediaPlayer class [here]( https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float, float) ) the needed parameters are floats. You could try to do this:
public void onClick(View v) {
mp.setVolume( 0.0, 0.0 );
}
And see if that solves your problem.
setVolume
added in API level 1
void setVolume (float leftVolume, float rightVolume)
Sets the volume on this player. This API is recommended for balancing the output of audio streams within an application. Unless you are writing an application to control user settings, this API should be used in preference to setStreamVolume(int, int, int) which sets the volume of ALL streams of a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0. UI controls should be scaled logarithmically.
Parameters
leftVolume float: left volume scalar
rightVolume float: right volume scalar

Setting up the visibility of an Image View depending on Shared Preferences

I Programm a Quiz App. I already set up that if the highscore is over 10, an ImageView will be shown permanently. That works very fine also on restart of the app, the only problem is that if the user reachs a highscore of for example 11 and directly later on the beginning of the quiz answers correctly and then false, the ImageView disappears. The shared preference is in the Main Activity (Quiz activity) and will be calles in Menu2 (second Activity).
Quiz Activity java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Randromizes the row of the questions
QuestionLibrary q = new QuestionLibrary();
System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
q.shuffle();
System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
mQuestionLibrary.shuffle();
//End randomizer
//We need this for the NAVIGATION DRAWER
mToolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Able to see the Navigation Burger "Button"
NavigationView mNavigationView = (NavigationView) findViewById(R.id.nv1);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case(R.id.nav_stats): //If nav stats selected Activity 2 will show up
Intent accountActivity = new Intent(getApplicationContext(),Menu2.class);
startActivity(accountActivity);
}
return true;
}
});
//Initialise
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
updateQuestion(); //New question appears
//Start of Button Listener1 -> if true, next question appears +score +1[] Else menu 2 will show
mButtonChoice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (mButtonChoice1.getText() == mAnswer) {
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optional...
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
});
//End of Button Listener1
//Start of Button Listener2
mButtonChoice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (mButtonChoice2.getText() == mAnswer) {
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optional...
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Oh... wrong your score is 0", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
});
//End of Button Listener2
//Start of Button Listener3
mButtonChoice3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My logic for Button goes in here
if (mButtonChoice3.getText() == mAnswer) {
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optional...
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Come on, that was not so hard...", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
});
//End of Button Listener3
}
private void updateQuestion() {
//If the max. number of questions is reached, menu2 will be open if not
//a new quiz selection appears
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
mQuestionNumber++;
}
else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score",mScore); //pass score to Menu2
startActivity(intent);
}
}
private void updateScore ( int point){
mScoreView.setText("" + mScore);
//Shared preferences = a variabe (mScore) gets saved and call up in another activity
SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("currentscore", mScore);
editor.apply();
}
#Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
public boolean onOptionsItemSelected (MenuItem item){
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Menu 2:
public class Menu2 extends AppCompatActivity {
private DrawerLayout mDrawerLayout2;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private Button popup;
private PopupWindow popupWindow;private LayoutInflater layoutInflater; //Alows to add a new layout in our window
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);
SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
int applyView =sharedpreferences.getInt("currentscore",0);
TextView txtScore = (TextView) findViewById(R.id.textScore2);
TextView txtHighScore = (TextView)findViewById(R.id.textHighScore);
ImageView imgTrophyView1 = (ImageView)findViewById(R.id.trophy1);
ImageView imgTrophyView2 = (ImageView) findViewById(R.id.trophy2);
Button bttPOPUP =(Button)findViewById(R.id.enablePOPUP);
Intent intent = getIntent();
int mScore = intent.getIntExtra ("score",0);
txtScore.setText("Your score is: " + mScore);
SharedPreferences mypref =getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (highScore>= mScore)
txtHighScore.setText("High score: " + highScore);
else{
txtHighScore.setText("New highscore: " + mScore);
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore",mScore);
editor.apply();
}
if (applyView >=10) {
imgTrophyView1.setVisibility(View.VISIBLE);
bttPOPUP.setVisibility(View.VISIBLE);
}
if (applyView >= 20){
imgTrophyView2.setVisibility(View.VISIBLE);
}
popup = (Button)findViewById(R.id.enablePOPUP);
popup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutInflater =(LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup)layoutInflater.inflate(R.layout.popup_menu2_1,null);
popupWindow = new PopupWindow(container,1000,980,true); //400,400=popUp size, true = makes that we can close the pop up by simply click out of the window
popupWindow.showAtLocation(mDrawerLayout2, Gravity.CENTER, 0, 0);
mDrawerLayout2.setAlpha((float) 0.1);
container.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent motionEvent ){
mDrawerLayout2.setAlpha((float) 1);
popupWindow.dismiss();
return true;
}
});
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
mDrawerLayout2.setAlpha((float) 1);
popupWindow.dismiss();
}
});
}
});
mToolbar = (Toolbar)findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout2 = (DrawerLayout) findViewById(R.id.drawerLayout2);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout2, R.string.open, R.string.close);
mDrawerLayout2.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView = (NavigationView) findViewById(nv2);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case(R.id.nav_home2):
Intent accountActivity2 = new Intent(getApplicationContext(),QuizActivity.class);
startActivity(accountActivity2);
}
return true;
}
});}
public void onClick(View view) {
Intent intent = new Intent(Menu2.this, QuizActivity.class);
startActivity(intent);
}
#Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
in your updateScore you are saving the data no matter what score is, so you delete the old value and change it with the new one, so you need to read the old score and compare it with the mScore like this :
SharedPreferences mypref =getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if(mScore> highScore){
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("currentscore", mScore);
editor.apply();
}
That happens because you have the following code
if (applyView >=10) {
imgTrophyView1.setVisibility(View.VISIBLE);
bttPOPUP.setVisibility(View.VISIBLE);
}
if (applyView >= 20){
imgTrophyView2.setVisibility(View.VISIBLE);
}
That checks the "currentScore" so if the user find only 1 answer the second time he is playing it's going to be 1 so the image won't show.
I notice that you have a sharedPref for current score and you also pass it with intent. You also have another sharedPref? My suggestion is to only pass it with intent and then check if it's a highscore, then save it to sharedPref. And only have one sharedPref.
EDIT
Remove the code below from updateScore
SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("currentscore", mScore);
editor.apply();
Then remove/edit all the shared pref code that you have in Menu 2 with something like this
SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
//first time high score
if (sharedPreferences.getInt("highScore", 0) == 0)
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("highScore", mScore );
editor.apply();
}
else
{
int oldScore = sharedPreferences.getInt("highScore", 0);
//new high score
if (mScore > oldScore)
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("highScore", mScore );
editor.apply();
}
}

Categories

Resources