If-else statement and visibility - android - android

I have five checkboxes in my app along with five progressbars, and have called visibility according to checkboxes to make progressbars visible/gone. so is there any alternative to if-else statements to use in visibility method , cus in that case there are endless possibilities in the five checkboxes so i have to write endless if else statements in order to make the progressbars visible/gone in all the possibilities.
for example- if CheckBox1&checkbox2 are checked, make progressbar2 visible
if checkbox1&checkbox3 are checked, make progressbar2 visible
in other words, i want to make Progressbar 1 visible if any One of the checkboxes are checked and progressbar 2 visible if any two are checked and so on..
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
public class Progress extends Activity {
ProgressBar progressBar1;
ProgressBar progressBar2;
CheckBox checkBox1;
CheckBox checkBox2;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
SharedPreferences setprefsd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
setprefsd = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
if (setprefsd.getBoolean("FirstCheckBox", false) == true) {
checkBox1.setChecked(true);
updateProgressBars();
}
if (setprefsd.getBoolean("SecondCheckBox", false) == true) {
checkBox2.setChecked(true);
updateProgressBars();
}
}
public void updateProgressBars() {
progressBar1.setVisibility(View.GONE);
progressBar2.setVisibility(View.GONE);
if (checkBox1.isChecked() && checkBox2.isChecked()) {
progressBar2.setVisibility(View.VISIBLE);
} else if (checkBox1.isChecked()) {
progressBar1.setVisibility(View.VISIBLE);
}
}
}

Short answer
You can use the ternary operator to make the visibility change simpler (instead of ifs).
I guess the approach here would be to count the number of checkboxes, then set the visibilities. You would just have to change your updateProgressBars() method like this:
public void updateProgressBars() {
int nbCheckboxes = 0;
if (checkBox1.isChecked())
nbCheckboxes++;
if (checkBox2.isChecked())
nbCheckboxes++;
progressBar1.setVisibility(nbCheckboxes >= 1 ? View.VISIBLE : View.GONE);
progressBar2.setVisibility(nbCheckboxes >= 2 ? View.VISIBLE : View.GONE);
}
Other remarks
IF statement with boolean expressiosn
Your are using constructs such as:
if (myBooleanExpression == true)
The == true is not needed because you're using a boolean expression here. Use instead:
if (myBooleanExpression)
Using arrays for your variables
If you use several numbered variables that have the same kind of purpose, you might want to consider using arrays.
public class Progress extends Activity {
ProgressBar[] progressBars;
CheckBox[] checkBoxes;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
SharedPreferences setprefsd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
setprefsd = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
progressBars = new ProgressBar[3]; // 3, or whatever number you have
progressBars[0] = (ProgressBar) findViewById(R.id.progressBar1);
progressBars[1] = (ProgressBar) findViewById(R.id.progressBar2);
progressBars[2] = (ProgressBar) findViewById(R.id.progressBar3);
checkBoxes = new CheckBox[3]; // 3 or whatever number you have
checkBoxes[0] = (CheckBox) findViewById(R.id.checkBox1);
checkBoxes[1] = (CheckBox) findViewById(R.id.checkBox2);
checkBoxes[2] = (CheckBox) findViewById(R.id.checkBox3);
checkBoxes[0].setChecked(setprefsd.getBoolean("FirstCheckBox", false));
checkBoxes[1].setChecked(setprefsd.getBoolean("SecondCheckBox", false));
checkBoxes[2].setChecked(setprefsd.getBoolean("ThirdCheckBox", false));
updateProgressBars();
}
public void updateProgressBars() {
int nbCheckBoxes = 0;
for (CheckBox cb : checkBoxes) {
if (cb.isChecked())
nbCheckBoxes++;
}
for (int i = 0; i < progressBars.length; i++) {
progressBars[i].setVisibility(nbCheckboxes > i ? View.VISIBLE : View.GONE);
}
}
}

