I already ask this question several time in stack overflow, I hope this time can somebody show me the correct code, I modify my coding many time still same output.
coding:
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
Button mRedColor;
Button mGreenColor;
Button mYellowColor;
Button[] b=new Button[2];
SharedPreferences mSharedPreferences;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
final Button[] b = new Button[]{(Button) findViewById(R.id.btnRed),
(Button) findViewById(R.id.btnGreen),
(Button) findViewById(R.id.btnYellow),};
mToolbar.setTitle(getResources().getString(R.string.app_name));
if (getColor() != getResources().getColor(R.color.colorPrimary)) {
for (int i = 0 ; i<b.length; i++){
if(b[i].equals(b[0]) ){
b[0].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
else if (b[i].equals(b[1])){
b[1].setBackgroundColor(getColor());
b[i].setEnabled(false);
}else if (b[i].equals(b[2])){
b[2].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
}
}
for (int i = 0; i < b.length; i++) {
b[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) //so we get its id here
{
case (R.id.btnRed):
b[0].setBackgroundColor(getResources().getColor(R.color.colorRed));
storeColor(getResources().getColor(R.color.colorRed));
b[0].setEnabled(false);
break;
case (R.id.btnGreen):
b[1].setBackgroundColor(getResources().getColor(R.color.colorGreen));
storeColor(getResources().getColor(R.color.colorGreen));
b[1].setEnabled(false);
break;
case (R.id.btnYellow):
b[2].setBackgroundColor(getResources().getColor(R.color.colorYellow));
storeColor(getResources().getColor(R.color.colorYellow));
b[2].setEnabled(false);
break;
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit=getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
}
#Override
public void onStop () {
super.onStop();
}
private void storeColor(int color){
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putInt("color", color);
mEditor.apply();
}
private int getColor(){
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("color",
getResources().getColor(R.color.colorPrimary));
return selectedColor;
}
}
The problem i face is in here: The first Button only will be coloured permanently after reopen application...., thanks
Try below code. you will able to change all buttons color but it will store only last selected button color.
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
Button mRedColor;
Button mGreenColor;
Button mYellowColor;
Button[] b = new Button[2];
SharedPreferences mSharedPreferences;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color);
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
final Button[] b = new Button[]{(Button) findViewById(R.id.btnRed),
(Button) findViewById(R.id.btnGreen),
(Button) findViewById(R.id.btnYellow),};
mToolbar.setTitle(getResources().getString(R.string.app_name));
int lastPostion = getButtonPosition();
if (getColor() != getResources().getColor(R.color.colorPrimary)) {
for (int i = 0; i < b.length; i++) {
if (b[i].equals(b[0]) && i == lastPostion) {
b[0].setBackgroundColor(getColor());
b[i].setEnabled(false);
} else if (b[i].equals(b[1]) && i == lastPostion) {
b[1].setBackgroundColor(getColor());
b[i].setEnabled(false);
} else if (b[i].equals(b[2]) && i == lastPostion) {
b[2].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
}
}
for (int i = 0; i < b.length; i++) {
b[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) //so we get its id here
{
case (R.id.btnRed):
b[0].setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
storeColor(getResources().getColor(android.R.color.holo_red_dark), 0);
b[0].setEnabled(false);
break;
case (R.id.btnGreen):
b[1].setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
storeColor(getResources().getColor(android.R.color.holo_green_dark), 1);
b[1].setEnabled(false);
break;
case (R.id.btnYellow):
b[2].setBackgroundColor(getResources().getColor(android.R.color.black));
storeColor(getResources().getColor(android.R.color.black), 2);
b[2].setEnabled(false);
break;
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
}
#Override
public void onStop() {
super.onStop();
}
private void storeColor(int color, int position) {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putInt("color", color);
mEditor.putInt("position", position);
mEditor.apply();
}
private int getColor() {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("color",
getResources().getColor(R.color.colorPrimary));
return selectedColor;
}
private int getButtonPosition() {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("position", 0);
return selectedColor;
}
}
Related
I need every click on the checkbox to increase the percentage in progressBar.
Example: I have two checkboxes, each corresponding to 50% within the progressBar.
I tried several codes, but none worked, I'm a beginner in java
Can someone help me? Please.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
if (preferences.contains("checkbox1") && preferences.getBoolean("checkbox1", false) == true) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox.isChecked()) {
editor.putBoolean("checkbox1", true);
editor.apply();
} else {
editor.putBoolean("checkbox1", false);
editor.apply();
}
}
});
if (preferences.contains("checkbox2") && preferences.getBoolean("checkbox2", false) == true) {
checkBox2.setChecked(true);
} else {
checkBox2.setChecked(false);
}
checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox2.isChecked()) {
editor.putBoolean("checkbox2", true);
editor.apply();
} else {
editor.putBoolean("checkbox2", false);
editor.apply();
}
}
});
}
}
The code of the mediaplayer (which starts under the comment: //Code of the mediaplayer begins) is every time called when I click a button. After some time when I click the button, the sound is not played anymore.
It is like : I click for 10 times and it is returning the sound when I click again it stops and does not work anymore. Thanks for looking, If there is any solution comment below! :D
Logcat:
E/AudioFlinger: no more track names available
E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
E/AudioTrack: AudioFlinger could not create track, status: -12
E/AudioSink: Unable to create audio track
E/ExtendedNuPlayerDecoder: error in opening audio sink. Could be fatal!!!
**Code of the main activity'*:
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;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;
SharedPreferences mypref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//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
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
final SharedPreferences.Editor editor = mypref.edit();
checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
editor.putBoolean("playSounds", !isChecked);
editor.commit();
if (!isChecked){
mp.setVolume(1,1);
mp2.setVolume(1,1);
}else{
mp.setVolume(0,0);
mp2.setVolume(0,0);
}
}
})
;
final boolean playSounds = mypref.getBoolean("playSounds", false);
checkBoxmp.setChecked(!playSounds);
if(playSounds){
mp.setVolume(1,1);
mp2.setVolume(1,1);
}
else{
mp.setVolume(0,0);
mp2.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();
//Code of the mediaplayer begins:
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp.release();
mp = null;
}
});
mp.start();
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
try {
mp2 = new MediaPlayer();
if (playSounds) {
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
mp2.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("wrong.mp3");
mp2.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp2.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp2.release();
mp2 = null;
}
});
mp2.start();
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 mediaplayer main code
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);
checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);
}
}
You are not releasing MediaPlayers. That could be the reason behind this issue. Without touching most of your logic, one way to do this is:
Make mp and mp2, private members of QuizActivity.
public class QuizActivity extends AppCompatActivity {
...
private MediaPlayer mp, mp2;
...
}
Create MediaPlayer whenever required, and release it when playback is done.
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
AssetFileDescriptor afd;
...
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp.release();
mp = null;
}
});
mp.start();
At other places, you will have to perform null checks as shown below, before accessing mp and mp2 to avoid NPE.
if (null != mp && null != mp2) {
if (!isChecked) {
mp.setVolume(1, 1);
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
mp2.setVolume(0, 0);
}
}
Other approach would be to add click-listeners only after creating media players.
This link sheds more light on MediaPlayer release.
And the complete source would look as shown below.
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;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;
SharedPreferences mypref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//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
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
final SharedPreferences.Editor editor = mypref.edit();
checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean("playSounds", !isChecked);
editor.commit();
if (null != mp && null != mp2) {
if (!isChecked) {
mp.setVolume(1, 1);
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
mp2.setVolume(0, 0);
}
}
}
});
final boolean playSounds = mypref.getBoolean("playSounds", false);
checkBoxmp.setChecked(!playSounds);
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();
//Code of the mediaplayer begins:
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
try {
mp2 = new MediaPlayer();
if (playSounds) {
mp2.setVolume(1, 1);
} else {
mp2.setVolume(0, 0);
}
AssetFileDescriptor afd;
afd = getAssets().openFd("wrong.mp3");
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp2.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp2.start();
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 mediaplayer main code
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);
checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);
}
}
There is a lot of countries in this app including India, Pakistan, UAE, South Africa..etc. When clicking on name of a country, a new activity will be opened. It will be saved by share preference and when we open the app, the last activity will be opened. I created an app like this. I want to add one more thing to this app.
I want to go to countries list view by a button from the opened activity. The user can change the country here and when opening the app, the changed country's activity must be opened. If all countries are opened like this, there must be a option for choosing another country. I hope you will do this for me.
The project code which is done by me is given below.
The share preference will work on it. I want an option to change the country option.
** countries Listview (MainActivity)**
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak .class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton =MainActivity new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
}
}
India Activity code
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(India.this, Main2Activity.class);
startActivity(mgButton);
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pak Activity Code
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton1 = new Intent(Pak.this, Main2Activity.class);
startActivity(mgButton1);
}
});
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You are very welcome for this - It took me some time to do and it is working exactly like you want it to.
MainActivity:
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
uae = (CardView) findViewById(R.id.uae);
south = (CardView) findViewById(R.id.south);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle!= null) {
SharedPreferences preferences,preferences1,preferences2,preferences3,preferences4;
SharedPreferences.Editor editor,editor1,editor2,editor3,editor4;
preferences = getSharedPreferences("pref", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences1 = getSharedPreferences("pref1", Context.MODE_PRIVATE);
editor1 = preferences1.edit();
editor1.clear();
editor1.apply();
preferences2 = getSharedPreferences("pref2", Context.MODE_PRIVATE);
editor2 = preferences2.edit();
editor2.clear();
editor2.apply();
preferences3 = getSharedPreferences("pref3", Context.MODE_PRIVATE);
editor3 = preferences3.edit();
editor3.clear();
editor3.apply();
preferences4 = getSharedPreferences("pref4", Context.MODE_PRIVATE);
editor4 = preferences4.edit();
editor4.clear();
editor4.apply();
} else {
checkPreferences();
}
//checkPreferences();
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
finish();
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak.class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
finish();
}
});
uae.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent keraButton = new Intent(MainActivity.this, Uae.class);
clickedCard = "Button 3";
keraButton.putExtra("fromMain3", clickedCard);
startActivity(keraButton);
finish();
}
});
south.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ButtonactivityIntent = new Intent(MainActivity.this, South.class);
clickedCard = "Button 4";
ButtonactivityIntent.putExtra("fromMain4", clickedCard);
startActivity(ButtonactivityIntent);
finish();
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
////U A E Preference
prefs = getSharedPreferences("pref3", MODE_PRIVATE);
if (prefs.getString("txt3", "").equals("") || prefs.getString("lastActivity3", "").equals("")) {
} else {
String txt2 = prefs.getString("txt3", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Uae.class);
mgButton.putExtra("fromMain3", txt2);
startActivity(mgButton);
finish();
}
//// SOUTH AFRICA Preference
prefs = getSharedPreferences("pref4", MODE_PRIVATE);
if (prefs.getString("txt4", "").equals("") || prefs.getString("lastActivity4", "").equals("")) {
} else {
String txt2 = prefs.getString("txt4", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, South.class);
mgButton.putExtra("fromMain4", txt2);
startActivity(mgButton);
finish();
}
}
}
India.java:
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(India.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pakistan.java
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(Pak.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You can repeat the process for all the other countries. In MainActivity where I check if (bundle!= null) can be simplified, but it is working.
This is my settings menu, it's a series of 9 imagebuttons that should change image depending on the preferences. When an imagebutton is pressed it should change the boolean value of a preference so that another activity can act accordingly.
Currently it populates the imagebuttons based on the defaultvalue's but changes made within the settings menu do not seem to be permanent.
public class SettingsActivity extends PreferenceActivity {
ImageButton[] level = new ImageButton[9];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
level[0] = (ImageButton) findViewById(R.id.imageButton);
level[1] = (ImageButton) findViewById(R.id.imageButton2);
level[2] = (ImageButton) findViewById(R.id.imageButton3);
level[3] = (ImageButton) findViewById(R.id.imageButton4);
level[4] = (ImageButton) findViewById(R.id.imageButton5);
level[5] = (ImageButton) findViewById(R.id.imageButton6);
level[6] = (ImageButton) findViewById(R.id.imageButton7);
level[7] = (ImageButton) findViewById(R.id.imageButton8);
level[8] = (ImageButton) findViewById(R.id.imageButton9);
PopulateButtons();
}
public void PopulateButtons(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
for (int i = 0; i < 9; i++) {
String prefKey = String.format("lev%s", i);
System.out.println(prefKey);
if (preferences.getBoolean(prefKey, false) == true) {
level[i].setBackgroundResource(R.mipmap.settings_verbs);
level[i].setOnClickListener(mySettingsHandler);
} else {
level[i].setBackgroundResource(R.mipmap.ic_launcher);
level[i].setOnClickListener(mySettingsHandler);
}
}
}
View.OnClickListener mySettingsHandler = new View.OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
System.out.println("Running populate method");
for (int i = 0; i < 9; i++) {
if (v.getId() == level[i].getId()) {
String prefKey = String.format("lev%s", i);
if (preferences.getBoolean(prefKey, false) == false) {
System.out.println("Yep");
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(prefKey, true);
editor.commit();
level[i].setBackgroundResource(R.mipmap.settings_verbs);
} else {
System.out.println("nope");
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(prefKey, false);
editor.commit();
level[i].setBackgroundResource(R.mipmap.ic_launcher);
}
}
}
}
};
}
You're setting the default values every time onCreate is called. Try
if (savedInstanceState == null) {
PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
}
If I am adding a number in my app let's say upto 15, I want to make sure the next time I open my app no matter if it crashed, phones was restarted, or app was exited; it should continue from number 15 rather than the 0. How can I work on that?
I tried something like this. This is probably wrong not sure how to fix it.
public class MainActivity extends Activity {
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.but);
final TextView txt = (TextView) findViewById(R.id.txt);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
i++;
txt.setText(" " + i);
i++;
editor.putInt("Scores: ", i);
editor.commit();
}
});
}
}
public class MainActivity extends Activity {
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// let i be previously saved value or default to zero
i = app_preferences.getInt("Scores: ",0);
Button btn = (Button) findViewById(R.id.but);
final TextView txt = (TextView) findViewById(R.id.txt);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
i++;
txt.setText(" " + i);
//i++; maybe DONT really increment twice (unless thats what you intended)
editor.putInt("Scores: ", i);
editor.commit();
}
});
}
}