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
Related
I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.
Activity A:
public class NewSuggestion extends AppCompatActivity {
private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etTitle = findViewById(R.id.etTitle);
etYear = findViewById(R.id.etYear);
etMonth = findViewById(R.id.etMonth);
rgSuggestWill =findViewById(R.id.rgSuggestWill);
final Calendar c = Calendar.getInstance();
String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int yy = c.get(Calendar.YEAR);
etYear.setText(new StringBuilder().append(yy));
etMonth.setText(new StringBuilder().append(mm));
spReviewer = findViewById(R.id.spReviewer);
adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReviewer.setAdapter(adapter);
spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("title",etTitle.getText().toString());
editor.putString("year",etYear.getText().toString());
editor.putString("month",etMonth.getText().toString());
// get selected radio button from radioGroup
int selectedId = rgSuggestWill.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
editor.putString("suggestionwill",radioButton.getText().toString());
if (spReviewer.getSelectedItem().toString().equals("Please choose")){
AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please choose your reviewer");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else{
editor.putString("reviewer",spReviewer.getSelectedItem().toString());
Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
startActivity(intent);
}
editor.apply();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
startActivity(intent);
}
}
Activity B:
public class NewSuggestion2 extends AppCompatActivity {
private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public static final int RequestPermissionCode = 1 ;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion2);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION (Cont..)");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
btnCamera=findViewById(R.id.btnCamera);
EnableRuntimePermission();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
btnGallery=findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
startActivity(intent);
}
});
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgAttach.setImageBitmap(null);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 7 && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgAttach.setImageBitmap(bitmap);
}
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imgAttach.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
Manifest.permission.CAMERA))
{
Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onBackPressed() {
}
}
Assign value to present,details,benefit from sharedpref
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));
In Activity B make sure you save data in onBackPressed()
#Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}
You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.
#Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.commit();
}
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);
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();
}
}
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);
I have have a problem here with my code. I want to open the next Activity using submit button but I'm having issues. Can anybody help me on the mistake I am making so that I can implement it? Thanks
public class Chairperson extends Activity implements View.OnClickListener{
TextView textView;
Button submit_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chairperson);
submit_btn = (Button) findViewById(R.id.submit_btn);
submit_btn.setOnClickListener(this);
textView = (TextView) findViewById(R.id.welcome_txt);
String message = getIntent().getStringExtra("message");
textView.setText(message);
Button submit_btn = (Button) findViewById(R.id.submit_btn);
final TextView submitTextView = (TextView) findViewById(R.id.submitTextView);
final RadioGroup rg1 = (RadioGroup) findViewById(R.id.rg1);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get the checked Radio Button ID from Radio Grou[
int selectedRadioButtonID = rg1.getCheckedRadioButtonId();
// If nothing is selected from Radio Group, then it return -1
if
(selectedRadioButtonID != -1) {
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedRadioButtonID);
String selectedRadioButtonText = selectedRadioButton.getText().toString();
submitTextView.setText(selectedRadioButtonText + " selected.");
} else {
submitTextView.setText("Nothing selected .");
}
}
});
}
#Override
public void onClick(View v) {
startActivity(new Intent(this, ViceChairperson.class));
}
}
I have written a code for your button, delete all previous code for submit_btn in your code and replace with this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addListenerOnButton();
public void addListenerOnButton() {
final Context context = this;
submit_btn = (Button) findViewById(R.id.submit_btn);
submit_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (radioGroup.getCheckedRadioButtonId() == -1)
{
Toast.makeText(context, "Select an option.", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(context, ViceChairperson.class);
startActivity(intent);
finish();
}
}
});
}
}
If you have any issues please let me know.
Just move the line
startActivity(new Intent(getApplicationContext(), ViceChairperson.class));
after the if (selectedRadioButtonID != -1) check. If that check succeeds you start the new activity, if not, nothing is launched.
There's no need for the second onClick method, which is not bound to anything and will never be invoked.