If you have 3 scenarios to check condition with 9 times.
Like:
if (!mCallType.isIncall() && mCallType.isOutcall() && mCallType.isTelecall()) {
glInCall.setVisibility(View.GONE);
glOutCall.setVisibility(View.VISIBLE);
glTeleCall.setVisibility(View.VISIBLE);
} else if (mCallType.isIncall() && !mCallType.isOutcall() && mCallType.isTelecall()) {
glOutCall.setVisibility(View.GONE);
glInCall.setVisibility(View.VISIBLE);
glTeleCall.setVisibility(View.VISIBLE);
} else if (mCallType.isIncall() && mCallType.isOutcall() && !mCallType.isTelecall()) {
glTeleCall.setVisibility(View.GONE);
glOutCall.setVisibility(View.VISIBLE);
glInCall.setVisibility(View.VISIBLE);
} else {
glOutCall.setVisibility(View.VISIBLE);
glInCall.setVisibility(View.VISIBLE);
glTeleCall.setVisibility(View.VISIBLE);
}
then don't use "IF, ELSE IF" condition.
The Best Replacement is HashMap
HashMap visiblityManager = new HashMap<>(); // Visibility Manage without if else condition.
visiblityManager.put(true, View.VISIBLE);
visiblityManager.put(false, View.GONE);
glInCall.setVisibility((Integer) visiblityManager.get(mCallType.isIncall())); // This Data comes from API or Database. it is a Boolean data.
glOutCall.setVisibility((Integer) visiblityManager.get(mCallType.isOutcall())); // This Data comes from API or Database. it is a Boolean data.
glTeleCall.setVisibility((Integer) visiblityManager.get(mCallType.isTelecall())); // This Data comes from API or Database. it is a Boolean data.
The Problem Solved.
☻♥ Done Keep Code.

Related

Saving UI state when moving between screens/activities Android app

