I've been trying for some days now to figure out why I am not getting a proper output from my app. No errors are showing up in logcat to explain why the output is "NaN" and not the value I'm attempting o calculate. Could someone show me the mistake(s) that I've made? It's a calculator app for my final year school project and I've tried to rectify the issue albeit without much success.
Here is the Main class for the app.
I've tried pretty much anything that has been suggested in various forums for similar issues.
public String educationStr, ethnicity, ldlStr, hdlStr, ageStr, tcStr, sysBPStr, diaBPStr;
public int married=0, education=0, educationSec=0, educationTert=0;
public int smoker=0, ethnicityChk=0;
public int highCholesterol=0;
public int atrialFibrillation=0;
public int familialCVD=0;
public int hypertension=0;
public int sex=0;
public int age=0;
public double tcVal = 0;
public double hdlVal=0;
public double ldlVal = 0;
public int sysBPval = 0;
public int diaBPval = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_calculator);
//spinner for sex choices
Spinner spinnerSex = findViewById(R.id.sexSelect);
ArrayAdapter<CharSequence> adapterSex = ArrayAdapter.createFromResource(this, R.array.SexChoices, simple_spinner_item);
adapterSex.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSex.setAdapter(adapterSex);
spinnerSex.setOnItemSelectedListener(this);
//spinner for marriage choices
Spinner spinnerMarried = findViewById(R.id.marriedSelect);
ArrayAdapter<CharSequence> adapterMarried = ArrayAdapter.createFromResource(this, R.array.YN, simple_spinner_item);
adapterMarried.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerMarried.setAdapter(adapterMarried);
spinnerMarried.setOnItemSelectedListener(this);
//spinner for Ethnicity
Spinner spinnerEthnicity = findViewById(R.id.ethnicitySelect);
ArrayAdapter<CharSequence> adapterEthnicity = ArrayAdapter.createFromResource(this, R.array.EthnicChoices, simple_spinner_item);
adapterEthnicity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEthnicity.setAdapter(adapterEthnicity);
spinnerEthnicity.setOnItemSelectedListener(this);
//spinner for education
Spinner spinnerEducation = findViewById(R.id.EduLevelSpin);
ArrayAdapter<CharSequence> adapterEducation = ArrayAdapter.createFromResource(this, R.array.EduLevel, simple_spinner_item);
adapterEducation.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEducation.setAdapter(adapterEducation);
spinnerEducation.setOnItemSelectedListener(this);
//spinner for smoking history
Spinner spinnerSmoker = findViewById(R.id.smokerSelect);
ArrayAdapter<CharSequence> adapterSmoker = ArrayAdapter.createFromResource(this, R.array.smoke, simple_spinner_item);
adapterSmoker.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSmoker.setAdapter(adapterSmoker);
spinnerSmoker.setOnItemSelectedListener(this);
//spinner for family health --> high cholesterol
Spinner spinnerHighCholesterol = findViewById(R.id.highCholesterolSelect);
ArrayAdapter<CharSequence> adapterHighCholesterol = ArrayAdapter.createFromResource(this, R.array.YN, simple_spinner_item);
adapterHighCholesterol.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerHighCholesterol.setAdapter(adapterHighCholesterol);
spinnerHighCholesterol.setOnItemSelectedListener(this);
//spinner for family health --> A Fib
Spinner spinnerAFib = findViewById(R.id.atrialFibrillationSelect);
ArrayAdapter<CharSequence> adapterAFib =
ArrayAdapter.createFromResource(this, R.array.YN, simple_spinner_item);
adapterAFib.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown
item);
spinnerAFib.setAdapter(adapterAFib);
spinnerAFib.setOnItemSelectedListener(this);
//spinner for family health --> Hypertension
Spinner spinnerHypertension = findViewById(R.id.HBPSpinSelect);
ArrayAdapter<CharSequence> adapterHypertension =
ArrayAdapter.createFromResource(this, R.array.YN,
simple_spinner_item);
adapterHypertension.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinnerHypertension.setAdapter(adapterHypertension);
spinnerHypertension.setOnItemSelectedListener(this);
//spinner for family health --> Hypertension
Spinner spinnerFamilialCVD = findViewById(R.id.familialCVDSpin);
ArrayAdapter<CharSequence> adapterFamilialCVD =
ArrayAdapter.createFromResource(this, R.array.YN,
simple_spinner_item);
adapterFamilialCVD.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinnerFamilialCVD.setAdapter(adapterFamilialCVD);
spinnerFamilialCVD.setOnItemSelectedListener(this);
//declaring button
final Button BtnSave = findViewById(R.id.btnSaveNsend);
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.ageEnter:
EditText enterAge = findViewById(R.id.ageEnter);
ageStr = enterAge.getText().toString();
age = Integer.valueOf(ageStr);
break;
case R.id.sysBPEnter:
EditText enterSys = findViewById(R.id.sysBPEnter);
sysBPStr = enterSys.getText().toString();
sysBPval = Integer.valueOf(sysBPStr);
break;
case R.id.diaBPEnter:
EditText enterDia = findViewById(R.id.diaBPEnter);
diaBPStr = enterDia.getText().toString();
diaBPval = Integer.valueOf(diaBPStr);
break;
case R.id.tcEnter:
EditText enterTC = findViewById(R.id.tcEnter);
tcStr = enterTC.getText().toString();
tcVal = Integer.valueOf(tcStr);
break;
case R.id.hdlEnter:
EditText enterHDL = findViewById(R.id.hdlEnter);
hdlStr = enterHDL.getText().toString();
hdlVal = Integer.valueOf(hdlStr);
break;
case R.id.ldlEnter:
EditText enterLDL = findViewById(R.id.ldlEnter);
ldlStr = enterLDL.getText().toString();
ldlVal = Integer.valueOf(ldlStr);
}
if (ethnicityChk == 1){
Intent RiskCalc1 = new
Intent(getApplicationContext(),displayLinRiskResult.class);
startActivity(RiskCalc1);
} else if (ethnicityChk == 2){
Intent RiskCalc2 = new
Intent(getApplicationContext(),displayDiscrimRiskResult.class);
startActivity(RiskCalc2);
}
}
});
}
#Override
public void onItemSelected(AdapterView<?>
adapterView, View view, int i, long l) {
switch(adapterView.getId()){
case R.id.sexSelect:
String sexStr = adapterView.getSelectedItem().toString();
if (sexStr.equalsIgnoreCase("female")){
sex = 1;
}
else if (sexStr.equalsIgnoreCase("male")){
sex = 0;
}
//Toast.makeText(adapterView.getContext(), sex,
Toast.LENGTH_SHORT).show();
break;
case R.id.marriedSelect:
String marriedStr = adapterView.getSelectedItem().toString();
if (marriedStr.equalsIgnoreCase("YES")){
married = 1;
}
else if (marriedStr.equalsIgnoreCase("NO")){
married = 0;
}
//Toast.makeText(adapterView.getContext(), married,
Toast.LENGTH_SHORT).show();
break;
case R.id.smokerSelect:
String smokerStr = adapterView.getSelectedItem().toString();
if (ethnicity.equalsIgnoreCase("Afro-Caribbean"))
{if (smokerStr.equalsIgnoreCase("Smoker")){
smoker = 1;
}
else if (smokerStr.equalsIgnoreCase("Non-smoker")){
smoker = 0;
} }
else if (ethnicity.equalsIgnoreCase("Mixed-Caribbean")){
{if (smokerStr.equalsIgnoreCase("Smoker")){
smoker = 0;
}
else if (smokerStr.equalsIgnoreCase("Ex-smoker")){
smoker = 1;
} }}
// Toast.makeText(adapterView.getContext(), smokerStr,
Toast.LENGTH_SHORT);
break;
case R.id.ethnicitySelect:
ethnicity = (String) adapterView.getSelectedItem();
if (ethnicity.equals("Afro-Caribbean")||
(ethnicity.equals("Indo-Caribbean"))){
ethnicityChk = 1;
}
else if (ethnicity.equals("Mixed-Caribbean")){
ethnicityChk = 2;
}
//Toast.makeText(adapterView.getContext(), ethnicityStr,
Toast.LENGTH_SHORT);
break;
case R.id.EduLevelSpin:
educationStr = (String) adapterView.getSelectedItem();
//Toast.makeText(adapterView.getContext(),education,
Toast.LENGTH_SHORT);
if (educationStr.equalsIgnoreCase("Secondary")){
educationSec = 1;
educationTert = 0;
education = 1;
}
else if (educationStr.equalsIgnoreCase("Tertiary")){
educationSec = 1;
educationTert = 1;
education = 1;
}
else {
education = 1;
educationSec = 0;
educationTert = 0;
}
break;
case R.id.highCholesterolSelect:
String highCholesterolStr = (String)
adapterView.getSelectedItem();
if (highCholesterolStr.equalsIgnoreCase("YES")){
highCholesterol = 1;
}
else if (highCholesterolStr.equalsIgnoreCase("NO")){
highCholesterol = 0;
}
//Toast.makeText(adapterView.getContext(),
highCholesterolStr,Toast.LENGTH_SHORT);
break;
case R.id.atrialFibrillationSelect:
String AfibStr = (String) adapterView.getSelectedItem();
if (AfibStr.equalsIgnoreCase("YES")){
atrialFibrillation = 1;
}
else if (AfibStr.equalsIgnoreCase("NO")){
atrialFibrillation = 0;
}
// Toast.makeText(adapterView.getContext(),
AfibStr,Toast.LENGTH_SHORT);
break;
case R.id.HBPSpinSelect:
String HBPstr = (String) adapterView.getSelectedItem();
if (HBPstr.equalsIgnoreCase("YES")){
hypertension = 1;
}
else if (HBPstr.equalsIgnoreCase("NO")){
hypertension = 0;
}
//Toast.makeText(adapterView.getContext(),
HBPstring,Toast.LENGTH_SHORT);
break;
case R.id.familialCVDSpin:
String famCVDStr = (String) adapterView.getSelectedItem();
if (famCVDStr.equalsIgnoreCase("YES")){
familialCVD = 1;
}
else if (famCVDStr.equalsIgnoreCase("NO")){
familialCVD = 0;
}
//Toast.makeText(adapterView.getContext(),
famCVDString,Toast.LENGTH_SHORT);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
Here is the class used to output the result:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_lin_risk);
TextView RiskViewLinRisk = findViewById(R.id.RiskViewLinRisk);
float LinRisk = (float) ((-16.13) + (0.119 * age) - (1.333 * sex)
+ (1.502 * married) + (2.619 * smoker) - (0.555 * (tcVal /
hdlVal)) + (0.026 *ldlVal) + (1.952 * highCholesterol) + (2.867
* atrialFibrillation) + (4.272 * hypertension) + (1.957 *
familialCVD));
String LinRiskStr = Float.toString(LinRisk);
RiskViewLinRisk.setText(LinRiskStr);
}
Just to give a bit more context than in the comments, double division in Java can return a NaN which stands for "not a number". This happens when you divide 0.0 by 0.0, but can also happen if you take the square root of a negative number.
Because Java implements the IEEE standard for NaN, it guarantees that NaN is never equal to itself. In fact, the only comparison that returns true is NaN != NaN. There's a very famous puzzle:
float x = //...
if (x != x)
System.out.println("Foo");
The question is "initialize x to a value which guarantees that Foo is printed". The answer is Float.NaN, because NaN is not equal to itself. Also, this is the only value that could work. All other values in Java would not solve this puzzle.
For this reason, a solution used lots of times to identify if a number is NaN is:
public boolean isNan(float x) {
return x != x;
}
(Since Java 8 a method exists in the standard lib to verify if a number is NaN)
You could use this to check the result of the division you're doing and avoid displaying NaN when you don't want to.
To display the values after you click on the button you have to run again the calculation and display it. I recommend extracting it into a method:
public float calculateLinRisk() {
return (float) ((-16.13) + (0.119 * age) - (1.333 * sex)
+ (1.502 * married) + (2.619 * smoker) - (0.555 * (tcVal /
hdlVal)) + (0.026 *ldlVal) + (1.952 * highCholesterol) + (2.867
* atrialFibrillation) + (4.272 * hypertension) + (1.957 *
familialCVD));
}
public void displayCurrentLinRisk() {
// This can also be a field in the main activity to
// avoid multiple calls to findViewById
TextView RiskViewLinRisk = findViewById(R.id.RiskViewLinRisk);
float LinRisk = calculateLinRisk()
String LinRiskStr = Float.toString(LinRisk);
RiskViewLinRisk.setText(LinRiskStr);
}
onCreate becomes:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_lin_risk);
displayCurrentLinRisk();
}
Then you can use this at the end of click listener
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ...
displayCurrentLinRisk();
}
}
Related
We are trying to use this array of integers in other methods. Setting the final shuffled Array to a global variable has become next to impossible. We have set other variable as global. The goal here is to have a new int [] fix array every time a button is clicked. We have been able to generate a random int [] ar but can not utilize the array in other methods. So our questions after making the random int [] ar how can we use it in the onClickBtnOne method? Code with comments below
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3,btn4,btn5,btn6;
String T1,T2,T3,T4,T5,T6;
int test[] = new int[7];
int count = 0;
int v1,v2,v3,v4,v5,v6;
int[] fix = {3,2,1,4,6,5};
// Trying to not use above values
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
main(null);
}
// end onCeate
public static void main(String args[]) {
int [] fix = {1,2,3,4,5,6};
shuffleArray(fix);
// Want to USE this fix shuffleArray
//==================================
for (int i = 0; i < fix.length; i++) {
System.out.print(fix[i] + ",");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int [] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void onClickBtnOne(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
count = count + 1;
v1 = count;
test[v1] = count;
if(fix[0] == test[v1]){
// Need a global fix[] here
// =========================
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
The array you are trying to use does not have an add method you need to put the values in from another variable like this ar[i] = a; So if you use this type of Array declaration List value = new ArrayList<>(); where you declared the other global variable life will be much easier. Modified code below
This will do the shuffle NOTICE value.clear() without this the List will grow each time it is initialized
public void shf(View view){
value.clear();
for (int i = 1; i <= 6; i++) {
value.add(i);
}
Collections.shuffle(value);
}
And here is your test method call value.get(index) Arrays are ZERO based
public void on1(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
if(value.get(0) == 1){
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
I wrote the core to add PDF pages to shared-preference for bookmarks, but when I click the image neither the image get changed nor the page number added to the book mark list.
Below is my code. It show me no error and image get clicked but the page number not added to spinner for book mark list.
Before I used a textview for the task and that was working fine but now I want a tag image to get changed when I tag or un-tag a page.
#EActivity(R.layout.activity_main)
#OptionsMenu(R.menu.actionbar)
public class PDFViewActivity extends SherlockActivity implements OnPageChangeListener, View.OnClickListener {
public static final String SAMPLE_FILE = "myfile.pdf";
public static final String KEY_BOOKMARKS = "bookmarks_pages";
#ViewById
PDFView pdfView;
#NonConfigurationInstance
String pdfName = SAMPLE_FILE;
#NonConfigurationInstance
Integer pageNumber = 1;
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
Spinner bookmarkSp;
ArrayAdapter<String> dataAdapter;
private final int TotalPages = 57;
#AfterViews
void afterViews() {
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
display(pdfName, false);
}
int check = 0;
private void display(String assetFileName, boolean jumpToFirstPage) {
if (jumpToFirstPage) pageNumber = 1;
int x = TotalPages;
int[] page_seq = new int[TotalPages];
for (int i = 0; i < TotalPages; i++) {
page_seq[i] = --x;
Log.d("testdesp", "" + page_seq[i]);
}
// .pages(2,1,0)
pdfView.fromAsset(assetFileName)
.defaultPage(TotalPages)
.pages(page_seq)
.onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
((TextView) findViewById(R.id.tv_total_page)).setText("/ " + pdfView.getPageCount());
}
})
.onPageChange(this)
.load();
findViewById(R.id.btn_go).setOnClickListener(this);
findViewById(R.id.tag_btn).setOnClickListener(this);
bookmarkSp = (Spinner) findViewById(R.id.sp_bookmark_list);
List<String> list = new ArrayList<String>();
String pages = sharedpreferences.getString(KEY_BOOKMARKS, "");
String[] split = pages.split(",");
list.add("");
for (String val : split)
if (val.length() > 0) {
int value = Integer.parseInt(val);
// value = pdfView.getPageCount() - (value - 1);
value = TotalPages - (value - 1);
list.add("" + value);
}
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bookmarkSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (++check > 1) {
String val = (String) parent.getItemAtPosition(position);
if (val.length() > 0) {
int value = Integer.parseInt(val);
value = pdfView.getPageCount() - (value - 1);
pdfView.jumpTo(value);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
bookmarkSp.setAdapter(dataAdapter);
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
((EditText) findViewById(R.id.et_page_number)).setText(pageCount - (pageNumber - 1) + "");
if (check(page))
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.tagged);
else
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.untaged);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean displaying(String fileName) {
return fileName.equals(pdfName);
}
#Override
public void onClick(View view) {
view.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_out));
switch (view.getId()) {
case R.id.btn_go:
int page = Integer.parseInt(((EditText) findViewById(R.id.et_page_number)).getText().toString());
page = TotalPages - (page - 1);
pdfView.jumpTo(page);
break;
case R.id.tag_btn:
if (((ImageView) findViewById(R.id.tag_btn)).getDrawable().getConstantState() == getResources().getDrawable(R.drawable.untaged).getConstantState() ) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "") + pageNumber + ",").commit();
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.tagged);
dataAdapter.add(pdfView.getPageCount() - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
} else if (((ImageView) findViewById(R.id.tag_btn)).getDrawable().getConstantState() == getResources().getDrawable(R.drawable.tagged).getConstantState() ) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "").replace(pageNumber + ",", "")).commit();
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.untaged);
dataAdapter.remove(TotalPages - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
}
break;
}
}
boolean check(int page) {
String number = sharedpreferences.getString(KEY_BOOKMARKS, "");
Log.d("testdisp", pdfView.getPageCount() + " ** " + number + " ****" + number.contains(page + ","));
return number.contains(page + ",");
}
}
I resolved my issue by adding a drawable resource
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/tagged" />
<item android:state_checked="false" android:drawable="#drawable/untaged" />
</selector>
and made below changes in my java activity code.
if (((CheckBox) findViewById(R.id.chk_tag)).isChecked()) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "") + pageNumber + ",").commit();
((CheckBox) findViewById(R.id.chk_tag)).setChecked(true);
dataAdapter.add(pdfView.getPageCount() - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
} else {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "").replace(pageNumber + ",", "")).commit();
((CheckBox) findViewById(R.id.chk_tag)).setChecked(false);
}
I have two spinners, the information on the 2nd spinner is based on the 1st spinner selection
EXAMPLE
SPINNER 1 PROTEIN DAIRY FRUITS
IF SPINNER 1 IS SET WITH PROTEIN then SPINNER 2 EGG CHICKEN
IF SPINNER 1 IS SET WITH FRUITS then SPINNER 2 APPLE ORANGE
Last value selected SPINNER 2 ORANGE
Now I want to preserve the last values selected of the SPINNER1 and SPINNER2, I am using SharedPreferences to accomplish this, it works as expected for SPINNER 1 FRUITS
Position 2 however for SPINNER2 it does not set the last value selected even though the position is correct position 1 when it is called onStart(); it selects the 1st value that is on the array APPLE
Any help would be appreciated
Thanks
public class TEST extends AppCompatActivity implements View.OnTouchListener {
SharedPreferences sharedPrefStoreInfo, sharedPrefGetInfo;
public String keyRow1, getBackInformationRow1;
String concatenateInfoRow1, currentDateString, concatenateInfoTotals, getBackInformationTotals,
getBackInformationParseTotals[],
getBackInformationParseRow1[]
;
// declare adaptors to bind with spinners
ArrayAdapter<String> spinnerFoodCategoryRow1Adapter;
// declare the references for the UI elements
public static Spinner spinnerFoodCategoryRow1,
spinnerFoodNameRow1,;
private String[] oilsFoodInformation, fruitsFoodInformation, foodCategoryInformation;
TextView day, date, textViewProteinRow1, textViewCarbsRow1, textViewFatRow1, textViewCaloriesRow1,
textViewDailyTotalProtein, textViewDailyTotalCarbs, textViewDailyTotalFat, textViewDailyTotalCalories
;
EditText editRow1;
String textInputRow1, textInputRow1ResultProtein, textInputRow1ResultCarbs, textInputRow1ResultFat,
textInputRow1ResultCalories,
dailyTotalProtein, dailyTotalCarbs, dailyTotalFat, dailyTotalCalories
;
int gramsEditTextInputParseRow1;
double resultIntProteinRow1, resultIntCaloriesRow1, resultIntCarbsRow1, resultIntFatRow1,;
double proteinInfoRule3Row1, carbsInfoRule3Row1, fatInfoRule3Row1, caloriesInfoRule3Row1,;
public String foodNameTempRow1,;
double canolaProtein = 0;
double canolaCarbs = 0;
double canolaFat = 1;
double canolaCalories = 8.84;
double coconutOilProtein = 0;
double coconutOilCarbs = 0;
double coconutOilFat = 1;
double coconutOilCalories = 8.62;
double cornProtein = 0;
double cornCarbs = 0;
double cornFat = 1;
double cornCalories = 9;
double applesProtein = 0;
double applesCarbs = 0;
double applesFat = 0;
double applesCalories = 0;
double apricotsProtein = 0;
double apricotsCarbs = 0;
double apricotsFat = 0;
double apricotsCalories = 0;
double bananasProtein = 0;
double bananasCarbs = 0;
double bananasFat = 0;
double bananasCalories = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_tracker_layout); -
editRow1 = (EditText) findViewById(R.id.editRow1);
textViewProteinRow1 = (TextView) findViewById(R.id.textViewProteinR1);
textViewCarbsRow1 = (TextView) findViewById(R.id.textViewCarbsR1);
textViewFatRow1 = (TextView) findViewById(R.id.textViewFatR1);
textViewCaloriesRow1 = (TextView) findViewById(R.id.textViewCaloriesR1);
spinnerFoodCategoryRow1 = (Spinner) findViewById(R.id.spinner1R1);
spinnerFoodNameRow1 = (Spinner) findViewById(R.id.spinner2R1);
initializeSpinnerFoodCategoryAdapters();
// CHANGE THE FONT SIZE OF SPINNER FOOD CATEGORY
spinnerFoodCategoryRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Change the selected item's text color
((TextView) view).setTextColor(Color.BLACK);
((TextView) view).setTextSize(12);
getSelectedFoodCategoryRow1(); // **
// THIS IS TO CHANGE THE FONT SIZE OF SPINNER FOOD NAME
spinnerFoodNameRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Change the selected item's text color
((TextView) view).setTextColor(Color.BLACK);
((TextView) view).setTextSize(10);
getSelectedFoodNameRow1();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});// end
} // end
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}// End Main
public void initializeSpinnerFoodCategoryAdapters() {
Resources res = getResources();
spinnerFoodCategoryRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
spinnerFoodCategoryRow1.setAdapter(spinnerFoodCategoryRow1Adapter);
spinnerFoodCategoryRow2Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
spinnerFoodCategoryRow2.setAdapter(spinnerFoodCategoryRow2Adapter);
}
public String getSelectedFoodCategoryRow1() {
Resources res = getResources();
String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
// FOOD NAME OILS ROW1
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0) {
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoOils));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1", selectedPosition);
editor.commit();
return selectedspinnerFoodCategoryRow1;
}
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 2) {
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoFruits));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1", selectedPosition);
editor.commit();
return selectedspinnerFoodCategoryRow1;
}
return selectedspinnerFoodCategoryRow1;
}
// RETRIEVE INFO FOODNAME FROM THE SPINNER ROW1
public String getSelectedFoodNameRow1() {
Resources res = getResources();
String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
String selectedspinnerFoodNameRow1 = (String) spinnerFoodNameRow1.getSelectedItem();
foodCategoryInformation = res.getStringArray(R.array.SpinnerArrayInfoFoodCategory);
oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);
fruitsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoFruits);
for (int n = 0; n < foodCategoryInformation.length; n++) {
// SELECTS INFORMATION ON THE FOOD CATEGORY SPINNER
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == n) {
// SELECT TYPE OF FOOD CATEGORY
switch (selectedspinnerFoodCategoryRow1) {
case "OILS":
foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;
// ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN OILS
for (int i = 0; i < oilsFoodInformation.length; i++) {
// SELECT FOOD NAME BASED ON POSITION IN DAIRY
if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1-OILS", i);
editor.commit();
if (selectedspinnerFoodNameRow1.equals("Canola")) {
// ASSIGN THE FOOD NAME SELECTED TO A
// foodNameTempRow1 VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
// ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
// THE CALCULATION CLICK BUTTON
proteinInfoRule3Row1 = canolaProtein;
carbsInfoRule3Row1 = canolaCarbs;
fatInfoRule3Row1 = canolaFat;
caloriesInfoRule3Row1 = canolaCalories;
} // end IF CANOLA
if (selectedspinnerFoodNameRow1.equals("Coconut Oil")) {
// ASSIGN THE FOOD NAME SELECTED TO A
// foodNameTempRow1 VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = coconutOilProtein;
carbsInfoRule3Row1 = coconutOilCarbs;
fatInfoRule3Row1 = coconutOilFat;
caloriesInfoRule3Row1 = coconutOilCalories;
} // end IF Coconut Oil
if (selectedspinnerFoodNameRow1.equals("Corn")) {
// ASSIGN THE FOOD NAME SELECTED TO A
// foodNameTempRow1 VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = cornProtein;
carbsInfoRule3Row1 = cornCarbs;
fatInfoRule3Row1 = cornFat;
caloriesInfoRule3Row1 = cornCalories;
} // end IF Corn
} // end if OILS POSITION
} // end for OILS
break;
case "FRUITS":
// ASSIGN THE FOOD CATEGORY SELECTED TO A
// foodCategoryTempRow1 VARIABLE
foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;
// ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN DAIRY
for (int i = 0; i < fruitsFoodInformation.length; i++) {
// SELECT FOOD NAME BASED ON POSITION IN DAIRY
if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {
if (selectedspinnerFoodNameRow1.equals("Apples")) {
// ASSIGN THE FOOD SELECTED TO A
// foodNameTempRow1Dairy VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
// ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
// THE CALCULATION CLICK BUTTON
proteinInfoRule3Row1 = applesProtein;
carbsInfoRule3Row1 = applesCarbs;
fatInfoRule3Row1 = applesFat;
caloriesInfoRule3Row1 = applesCalories;
} // end if Apples
if (selectedspinnerFoodNameRow1.equals("Apricots")) {
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = apricotsProtein;
carbsInfoRule3Row1 = apricotsCarbs;
fatInfoRule3Row1 = apricotsFat;
caloriesInfoRule3Row1 = apricotsCalories;
} // end if Apricots
if (selectedspinnerFoodNameRow1.equals("Bananas")) {
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = bananasProtein;
carbsInfoRule3Row1 = bananasCarbs;
fatInfoRule3Row1 = bananasFat;
caloriesInfoRule3Row1 = bananasCalories;
} // end if Bananas
} // end if FRUITS POSITION
} // end for FRUITS
break;
}// END SWITCH
} // IF OUTER
} // OUTER FOR LOOP
return selectedspinnerFoodNameRow1;
}// end METHOD GET FOODNAME ROW1
public boolean onTouch(View v, MotionEvent ev) {
boolean handledHere = false;
final int action = ev.getAction();
final int evX = (int) ev.getX();
final int evY = (int) ev.getY();
int nextImage = -1;
ImageView imageView = (ImageView) v.findViewById(R.id.image);
if (imageView == null)
return false;
Integer tagNum = (Integer) imageView.getTag();
int currentResource = (tagNum == null) ? R.drawable.background_food_tracker : tagNum.intValue();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (currentResource == R.drawable.background_food_tracker) {
handledHere = true;
} else
handledHere = true;
break;
case MotionEvent.ACTION_UP:
int touchColor = getHotspotColor(R.id.image_areas, evX, evY);
ColorTouchAreas ct = new ColorTouchAreas();
int tolerance = 25;
nextImage = R.drawable.background_food_tracker;
if (ct.closeMatch(Color.RED, touchColor, tolerance))
{
// GET INPUT EDIT INFORMATION ENTERED IN GRAMS
textInputRow1 = editRow1.getText().toString();
// VALIDATION NOT EMPTY FIELD EDITTEXT
if (textInputRow1.equals(""))
{
MainActivity.mpButtonSumit.start(); // sound
tToast("Please Enter Weight Of Grams For " + foodNameTempRow1);
}
else {
// SELECTS THE TYPE OF FOOD CATEGORY
switch (foodCategoryTempRow1) {
case "OILS":
// tToast("CLICK OILS ROW1"); // TESTING
for (int i = 0; i < oilsFoodInformation.length; i++) {
if (foodNameTempRow1.equals(oilsFoodInformation[i])) {
MainActivity.mpButtonSumit.start(); // sound
// tToast("STRING VALUE= " + textInputRow1);
if (!"".equals(textInputRow1)) {
gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);
// tToast("INT VALUE= " +
// String.valueOf(gramsEditTextInputParseRow1));
// //TESTING
resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
* proteinInfoRule3Row1);
resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1);
// MAKE CALCULATION CARBS
resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1);
// MAKE CALCULATION FAT
resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
resultIntFatRow1 = (int) Math.round(resultIntFatRow1);
// MAKE CALCULATION CALORIES
resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
* caloriesInfoRule3Row1);
resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1);
// PARSE BACK FROM INTEGER TO STRING TO SET
// THE TEXT WHEN CLICK BUTTON IS CLICED
textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);
// CONCATENATE INFORMATION IN ROW 1
concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
+ " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories
;
// CREATE KEY ROW1
keyRow1 = currentDateString + "-" + "keyRow1"; /
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
// now get Editor
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
// put your value the key would be current
// date + keyRow1
editor.putString(keyRow1, concatenateInfoRow1);
// commits your edits
editor.commit();
} // end if initial edittext is empty
textViewProteinRow1.setText(textInputRow1ResultProtein);
// CARBS GRAMS
textViewCarbsRow1.setText(textInputRow1ResultCarbs);
// FAT GRAMS
textViewFatRow1.setText(textInputRow1ResultFat);
// CALORIES GRAMS
textViewCaloriesRow1.setText(textInputRow1ResultCalories);
} // end if Oils
} // end for Oils
break;
case "FRUITS":
for (int i = 0; i < fruitsFoodInformation.length; i++) {
if (foodNameTempRow1.equals(fruitsFoodInformation[i])) {
MainActivity.mpButtonSumit.start(); // sound
// tToast("STRING VALUE= " + textInputRow1);
if (!"".equals(textInputRow1)) {
gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);
resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
* proteinInfoRule3Row1);
resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1); // ROUND
// UP
// VALUE
// MAKE CALCULATION CARBS
resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1); // ROUND
resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
resultIntFatRow1 = (int) Math.round(resultIntFatRow1); // ROUND
resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
* caloriesInfoRule3Row1);
resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1); //
textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);
// CONCATENATE INFORMATION IN ROW 1
concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
+ " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories
;
// CREATE KEY ROW1
keyRow1 = currentDateString + "-" + "keyRow1";
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
// now get Editor
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putString(keyRow1, concatenateInfoRow1);
// commits your edits
editor.commit();
} // end if initial edittext is empty
// --------------------------------------------------------------------------
textViewProteinRow1.setText(textInputRow1ResultProtein);
textViewCarbsRow1.setText(textInputRow1ResultCarbs);
textViewFatRow1.setText(textInputRow1ResultFat);
textViewCaloriesRow1.setText(textInputRow1ResultCalories);
} // end if FRUITS
} // end for FRUITS
break;
} // END HAND SUBMMIT RED IMAGE BUTTON
else if (ct.closeMatch(Color.WHITE, touchColor, tolerance))
nextImage = R.drawable.background_food_tracker;
;
if (currentResource == nextImage) {
nextImage = R.drawable.background_food_tracker;
}
handledHere = true;
break;
default:
handledHere = false;
} // end switch
if (handledHere) {
if (nextImage > 0) {
imageView.setImageResource(nextImage);
imageView.setTag(nextImage);
}
}
return handledHere;
}// end
// Method
public int getHotspotColor(int hotspotId, int x, int y) {
ImageView img = (ImageView) findViewById(hotspotId);
if (img == null) {
// Log.d ("SubMain", "Hot spot image not found");
return 0;
} else {
img.setDrawingCacheEnabled(true);
Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
if (hotspots == null) {
// Log.d ("ImageAreasActivity", "Hot spot bitmap was not
// created");
return 0;
} else {
img.setDrawingCacheEnabled(false);
return hotspots.getPixel(x, y);
}
}
}// End Method
// ----------------------------------------------------------------------
public void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
// ------------------------------------------------------------------------------------------------------------------
public void onStart() {
super.onStart();
// GET INFORMATION BACK FROM SPINNER BASED ON POSITION STORED
sharedPrefGetInfo = PreferenceManager.getDefaultSharedPreferences(this);
int positionRow1 = sharedPrefGetInfo.getInt("ROW1", 0);
// tToast(String.valueOf(positionRow1)); //TESTING
if (positionRow1 >= 0) {
// LOAD SPINNER INFORMATION ROW1
spinnerFoodCategoryRow1.setSelection(positionRow1);
}
//---------------------------------------HERE IS THE PROBLEM SETTING THE CORRECT VALUE FOR SPINNER --------------------
//THE SPINNER 2 IS NOT BEING SET
Resources res = getResources();
oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == positionRow1) {
tToast("OILS TYPE TRUE");
int positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);
//THIS IS THE CORRECT POSITION FOR SPINNER 2
tToast("POSITION FOODNAME BACK = " + String.valueOf(positionRow1Oils));
// validation
if (positionRow1Oils >= 0) {
for (int n = 0; n < oilsFoodInformation.length; n++) {
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoOils));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
tToast("Iteration # = " + n);
// LOAD SPINNER INFORMATION ROW1 OILS
if (n == positionRow1Oils) {
tToast("SPINNER FOOD NAME IS SET");
spinnerFoodNameRow1.setSelection(positionRow1Oils); // NOT
// WORKING
}
}
} // end if
}
// -----------------------------------------------------------------------------------------------------------------------
currentDateString = DateFormat.getDateInstance().format(new Date());
keyRow1 = currentDateString + "-" + "keyRow1";
getBackInformationRow1 = sharedPrefGetInfo.getString(keyRow1, "");
// MAKE SURE THE ARRAY KEY IS NOT EMPTY
if (!getBackInformationRow1.equals("")) {
getBackInformationParseRow1 = getBackInformationRow1.split(" - ", 4);
textViewProteinRow1.setText(getBackInformationParseRow1[0]);
textViewCarbsRow1.setText(getBackInformationParseRow1[1]);
textViewFatRow1.setText(getBackInformationParseRow1[2]);
textViewCaloriesRow1.setText(getBackInformationParseRow1[3]);
}
}// end class
To fix my problem I just got the info stored (sharedPref) on onStart(); and set the spinner using the position (positionRow1Oils) gotten from it, on the method selection for spinner1 spinnerFoodNameRow1.setSelection(positionRow1Oils);
public void onStart() {
super.onStart();
positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);
}
public String getSelectedFoodCategoryRow1() {
Resources res = getResources();
String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
//FOOD NAME OILS ROW1
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0)
{
//POPULATE INFORMATION FROM STRINGS XML TO FOOD NAME SPINNERS DEPENDING ON INFORMATION ON SELECTED ON FOOD CATEGORY SPINNER ROW1
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, res.getStringArray(R.array.SpinnerArrayInfoOils));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
//PRESERVE SPINNER INFORMATION ROW1
int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1", selectedPosition);
editor.commit();
*//SET SPINNER FOODNAME OILS WITH THE INFORMATION (POSITION) GOT FROM SHARERE PREFERENCE*
spinnerFoodNameRow1.setSelection(positionRow1Oils);
return selectedspinnerFoodCategoryRow1;
}
It seems that, when a spinner2 information is set based in spinner1 information, to preserve the information from spinner2 it should be set in spinner1 method and not on the onStart();
It hope it helps someone facing the same issue.
I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.
I need to pick a button, 'H' which represents the atomic element in periodic table, as many times as needed, and it has to add up the overall weight number, and display it in the mw_results.
So far, I am only able to display it, for two times, as I had hard coded it the value.
Any ideas how I could keep adding the number, without hard coding it..?
Thanks.!
Below is the code:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeight = {0};
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.H:
mf_result.append(String.valueOf("H"));
mw_result.setText(String.valueOf(123));
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + MoWeight;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
mw_result = (TextView)findViewById(R.id.editText);
g.dismiss();
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.C:
mf_result.append(String.valueOf("C"));
mw_result.setText(String.valueOf(456));
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + MoWeight;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
mw_result = (TextView)findViewById(R.id.editText);
g.dismiss();
}
}
});
g.show();
}
It seems like you're resetting the text view back to 123 and 456 respectively on each click.
It's kinda hard to see exactly what you want, but this might help you to get on the right track:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeightArray = {0}; //rename this for readability -- is this used at all?
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.H:
String sMW= mw_result.getText().toString();
mf_result.append(String.valueOf("H"));
if (sMW.matches("")) {
mw_result.setText(String.valueOf(123));
}
else{
float MoWeight = Float.valueOf(sMW);
MoWeight += 123;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
//mw_result = (TextView)findViewById(R.id.editText); no need for this
g.dismiss();
}
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.C:
String sMW= mw_result.getText().toString();
mf_result.append(String.valueOf("C"));
if (sMW.matches("")) {
mw_result.setText(String.valueOf(456));
}
else{
float MoWeight = Float.valueOf(sMW);
MoWeight += 456;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
//mw_result = (TextView)findViewById(R.id.editText); No need for this
g.dismiss();
}
}
}
});
g.show();
}
Try this:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeight = {0};
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
mw_result.setTag(1);//1 in case you're updating 123 values
mw_result.setTag(2);//2 in case you're updating 456 values
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int key = Integer.parseInt(mw_result.getTag().toString());
if(key==2){
mw_result.setTag(1);//1 in case you're updating 123 values
mf_result.append(String.valueOf("H"));
mw_result.setText(String.valueOf(123));
g.dismiss();
}
else{
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + 1;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int key = Integer.parseInt(mw_result.getTag().toString());
if(key==1){
mw_result.setTag(2);//1 in case you're updating 123 values
mf_result.append(String.valueOf("C"));
mw_result.setText(String.valueOf(456));
g.dismiss();
}
else{
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + 1;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
}
}
});
g.show();
}