progressBar with 5 checkbox - java

I need progressBar to load the percentage of how many checkboxes are checked.
I tried to use it for 5 checkbox:
"progressbar.setProgress (20)" if it was checked, and if it was not "progressbar.setProgress (-20)"
The progressBar loads only "20%" even if the 5 checkboxes are checked.Can someone help me?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
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);
final CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
final CheckBox checkBox4 = (CheckBox) findViewById(R.id.checkBox4);
final CheckBox checkBox5 = (CheckBox) findViewById(R.id.checkBox5);
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);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox1", false);
progressBar.setProgress(-20);
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);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox2", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
if (preferences.contains("checkbox3") && preferences.getBoolean("checkbox3", false) == true) {
checkBox3.setChecked(true);
} else {
checkBox3.setChecked(false);
}
checkBox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox3.isChecked()) {
editor.putBoolean("checkbox3", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox3", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
if (preferences.contains("checkbox4") && preferences.getBoolean("checkbox4", false) == true) {
checkBox4.setChecked(true);
} else {
checkBox4.setChecked(false);
}
checkBox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox4.isChecked()) {
editor.putBoolean("checkbox4", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox4", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
if (preferences.contains("checkbox5") && preferences.getBoolean("checkbox5", false) == true) {
checkBox5.setChecked(true);
} else {
checkBox5.setChecked(false);
}
checkBox5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox5.isChecked()) {
editor.putBoolean("checkbox5", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox5", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
}
}

Your problem is you always set it to 20 or -20 instead of updating it from its current value. use
progressBar.setProgress(progressBar.getProgress()+20);
or
progressBar.setProgress(progressBar.getProgress()-20);

Related

How to implement the saving of night mode in multiple activities?

I tried using an Inflater to check whether the Switch responsible for activating and deactivating night mode in my Settings activity is enabled or not. The MainActivity doesn't remember the night mode state after relaunching the app.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.activity_settings, null);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
view.findViewById(R.id.night_mode);
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.settings) {
Intent myintent = new Intent(MainActivity.this, Settings.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
Settings.java:
public class Settings extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(final Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.calculator) {
Intent myintent = new Intent (Settings.this, MainActivity.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
I'm not sure what the reason for this is.

Android - How to save checkbox states and after app is closed, the values saved in CheckBoxes persist?

I've been working on the Android SDK platform, and it is a bit unclear how to save an application's state. I'm creating a menu which has CheckBoxes. I do get the idea of SharedPreferences but I'm not able to get my head around the implementation of SharedPreferences in CheckBoxes.
I want those checkboxes (multiple checkboxes) stay checked/unchecked even if the user relaunches the app.
public class MainActivity extends AppCompatActivity {
protected WebView myWebView;
protected TextView text_selection;
protected TextView mOutputText;
public static final String TAG = "mytag";
protected SharedPreferences sharedPreferences;
protected SharedPreferences.Editor editor;
private final String PREFERENCE_FILE_KEY = "myAppPreference";
private Context context;
protected CheckBox animal, fisheries, dairy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
//sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
//Context context = getActivity();
//SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("animal", false);
editor.putBoolean("fisheries", false);
editor.putBoolean("dairy", false);
//editor.putBoolean("checkbox", checkbox.isChecked()));
editor.commit();
this.myWebView = (WebView) findViewById(R.id.webview);
this.text_selection = findViewById(R.id.text_selected);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("------");
//mOutputText = (TextView) findViewById(R.id.tv_output);
mOutputText = findViewById(R.id.textView);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if(task.isSuccessful()){
String token=task.getResult().getToken();
Log.d(TAG, "onComplete: Token: "+token);
mOutputText.setText("Token has been generated");
}else{
mOutputText.setText("Token failed");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
if (sharedPreferences.getBoolean("animal", false)) {
// findItem id function return the id of the menu
menu.findItem(R.id.animal).setChecked(true);
} else if (sharedPreferences.getBoolean("fisheries", false)) {
menu.findItem(R.id.fisheries).setChecked(true);
} else if (sharedPreferences.getBoolean("dairy", false)) {
menu.findItem(R.id.dairy).setChecked(true);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("animal", false);
} else {
item.setChecked(true);
editor.putBoolean("animal", true);
}
break;
case R.id.fisheries:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("fisheries", false);
} else {
item.setChecked(true);
editor.putBoolean("fisheries", true);
}
break;
case R.id.dairy:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("dairy", false);
} else {
item.setChecked(true);
editor.putBoolean("dairy", true);
}
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
}
Below example;
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
editor.putBoolean("dairy", isChecked);
editor.commit();
}
});
Replace the beginning stuff in your onCreate with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
animal.setChecked(getCheckboxStatus("animal"));
animal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("animal", isChecked);
}
}
);
fisheries.setChecked(getCheckboxStatus("fisheries"));
fisheries.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("fisheries", isChecked);
}
}
);
dairy.setChecked(getCheckboxStatus("dairy"));
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("dairy", isChecked);
}
}
);
// Your WebView and Firebase stuff
}
private void saveCheckBoxValue(String key, boolean isChecked) {
editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean getCheckboxStatus(String key) {
return sharedPreferences.getBoolean(key, false);
}
Change the onCreateOptionsMenu function to the following:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
menu.findItem(R.id.animal).setChecked(sharedPreferences.getBoolean("animal", false));
menu.findItem(R.id.fisheries).setChecked(sharedPreferences.getBoolean("fisheries", false));
menu.findItem(R.id.dairy).setChecked(sharedPreferences.getBoolean("dairy", false));
return true;
}
Change the onOptionsItemSelected function to:
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
editor.putBoolean("animal", item.isChecked());
break;
case R.id.fisheries:
editor.putBoolean("fisheries", item.isChecked());
break;
case R.id.dairy:
editor.putBoolean("dairy", item.isChecked());
break;
}
editor.apply();
return super.onOptionsItemSelected(item);
}