I am doing a multiscreen quiz app. For each question I have a separate activity / screen. At the bottom of each screen there are next/previous "buttons" which navigate to the next/previous screen. Please see the UI example of a screen with a question:
I have a problem though. Let's assume a user selects answers to a question 2 and then clicks "Previous", selects an answer in question 1 and hits "Next".
I would like to save the UI state of the Question 2, so the selected answer stays if a user comes back to a question either by clicking previous or next.
One thing I managed to accomplish is when a user clicks "previous" the UI stays, I used the following code in the manifest file:
android:launchMode="singleTask"
However I cannot make it saved when a user comes bak to a question via "next". Here is my code for the activity with the question 2:
package com.example.justynagolawska.quizappiteration2;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class Question2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
ActionBar actionbar = getSupportActionBar();
// Applies the custom action bar style
getSupportActionBar().setDisplayOptions(actionbar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
// Changes the action bar title
TextView title = (TextView) getSupportActionBar().getCustomView().findViewById(R.id.action_bar_title);
title.setText(R.string.q2_name);
//Getting the intent with score for question 1
Intent question2Intent = getIntent();
final int resultQ1 = question2Intent.getIntExtra("q1result", 0);
// Find the View that shows the next TextView
TextView nextQuestion = (TextView) findViewById(R.id.next);
// Set a click listener on that View
nextQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
//Calculate Question 2 score
int resultQ2 = calculateResultQ2(isCheckBox1Q2, isCheckBox2Q2, isCheckBox3Q2);
Intent question3Intent = new Intent(Question2Activity.this, Question3Activity.class);
question3Intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
question3Intent.putExtra ("q1result", resultQ1);
question3Intent.putExtra ("q2result", resultQ2);
startActivity(question3Intent);
}
});
// Find the View that shows the next TextView
TextView previousQuestion = (TextView) findViewById(R.id.previous);
// Set a click listener on that View
previousQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
Intent question1Intent = new Intent(Question2Activity.this, Question1Activity.class);
startActivity(question1Intent);
}
});
}
/**
* Check which checkbox was selected in the question 2
*
* #param checkBox1 is whether or not the user checked the checkbox1
* #param checkBox2 is whether or not the user checked the checkbox2
* #param checkBox3 is whether or not the user checked the checkbox3
* #return the score the user got for question 2
*/
private int calculateResultQ2(boolean checkBox1, boolean checkBox2, boolean checkBox3) {
int result = 0;
if (checkBox1 && checkBox2 && checkBox3) {
result = 1;
}
return result;
}
I would appreciate very much if anyone could help me out. Thank you!
EDIT: Below is my working code using sharedPreferences, the solution proposed by #tahsinRupam
package com.example.justynagolawska.quizappiteration2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class Question2Activity extends AppCompatActivity {
SharedPreferences mypref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
final CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
final CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
final CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
mypref = PreferenceManager.getDefaultSharedPreferences(this);
ActionBar actionbar = getSupportActionBar();
// Applies the custom action bar style
getSupportActionBar().setDisplayOptions(actionbar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
// Changes the action bar title
TextView title = (TextView) getSupportActionBar().getCustomView().findViewById(R.id.action_bar_title);
title.setText(R.string.q2_name);
//Getting the intent with score for question 1
Intent question2Intent = getIntent();
final int resultQ1 = question2Intent.getIntExtra("q1result", 0);
// Find the View that shows the next TextView
TextView nextQuestion = (TextView) findViewById(R.id.next);
// Set a click listener on that View
nextQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
//Getting the answer to question 2 checkbox 1
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
//Calculate Question 2 score
int resultQ2 = calculateResultQ2(isCheckBox1Q2, isCheckBox2Q2, isCheckBox3Q2);
Intent question3Intent = new Intent(Question2Activity.this, Question3Activity.class);
question3Intent.putExtra ("q1result", resultQ1);
question3Intent.putExtra ("q2result", resultQ2);
startActivity(question3Intent);
}
});
// Find the View that shows the next TextView
TextView previousQuestion = (TextView) findViewById(R.id.previous);
// Set a click listener on that View
previousQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
Intent question1Intent = new Intent(Question2Activity.this, Question1Activity.class);
startActivity(question1Intent);
}
});
}
/**
* Check which checkbox was selected in the question 2
*
* #param checkBox1 is whether or not the user checked the checkbox1
* #param checkBox2 is whether or not the user checked the checkbox2
* #param checkBox3 is whether or not the user checked the checkbox3
* #return the score the user got for question 2
*/
private int calculateResultQ2(boolean checkBox1, boolean checkBox2, boolean checkBox3) {
int result = 0;
if (checkBox1 && checkBox2 && checkBox3) {
result = 1;
}
return result;
}
#Override
protected void onPause() {
super.onPause();
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
if(isCheckBox1Q2 == true){
mypref.edit().putBoolean("Iscb1Checked", true).apply();
}
else if(isCheckBox1Q2 == false){
mypref.edit().putBoolean("Iscb1Checked", false).apply();
}
if(isCheckBox2Q2 == true){
mypref.edit().putBoolean("Iscb2Checked", true).apply();
}
else if(isCheckBox2Q2 == false){
mypref.edit().putBoolean("Iscb2Checked", false).apply();
}
if(isCheckBox3Q2 == true){
mypref.edit().putBoolean("Iscb3Checked", true).apply();
}
else if(isCheckBox3Q2 == false){
mypref.edit().putBoolean("Iscb3Checked", false).apply();
}
}
#Override
protected void onResume() {
super.onResume();
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
if(mypref.contains("Iscb1Checked")){
if(mypref.getBoolean("Iscb1Checked",false)){
checkBox1Q2.setChecked(true);
}
}
if(mypref.contains("Iscb2Checked")){
if(mypref.getBoolean("Iscb2Checked",false)){
checkBox2Q2.setChecked(true);
}
}
if(mypref.contains("Iscb3Checked")){
if(mypref.getBoolean("Iscb3Checked",false)){
checkBox3Q2.setChecked(true);
}
}
}
}
Please note that I replaced the below in the onPause(); method as I was getting null exception:
checkBox1Q2.isChecked()
!checkBox1Q2.isChecked()
with
isCheckBox1Q2 == true
isCheckBox1Q2 == false
You can use SharedPreference to store your value.
1) Declare checkbox and SharedPreference publicly:
CheckBox checkBox1Q2;
CheckBox checkBox2Q2;
CheckBox checkBox3Q2;
SharedPreferences mypref;
2) In your onCreate() initialize SharedPreference:
mypref = PreferenceManager.getDefaultSharedPreferences(this);
3) Save Checkbox states in onPause() (cause onPause() is called when the back button is pressed). You could declare in onStop() or onDestroy() too.
#Override
protected void onPause() {
super.onPause();
if(checkBox1Q2.isChecked()){
mypref.edit().putBoolean("Iscb1Checked", true).apply();
}
else if(!checkBox1Q2.isChecked()){
mypref.edit().putBoolean("Iscb1Checked", false).apply();
}
if(checkBox2Q2.isChecked()){
mypref.edit().putBoolean("Iscb2Checked", true).apply();
}
else if(!checkBox2Q2.isChecked()){
mypref.edit().putBoolean("Iscb2Checked", false).apply();
}
if(checkBox3Q2.isChecked()){
mypref.edit().putBoolean("Iscb3Checked", true).apply();
}
else if(!checkBox3Q2.isChecked()){
mypref.edit().putBoolean("Iscb3Checked", false).apply();
}
}
4) Get CheckBox states in onResume() method:
#Override
protected void onResume() {
super.onResume();
if(mypref.contains("Iscb1Checked")){
if(mypref.getBoolean("Iscb1Checked",false)){
checkBox1Q2.setChecked(true);
}
}
if(mypref.contains("Iscb2Checked")){
if(mypref.getBoolean("Iscb2Checked",false)){
checkBox2Q2.setChecked(true);
}
}
if(mypref.contains("Iscb3Checked")){
if(mypref.getBoolean("Iscb3Checked",false)){
checkBox3Q2.setChecked(true);
}
}
}
You're now getting the Checkbox view in onClick. Try to avoid that. Always get views (findViewById) in the initial part of onCreate (After setContentView).

Save CheckBox State to SharedPreferences File in Android

I have a couple of check boxes that I need to save so that when the user opens the Application again, they can see the state that they left the application in. I have tried using the preferences but I can't seem to get the result correctly.
MainActivity.java
package com.example.android.documentchecklist;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
public class MainActivity extends AppCompatActivity {
CheckBox allotment, sscMarkList, hscMarkList, leaving, profomaCap, jeeScoreCard, gapCer, casteCer, casteVal, nonCreamyL, domicileCertificate, photograph, migration, adhaarCard, nationalityCertificate;
boolean hasAllotment, hasSscMarkList, hasHscMarkList, hasLeaving, hasProfoma, hasJeeScore, hasGapCertificate, hasCasteCertificate, hasCasteValidity, hasNonCreamyLayer, hasDomicileCertificate, hasPhoto, hasMigCertificate, hasadhaarCard, hasNationalityCertificate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allotment = (CheckBox) findViewById(R.id.allot);
sscMarkList = (CheckBox) findViewById(R.id.ssc);
hscMarkList = (CheckBox) findViewById(R.id.hsc);
leaving = (CheckBox) findViewById(R.id.leaving);
profomaCap = (CheckBox) findViewById(R.id.profoma);
jeeScoreCard = (CheckBox) findViewById(R.id.jeeScore);
gapCer = (CheckBox) findViewById(R.id.gapCertificate);
casteCer = (CheckBox) findViewById(R.id.casteCertificate);
casteVal = (CheckBox) findViewById(R.id.casteValidity);
nonCreamyL = (CheckBox) findViewById(R.id.nonCreamyLayer);
adhaarCard = (CheckBox) findViewById(R.id.adhaarCard);
nationalityCertificate = (CheckBox) findViewById(R.id.nationalityCer);
domicileCertificate = (CheckBox) findViewById(R.id.domicile);
photograph = (CheckBox) findViewById(R.id.photo);
migration = (CheckBox) findViewById(R.id.migration);
}
public void checkBoxClicked(View view) {
int id = view.getId();
if (id == R.id.mahaState) {
migration.setVisibility(View.GONE);
allotment.setText(getString(R.string.allot));
allotment.setVisibility(View.VISIBLE);
hasAllotment = allotment.isChecked();
sscMarkList.setText(getString(R.string.ssc));
sscMarkList.setVisibility(View.VISIBLE);
hasSscMarkList = sscMarkList.isChecked();
hscMarkList.setText(getString(R.string.hsc));
hscMarkList.setVisibility(View.VISIBLE);
hasHscMarkList = hscMarkList.isChecked();
leaving.setText(getString(R.string.leaving));
leaving.setVisibility(View.VISIBLE);
hasLeaving = leaving.isChecked();
profomaCap.setText(getString(R.string.proforma));
profomaCap.setVisibility(View.VISIBLE);
hasProfoma = profomaCap.isChecked();
jeeScoreCard.setText(getString(R.string.jee));
jeeScoreCard.setVisibility(View.VISIBLE);
hasJeeScore = jeeScoreCard.isChecked();
gapCer.setText(getString(R.string.gap_cert));
gapCer.setVisibility(View.VISIBLE);
hasGapCertificate = gapCer.isChecked();
casteCer.setText(getString(R.string.caste_cert));
casteCer.setVisibility(View.VISIBLE);
hasCasteCertificate = casteCer.isChecked();
casteVal.setText(getString(R.string.caste_validity));
casteVal.setVisibility(View.VISIBLE);
hasCasteValidity = casteVal.isChecked();
nonCreamyL.setText(getString(R.string.non_creamy));
nonCreamyL.setVisibility(View.VISIBLE);
hasNonCreamyLayer = nonCreamyL.isChecked();
adhaarCard.setText(getString(R.string.aadhar));
adhaarCard.setVisibility(View.VISIBLE);
hasadhaarCard = adhaarCard.isChecked();
nationalityCertificate.setText(getString(R.string.nationality_cert));
nationalityCertificate.setVisibility(View.VISIBLE);
hasNationalityCertificate = nationalityCertificate.isChecked();
domicileCertificate.setText(getString(R.string.domicile));
domicileCertificate.setVisibility(View.VISIBLE);
hasDomicileCertificate = domicileCertificate.isChecked();
photograph.setText(getString(R.string.photos));
photograph.setVisibility(View.VISIBLE);
hasPhoto = photograph.isChecked();
}
}
#Override
public void onPause() {
super.onPause();
save(allotment.isChecked());
save(sscMarkList.isChecked());
save(hscMarkList.isChecked());
save(leaving.isChecked());
save(profomaCap.isChecked());
save(jeeScoreCard.isChecked());
save(gapCer.isChecked());
save(casteCer.isChecked());
save(casteVal.isChecked());
save(nonCreamyL.isChecked());
save(domicileCertificate.isChecked());
save(photograph.isChecked());
save(migration.isChecked());
save(adhaarCard.isChecked());
save(nationalityCertificate.isChecked());
}
#Override
public void onResume() {
super.onResume();
allotment.setChecked(load());
sscMarkList.setChecked(load());
sscMarkList.setChecked(load());
hscMarkList.setChecked(load());
leaving.setChecked(load());
profomaCap.setChecked(load());
jeeScoreCard.setChecked(load());
gapCer.setChecked(load());
casteCer.setChecked(load());
casteVal.setChecked(load());
nonCreamyL.setChecked(load());
domicileCertificate.setChecked(load());
photograph.setChecked(load());
migration.setChecked(load());
adhaarCard.setChecked(load());
nationalityCertificate.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.apply();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);
}
}
Thank You for your help.
you are using the single key i.e. check to store your all checkbox state so only the state of this call save(nationalityCertificate.isChecked()); will be saved ,so you need to use different keys for different checkboxes
for example
// use different keys to store state of different check boxes
save(allotment.isChecked(),"allotment");
save(sscMarkList.isChecked(),"sscMarkList");
// use same keys to fetch values which were used during save function call
allotment.setChecked(load("allotment"));
sscMarkList.setChecked(load("sscMarkList"));
private void save(final boolean isChecked, String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean load(String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, false);
}
Note: you can also initialize your shared preference like your CheckBox views in onCreate or onStart only once instead of re-initializing it every time in save