Progress bar for counting checkboxes

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();
}
}
});
}
}

cannot apply String values in a Text View array

in if(saveInstanceState != null) I am trying to save the changes of the text in Text Views that happened by whoWon() method to save it in while user rotate the phone and get it back as it was before rotation but it shows me an error that says getText() in TextView cannot be applied to (java.lang.string) , I tried to add .toString() but it didn't work.
public class Multiplayer extends AppCompatActivity {
private TextView mTicTacTextViews [] = new TextView[9];
private Button mButtonX;
private Button mButtonO;
private Button mResult;
private int mcheckAllButtonsClicked =0;
private String TEXT_VIEW_VALUES_KEY = "VALUES OF TEXT VIEW'S";
private String mTextviewValues [] = new String[9];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null)
{
String values[]=savedInstanceState.getStringArray(TEXT_VIEW_VALUES_KEY);
for (int i=0;i<values.length;i++ ) {
mTextviewValues[i]=values[i];
mTicTacTextViews[i].getText(mTextviewValues[i]);
}
}
setContentView(R.layout.activity_tic_tac);
mTicTacTextViews[0] = (TextView) findViewById(R.id.tic_tac_one);
mTicTacTextViews[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[0]);
ifPressed_OButton(mTicTacTextViews[0]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[1] = (TextView) findViewById(R.id.tic_tac_two);
mTicTacTextViews[1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[1]);
ifPressed_OButton(mTicTacTextViews[1]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[2] = (TextView) findViewById(R.id.tic_tac_three);
mTicTacTextViews[2].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[2]);
ifPressed_OButton(mTicTacTextViews[2]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[3] = (TextView) findViewById(R.id.tic_tac_four);
mTicTacTextViews[3].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[3]);
ifPressed_OButton(mTicTacTextViews[3]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[4] = (TextView) findViewById(R.id.tic_tac_five);
mTicTacTextViews[4].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[4]);
ifPressed_OButton(mTicTacTextViews[4]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[5] = (TextView) findViewById(R.id.tic_tac_six);
mTicTacTextViews[5].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[5]);
ifPressed_OButton(mTicTacTextViews[5]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[6] = (TextView) findViewById(R.id.tic_tac_seven);
mTicTacTextViews[6].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[6]);
ifPressed_OButton(mTicTacTextViews[6]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[7] = (TextView) findViewById(R.id.tic_tac_eight);
mTicTacTextViews[7].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[7]);
ifPressed_OButton(mTicTacTextViews[7]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[8] = (TextView) findViewById(R.id.tic_tac_nine);
mTicTacTextViews[8].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[8]);
ifPressed_OButton(mTicTacTextViews[8]);
mcheckAllButtonsClicked+=1;
}
});
mButtonX = (Button) findViewById(R.id.x_button);
mButtonX.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mUserPressed_XButton =true;
}
});
mButtonO = (Button) findViewById(R.id.o_button);
mButtonO.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mUserPressed_OButton =true;
}
});
mTextviewValues [0]=mTicTacTextViews[0].getText().toString();
mTextviewValues [1]=mTicTacTextViews[1].getText().toString();
mTextviewValues [2]=mTicTacTextViews[2].getText().toString();
mTextviewValues [3]=mTicTacTextViews[3].getText().toString();
mTextviewValues [4]=mTicTacTextViews[4].getText().toString();
mTextviewValues [5]=mTicTacTextViews[5].getText().toString();
mTextviewValues [6]=mTicTacTextViews[6].getText().toString();
mTextviewValues [7]=mTicTacTextViews[7].getText().toString();
mTextviewValues [8]=mTicTacTextViews[8].getText().toString();
mResult = (Button) findViewById(R.id.result_button);
mResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
whoWon();
}
});
}
private void whoWon ()
{
mTextviewValues [0]=mTicTacTextViews[0].getText().toString();
mTextviewValues [1]=mTicTacTextViews[1].getText().toString();
mTextviewValues [2]=mTicTacTextViews[2].getText().toString();
mTextviewValues [3]=mTicTacTextViews[3].getText().toString();
mTextviewValues [4]=mTicTacTextViews[4].getText().toString();
mTextviewValues [5]=mTicTacTextViews[5].getText().toString();
mTextviewValues [6]=mTicTacTextViews[6].getText().toString();
mTextviewValues [7]=mTicTacTextViews[7].getText().toString();
mTextviewValues [8]=mTicTacTextViews[8].getText().toString();
if(mTextviewValues[0].equals(mTextviewValues[1]) & mTextviewValues[1].equals(mTextviewValues[2]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[1].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[8]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[0].equals(mTextviewValues[3]) & mTextviewValues[3].equals(mTextviewValues[6]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[1].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[7]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[2].equals(mTextviewValues[5]) & mTextviewValues[5].equals(mTextviewValues[8]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[2].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[6]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[2].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[6]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[6].equals(mTextviewValues[7]) & mTextviewValues[7].equals(mTextviewValues[8]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else Log.i("error" , "whowon didn't work");
}
#Override
protected void onSaveInstanceState(Bundle bundle)
{
super.onSaveInstanceState(bundle);
bundle.putStringArray(TEXT_VIEW_VALUES_KEY,mTextviewValues);
}
}
getText() doesn't take a parameter. mTicTacTextViews[i].getText() returns the text in the view. Are you trying to set the text in the view? If so, you want setText(CharSequence), not CharSequence getText().

Sound is stopping after a period of time

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);
}
}

Categories