How can i have a handler if one of these fields don't have values when user pressed post?

I have this fields where every field is important and I don't have an idea how to do this. Where I want it if I pressed post there will be a message that not all fields have values. Here is my code.
InsertActivity
package com.example.kun.carkila;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.util.HashMap;
public class InsertActivity extends AppCompatActivity implements View.OnClickListener {
EditText etCarModel,etCarType,etCapacity,etImageURL,etFuelType,etPlateNumber;
Button btnPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etCarModel = (EditText)findViewById(R.id.etCarModel);
etCarType = (EditText)findViewById(R.id.etCarType);
etCapacity = (EditText)findViewById(R.id.etCapacity);
etImageURL = (EditText)findViewById(R.id.etImageURL);
etFuelType = (EditText)findViewById(R.id.etFuelType);
etPlateNumber = (EditText)findViewById(R.id.etPlateNumber);
btnPost = (Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
}
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("txtCarModel",etCarModel.getText().toString());
postData.put("txtCarType",etCarType.getText().toString());
postData.put("txtCapacity",etCapacity.getText().toString());
postData.put("txtImage",etImageURL.getText().toString());
postData.put("txtFuelType",etFuelType.getText().toString());
postData.put("txtPlateNumber",etPlateNumber.getText().toString());
PostResponseAsyncTask taskPost = new PostResponseAsyncTask(InsertActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if(s.contains("New records created successfully")){
Toast.makeText(InsertActivity.this, "Car Posted!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(InsertActivity.this, ownerhome.class);
startActivity(in);
}else{
}
}
});
taskPost.execute("http://carkila.esy.es/insert.php");
}
}
Hope for a kind response and I wanted to learn in an easy way. Thank you guys.
Before executing your asynctask you have to check is any EdiText feilds are empty or not. Like
TextUtils.isEmpty(etCarModel.getText().toString())
You have to check for each EditText In starting of OnClick method and if any editText is empty then show alert and do not execute your asynktask.
Check first if each field is empty:
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
if (TextUtils.isEmpty(etCarModel.getText().toString())) {
Toast.makeText(this, "Car model is empty", LENGTH_SHORT).show()
return;
}
postData.put("txtCarModel",etCarModel.getText().toString());
if (TextUtils.isEmpty(etCarType.getText().toString())) {
Toast.makeText(this, "Car type is empty", LENGTH_SHORT).show();
return;
}
postData.put("txtCarType",etCarType.getText().toString());
//and so on
}
Yours is a simple problem. I have, because I needed these checks a lot, created a couple of utility methods for this purpose. You may place them in any class that you want.
safeGetText() to get text from a TextView:
public static String safeGetText(TextView textView, boolean isNullable)
{
String result = null;
if(textView != null)
{
CharSequence text = textView.getText();
if(text != null)
{
result = text.toString();
}
}
if(result == null && !isNullable)
{
// This check is for situations where the text cannot be null.
// Now, I find this utterly pointless, but what the hell.
result = "";
}
return result;
}
'isStringNullOrEmpty()' to check for null/empty strings:
public static boolean isStringNullOrEmpty(#Nullable String input)
{
if (input == null || input.length() <= 0)
{
return true;
}
else
{
return false;
}
}
Although these methods don't do anything magical, they helped me clean up the way I checked for Strings in my TextViews.
When you need to check the input (possibly in onClick()), put up empty checks for each field like:
boolean isEmpty = isStringNullOrEmpty(safeGetText(field, true)); // true/false in arg2 doesn't matter here
You would need to apply this check for every field in your current implementation. You could make arrangements to iterate through all fields in a loop like this:
boolean areFieldsValid = true;
for(TextView field : arrayOfAllFields)
{
boolean isCurrentFieldValid = isStringNullOrEmpty(safeGetText(field, true));
areFieldsValid &= isCurrentFieldValid;
}
// Here, the flag 'areFieldsValid' will only be true if all fields are valid
Let me know if this solves your purpose, and/or if you need more help.
You can use an editText array so that you can use a for loop instead of writing it all over. For key name in Hashmap you can use id name of editText in a for loop
String str = editText[i].getResources().getResourceName(id);
str = str.substring(str.lastIndexOf(":id/") + 4);
postData.put(str,editText[i].getText().toString());
This code will be in a for loop to put all the data.
and in similar way you can check where this strings are null or not.
for(int i=0;i<6;i++){
if(editText[i].getText().toString().equals("")){
//Error alert
}
}
I think this will reduce a lot of LOC.

How to Change a TextView with the values in an EditText

I am completely new to App making and I want to make something in which there are two EditTexts (number only), which are then divided and turned into a percentage and displayed in a TextView. Unfortunately, I have no idea if what I am doing is correct. Here is my code
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class FirstInformation extends Activity {
EditText eT4 = (EditText)findViewById(R.id.editText4);
EditText eT5 = (EditText)findViewById(R.id.editText5);
TextView tV6 = (TextView)findViewById(R.id.textView6);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_information);
if (eT4 != null && eT5 != null){
double numerator = (double) Integer.parseInt(eT4.getText().toString());
double denominator = (double) Integer.parseInt(eT5.getText().toString());
double textView = Math.round(numerator/denominator)*100;
tV6.setText(textView+"");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_information, menu);
return true;
}
public void updateTextView() {
if (eT4 != null && eT5 != null){
double numerator = (double) Integer.parseInt(eT4.getText().toString());
double denominator = (double) Integer.parseInt(eT5.getText().toString());
double textView = Math.round(numerator/denominator)*100;
tV6.setText(textView+"");
}
return;
}
}
Any feedback at all would be great. Thank you so much!
findViewById() in onCreate()
Division by zero
Your issue here is with the following code:
EditText eT4 = (EditText)findViewById(R.id.editText4);
EditText eT5 = (EditText)findViewById(R.id.editText5);
TextView tV6 = (TextView)findViewById(R.id.textView6);
findViewById method returns null for all those calls because you're doing UI related tasks before the setContentView method has finished. So you can declare the variables there and then initialize them after setContentView method.
Just as the other guys said, the findViewById() calls go into the onCreate() method otherwise they shall return null.
One other thing: updateTextView() is never called. You could use a TextWatcher or simply an onClickListener:
tv6.setOnClickListener(new onClickListener() {
#Override
public void onClick(View v) {
updateTextView();
}
});
And the result will be updated every time you click on the result textView. By the way using a TextWatcher (with afterTextChanged() method) is a better practice. I suggest you to take a guide/tutorial and try that ;)

Hiding and showing a single Menu Button

I have a project for an Android class, so I'm still learning and this should be a basic question. We were given a tip calculator and already made some modifications, now we have to add a menu.
When it starts up, it will be in multi-person mode. Gives a text box and Text Field for how many people you want the bill split into. When you hit menu, it should show a Single person mode which eliminates a text box and text field. The menu then changes to show a multi-person mode button in the menu.
I've got everything to work except it's showing both buttons, I cannot figure out how to hide a button temporarily. The main error is:
Cannot invoke setVisibility(int) on the primitive type int
on the statement:
multiple_button.setVisibility(View.GONE);
I've tried every combination of hiding the button I can think of, and think that the above line is correct, but unsure of how make it work.
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
I have this in the code, but it's not doing anything either.
Any help would be greatly appreciated.
edit: code. I've read through the link, but considering I don't have a OnPrepareOptions section, I need to re-read it
package com.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class tipcalc extends Activity
{
public static int one_person_button = Menu.FIRST;
private int multiple_button = Menu.FIRST +1;
static final private int reset_button = Menu.FIRST +2;
private static final int MENU_ITEM = 0;
private EditText txtbillamount;
private EditText txtpeople;
private EditText txtpercentage;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople=0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem itemOne = menu.add(0, one_person_button, Menu.NONE,
R.string.one_person);
MenuItem itemMultiple = menu.add(1, multiple_button, Menu.NONE,
R.string.multiple);
MenuItem itemReset = menu.add(2, reset_button, Menu.NONE,
R.string.reset);
itemOne.setIcon(R.drawable.ic_menu_invite);
itemMultiple.setIcon(R.drawable.ic_menu_allfriends);
itemReset.setIcon(R.drawable.ic_menu_refresh);
one_person_button.setGroupVisible(0, true);
multiple_button.setVisibility(View.GONE);
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (one_person_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.INVISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.INVISIBLE) ;
multiple_button = View.VISIBLE;
one_person_button = View.GONE;
numofpeople = 1; }
else if (multiple_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.VISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.VISIBLE) ;
multiple_button = View.GONE;
one_person_button = View.VISIBLE;
}
return false;
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
txtperperson=(TextView)findViewById(R.id.txtperperson);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
RadioButton poorButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton goodButton = (RadioButton) findViewById(R.id.radioButton2);
RadioButton excellentButton = (RadioButton) findViewById(R.id.radioButton3);
if (poorButton.isChecked()){
percentage = Double.parseDouble(poorButton.getText().toString());
} else if (goodButton.isChecked()){
percentage = Double.parseDouble(goodButton.getText().toString());
} else if (excellentButton.isChecked()){
percentage = Double.parseDouble(excellentButton.getText().toString());
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
txtperperson.setText("");
txttipamount.setText("");
txttotal.setText("");
}
}
Post all of your relavent source code. Without it, we cannot give you specific advice about what is going wrong.
I can tell you though you'll be needing to override onPrepareOptionsMenu() and inside there you'll want to check which mode your in and make the proper button be visible. But you need to call setVisibility(View.VISIBLE); on a reference to the button widget, not on an int.
This page holds the answer to your questions.
try calling setVisibility with 8

Categories

Resources