I have 2 editText's and I want to handle both inputs with onTextChanged, can I do this with an array if so how, I dont see how I can do it without using arrays. OK, this is the update on what I have.
public class AlphaActivity extends Activity {
private static final String TO_BOX = "TO_BOX";
private static final String FROM_BOX = "FROM_BOX";
// private String updateGuess;
// private String update_label;
private int guess, theFirst, theLast;
//private int count;
private String update_text;
EditText firstText;
EditText secondText;
TextView updateLabel;
Button tooHighButton;
Button tooLowButton;
Button correctButton;
Button newGameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alpha);
if(savedInstanceState == null){
// Just started
theFirst = 0;
theLast = 100;
}
else
{
// App is being restored
theFirst = savedInstanceState.getInt(TO_BOX);
theLast = savedInstanceState.getInt(FROM_BOX);
}
//fromBox = (EditText) findViewById(R.id.firstText);
//toBox = (EditText) findViewById(R.id.secondText);
//fromBox.addTextChangedListener(fromBox);
//toBox.addTextChangedListener(toBox);
updateLabel = (TextView)findViewById(R.id.updateText);
firstText = (EditText)findViewById(R.id.firstText);
firstText.addTextChangedListener(fromBoxListener);
secondText = (EditText)findViewById(R.id.secondText);
secondText.addTextChangedListener(fromBoxListener);
tooHighButton = (Button)findViewById(R.id.guiTooHigh);
tooLowButton = (Button)findViewById(R.id.tooLowGui);
correctButton = (Button)findViewById(R.id.correctGui);
setButtonOnClickListeners();
}
private TextWatcher fromBoxListener = new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
try
{
//theFirst = Integer.parseInt(s.toString());
theFirst = Integer.parseInt(firstText.getText().toString());
theLast = Integer.parseInt(secondText.getText().toString());
if (theFirst > theLast)
{
updateLabel.setText("You must flip your integers");
}
else if (theFirst < 0)
{
updateLabel.setText("You cannot enter a negative number!");
}
guess = (theFirst + theLast) / 2;
updateLabel.setText("Did you think of " + guess + " ?");
} catch (NumberFormatException nfe)
{
updateLabel.setText("You must enter an integer! ");
}
//updateLabel();
}
};
private void setButtonOnClickListeners(){
tooHighButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
theLast = (guess - 1);
guess = (theFirst + theLast) / 2;
if (theFirst < theLast)
{
secondText.setText("" + theLast);
updateLabel.setText("Did you think of " + guess + " ?");
//count++;
} else if (theFirst > theLast)
{
updateLabel.setText("It appears you changed your number!");
} else
{
updateLabel.setText("Did you think of " + guess + " ?");
}
}
});
tooLowButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
theFirst = (guess + 1);
guess = (theFirst + theLast) / 2;
if (theFirst < theLast)
{
firstText.setText("" + theFirst);
updateLabel.setText("Did you think of " + guess + " ?");
//count++;
} else if (theFirst > theLast)
{
updateLabel.setText("It appears you changed your number!");
} else
{
updateLabel.setText("Did you think of " + guess + " ?");
}
}
});
correctButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
updateLabel.setText("Thank you for playing this game!");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.alpha, menu);
return true;
}
}
To accomplish what I think you are asking you can do the following,
editText1.addTextChangedListener(fromBoxListener)
editText2.addTextChangedListener(fromBoxListener)
Now, the code in
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
will run when the text in either of them has changed. I'm not sure if this is what you really want since I don't know how your logic works or what you are trying to accomplish in the end.
Also, since you are parsing an Object that could have non-integers, you may want to wrap it in a try/catch or do some type of error-checking
Have you tried moving your code to the afterTextChanged() method of your TextWatcher?
External listeners get updated before the internal Editor of an EditText during the onTextChanged() phase, so your readings for firstText.getText() and secondText.getText() may not return the results you expect because they haven't been internally updated yet.
Related
What I want my app to do is to calculate an average and display it in a TextView.
I have a layout with two buttons (button0 and button1) and six TextViews. When I press one of the buttons, my app gets the count of the number of clicks it is pressed, and the same thing with the other button. And it also gets the count of the total number of clicks the two buttons are pressed. So if I divide the number of clicks button0 is pressed by the number of total clicks the two buttons are pressed and I multiply it by 100, I get the percentage clicks that button is pressed.
So this is the code:
Button button0, button1;
int click_button0, click_button1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
final TextView times_0_tv = (TextView) view.findViewById(R.id.times_0);
final TextView percentage_0_tv = (TextView) view.findViewById(R.id.percentage_0);
final TextView times_1_tv = (TextView) view.findViewById(R.id.times_1);
final TextView percentage_1_tv = (TextView) view.findViewById(R.id.percentage_1);
final TextView total_clicks_tv = (TextView) view.findViewById(R.id.total_clicks);
button0 = (Button) view.findViewById(R.id.button0);
button1 = (Button) view.findViewById(R.id.button1);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button0 = click_button0 + 1;
total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
if (click_button0 == 1) {
Toast.makeText(getActivity(), "Number 0 has apperared 1 time", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Number 0 has apperared " + click_button0 + " times", Toast.LENGTH_SHORT).show();
}
times_0_tv.setText(String.valueOf(click_button0));
times_1_tv.setText(String.valueOf(click_button1));
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button1 = click_button1 + 1;
total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
if (click_button1 == 1) {
Toast.makeText(getActivity(), "Number 1 has apperared 1 time", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Number 1 has apperared " + click_button1 + " times", Toast.LENGTH_SHORT).show();
}
times_0_tv.setText(String.valueOf(click_button0));
times_1_tv.setText(String.valueOf(click_button1));
}
});
times_0_tv.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String times0String = times_0_tv.getText().toString();
String times1String = times_1_tv.getText().toString();
String totaltimesString = total_clicks_tv.getText().toString();
// convert the String into a double
if (times0String.length() > 0) {
click_button0 = (int) Double.parseDouble(times0String);
}
if (times1String.length() > 0) {
click_button1 = (int) Double.parseDouble(times1String);
}
if (totaltimesString.length() > 0) {
total_clicks = (int) Double.parseDouble(totaltimesString);
}
// calculate re
double percent0calc = calc_percent0();
// set the label for re1Text
percentage_0_tv.setText(Double.toString(percent0calc));
}
});
times_1_tv.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String times0String = times_0_tv.getText().toString();
String times1String = times_1_tv.getText().toString();
String totaltimesString = total_clicks_tv.getText().toString();
// convert the String into a double
if (times0String.length() > 0) {
click_button0 = (int) Double.parseDouble(times0String);
}
if (times1String.length() > 0) {
click_button1 = (int) Double.parseDouble(times1String);
}
if (totaltimesString.length() > 0) {
total_clicks = (int) Double.parseDouble(totaltimesString);
}
// calculate re
double percent1calc = calc_percent1();
// set the label for re1Text
percentage_1_tv.setText(Double.toString(percent1calc));
}
});
}
double calc_percent0() {
return click_button0/total_clicks;
}
double calc_percent1() {
return click_button1/total_clicks;
}
Here is a screenshot of the layout:
The problem comes when I press a button, the percentage is 0%, it doesn't change. The idea is, for example, if I press button0 3 times and button1 1 time, percentage for 0 is 75% and percentage for 1 is 25%. Any idea will be welcomed, thanks!
EDIT: I have deleted implemention of TextWatcher and I have added some lines to the code. It is working fine when I click button0 because it shows the percentage of clicks is 100%, but the moment I click button1, both percentages turn 0, and I don't get any percentage. It seems there is a problem when passing the value of the total clicks to the percentage calc.
Here is the code now for the Fragment:
Button button0, button1;
int click_button0, click_button1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
final TextView times_0_tv = (TextView) view.findViewById(R.id.times_0);
final TextView percentage_0_tv = (TextView) view.findViewById(R.id.percentage_0);
final TextView times_1_tv = (TextView) view.findViewById(R.id.times_1);
final TextView percentage_1_tv = (TextView) view.findViewById(R.id.percentage_1);
final TextView total_clicks_tv = (TextView) view.findViewById(R.id.total_clicks);
button0 = (Button) view.findViewById(R.id.button0);
button1 = (Button) view.findViewById(R.id.button1);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button0 = click_button0 + 1;
total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
if (click_button0 == 1) {
Toast.makeText(getActivity(), "Number 0 has apperared 1 time", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Number 0 has apperared " + click_button0 + " times", Toast.LENGTH_SHORT).show();
}
times_0_tv.setText(String.valueOf(click_button0));
times_1_tv.setText(String.valueOf(click_button1));
percent0 = click_button0/total_clicks;
percentage_0_tv.setText(String.valueOf(percent0));
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button1 = click_button1 + 1;
total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
if (click_button1 == 1) {
Toast.makeText(getActivity(), "Number 1 has apperared 1 time", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Number 1 has apperared " + click_button1 + " times", Toast.LENGTH_SHORT).show();
}
times_0_tv.setText(String.valueOf(click_button0));
times_1_tv.setText(String.valueOf(click_button1));
percent1 = click_button1/total_clicks;
percentage_1_tv.setText(String.valueOf(percent1));
}
});
}
Why don't you just calculate and set the percentage in the buttons onClick? You want to update the percentage when the button is clicked, therefore the logic should be within the buttons OnClickListener, not the TextWatcher.
Also, instead of getting the values from your TextViews, use the variables you already have: int click_button0, click_button1;
Do the calculation in the onClick using the variables values and then set the TextViews value and it should work as intended.
Also, if you are going to try and parse a string as a number double, int etc you should surround it in a try catch in case of an exception. And in this case you should just use Integer.parseInt instead of using parseDouble and then casting it to an int.
Edit: Ah yep, that'd be because you are dividing an int by an int, so the result will also be an int. A quick fix is to cast one of the numbers to a float/double, and when you divide you will get a decimal number.
((double) click_button0) / total_clicks;
You should also update both percentages at the same time, seeing as one number changing affects the other.
Please guys help me! I'm going crazy ! Below is a brief summary of my code that should be used to make a simple subtraction . Should I just read the amount of SCONTRINO and if you put CONTANTI , the field VINCITE , will have as setText SCONTRINO - CONTANTI , same with VINCITE , will CONTANTI.setText SCONTRINO - VINCITE .
But despite everything seems to be well written , when I insert a field , I StackOverflowError by the two Update methods.
public class AssegnaScontoActivity extends Activity {
TextView contanti;
TextView vincite;
TextView scontrino;
Float contantiFloat;
Float vinciteFloat;
Float scontrinoFloat;
public void onCreate(Bundle savedInstanceState) {
//INIZIALIZZAZIONE ACTIVITTY
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.assegna_sconto_activity_landscape);
//--------------------------
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contanti.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
contantiFloat = number;
updateVincite();
}
});
vincite.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
vinciteFloat = number;
updateContanti();
}
});
}
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
vincite.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private void updateContanti()
{
Float total = scontrinoFloat - vinciteFloat; // This is where you apply your function
contanti.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private abstract class TextChangedListener implements TextWatcher
{
public abstract void numberEntered(Float number);
#Override
public void afterTextChanged(Editable s)
{
String text = s.toString();
try
{
Float parsedFloat = Float.parseFloat(text);
numberEntered(parsedFloat);
} catch (NumberFormatException e)
{
Log.w(getPackageName(), "Non si puo' parsare '" + text + "' col numero", e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
}
Your code is going into an infinite loop because you are changing the text when afterTextChanged() is called, which causes afterTextChanged() to be called again and so on until eventually you overflow your call stack.
You can stop this by only setting the text inside updateVincite() and updateContanti() if it is different to the current text.
e.g.:
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
String text = ""+total;
if(!vincite.getText().toString().contentEquals(text))
vincite.setText(text); // need to do that otherwise int will
// be treated as res id.
}
and do the same for updateContanti()
First define contanti and vincite .
Change code as follows.
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);
I have a ListView which has multiple EditTexts per item. When I change an EditText on one item, I'd like it to affect the text on the next item. I'm using an onFocusChanged listener and I can successfully update the underlying data, but My actual focus is lost (and my cursor ends up in weird places). Please review my code and offer any insight. I've been banging my head about this for a while.
Note:
I am not recycling items using a holder, as this was giving me odd behavior and my performance is not suffering. Every time I've tried re-enabling the recycling, things get messier.
I have overriden hasStableIds to return true, but it doesn't seem to make any difference.
Assigning the Listener:
MyFocusChangeListener myFocusListener = new MyFocusChangeListener(myItem, position);
holder.et_min.setOnFocusChangeListener(myFocusListener);
Defining the Listener:
private class MyFocusChangeListener implements View.OnFocusChangeListener{
private EditText et;
private EditText curView;
private ScaleItem item;
private Integer pos;
public MyFocusChangeListener(ScaleItem item, Integer pos){
this.item = item;
this.pos = pos;
}
#Override
public void onFocusChange(View v, boolean hasFocus){
if(!hasFocus){
et = (EditText) v;
System.out.println("EditText lost focus on row: " + et.getText().toString() + " et id: " + et.getId());
if(pos < data.size()){
data.get(pos + 1).setMax(Double.valueOf(et.getText().toString()));
notifyDataSetChanged();
System.out.println("Updated dataset and called notifyDataSetChanged()");
}
} else {
et = (EditText) v;
if(et != null)
System.out.println("EditText just RECEIVED focus on row : " + et.getText().toString() + " et id: " + et.getId());
}
}
}
This is the console output I get, if I enter the activity, click field A, and then click field B.
Notice:
Each EditText (regardless of row) has the same ID (I think this is expected)
The only change I'm making is to the underlying data. In fact, I have the same issue if I change nothing but call notifyDataSetChanged.
The target field loses focus, I've no idea why.
TL;DR - Calling notifyDataSetChanged() in my onFocusChangedListener causes focus to freak out in my ListView.
See? The cursor is drunk.
If you focus a EditText in ListView get position value, after updating ListView redrawn and automatically it will select last position.
Step 1:
if (_Curserposition == position) {
holder.textViewStake.setFocusableInTouchMode(true);
//holder.textViewStake.clearFocus();
holder.textViewStake.requestFocus();
holder.textViewStake.setSelection(holder.textViewStake.getText().toString().length());
}
Step 2:
holder.textViewStake.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
_Curserposition = position;
Log.d(">>>", "setOnFocusChangeListener" + _Curserposition);
/*
//showVirtualKeyboard(con_text, v);
// holder.textViewStake.requestFocus();
InputMethodManager imm = (InputMethodManager) activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (hasFocus) {
imm.showSoftInput(holder.textViewStake, InputMethodManager.SHOW_FORCED);
} else {
imm.hideSoftInputFromWindow(holder.textViewStake.getWindowToken(), 0);
}*/
}
});
Step 3:
holder.textViewStake.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
betlist_view.setFocusable(false);
if (s.length() > 0) {
try {
if (Integer.parseInt(holder.textViewStake.getText().toString()) > 0) {
int _Stackamt = Integer.parseInt(holder.textViewStake.getText().toString());
int _picknumber = arrayDailyGameDrawList.get(position).getID();
//Log.d(">>>", "_picknumber" + position + "-" + arrayDailyGameDrawList.get(position).getBetNumberID() + "-" + Common.DrawId + "-" + _Stackamt + "-" + arrayDailyGameDrawList.get(position).getBetNumberID());
AddUpdateDailyGameNumberIntoList(
position,
2,
arrayDailyGameDrawList.get(position).getBetNumberID(),
Common.DrawId,
_Stackamt,
arrayDailyGameDrawList.get(position).getBetNumberID()
);
/* new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);*/
}
} catch (Exception e) {
}
} else {
holder.textViewStake.setText("0");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
I have an application which has asks a user to input the amount of what he/she eats. The input field I used is an EditText. What I want to happen is when there's a change in the edittext, it should calculate (i.e., multiply the amount by its calories like 2 amount of bread is equal to 8 calories. So the answer should be 16 calories.)
But I can't get it to work. Please have a look on what I've tried:
UPDATED:
public class Bread_White extends Activity implements OnClickListener, OnItemSelectedListener {
Spinner sp;
Button calories, save, back, home;
String selected, strCalories;
TextView tv;
EditText etAmount;
int total;
RadioGroup rgMeal;
//RadioButton breakfast, ms, lunch, as, dinner, es;
String[] classes = {
"Cornbread",
"French Bread",
"French Toast",
"French Toast, low fat",
"Italian Bread",
"Wheat Bread",
"Wheat Bread, low calories",
"Wheat Bread, whole wheat"
};
//put how much calorie each food item has in this array
int[] intCalories = {188, 185, 126, 149, 81, 66, 46, 89};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.food_vegetable);
initControls();
}
private void initControls() {
// TODO Auto-generated method stub
// RadioGroup
rgMeal = (RadioGroup) findViewById (R.id.rgSelectMeal);
sp = (Spinner) findViewById (R.id.spFoodVegetable);
save = (Button) findViewById (R.id.btFoodVegetableSave);
calories = (Button) findViewById (R.id.btFoodVegetableCalories);
back = (Button) findViewById (R.id.tabs_back);
home = (Button) findViewById (R.id.tabs_home);
tv = (TextView) findViewById (R.id.txtMenuHeader);
etAmount = (EditText) findViewById (R.id.etAmount);
tv.setText(R.string.whitebread);
ArrayAdapter<String> array =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, classes);
sp.setAdapter(array);
sp.setOnItemSelectedListener(this);
back.setOnClickListener(this);
home.setOnClickListener(this);
save.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch( v.getId() ){
case R.id.btFoodVegetableSave:
String mealname = selected;
String serving = calories.getText().toString();
int i = Integer.parseInt(serving.replaceAll("[\\D]", ""));
//int amount = Integer.valueOf(etAmount.getText().toString());
//int answer = amount * i;
String strAnswer = String.valueOf(i);
//calories.setText(strAnswer);
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sdf.format(new Date());
if ( ( mealname.isEmpty() || strAnswer.isEmpty() ) ){
// call for custom toast
viewErrorToast();
}
else {
boolean didItWork = true;
try{
int checkedRadioButton = rgMeal.getCheckedRadioButtonId();
switch( checkedRadioButton ){
case R.id.rbBreakfast:
BreakFastLog bfLog = new BreakFastLog(Bread_White.this);
bfLog.open();
bfLog.createEntry(mealname, strAnswer, strDate);
bfLog.close();
break;
case R.id.rbMorningSnack:
MorningSnackLog msLog = new MorningSnackLog(Bread_White.this);
msLog.open();
msLog.createEntry(mealname, strAnswer, strDate);
msLog.close();
break;
case R.id.rbLunch:
LunchLog lunchLog = new LunchLog(Bread_White.this);
lunchLog.open();
lunchLog.createEntry(mealname, strAnswer, strDate);
lunchLog.close();
break;
case R.id.rbAfternoonSnack:
AfternoonSnackLog asLog = new AfternoonSnackLog(Bread_White.this);
asLog.open();
asLog.createEntry(mealname, strAnswer, strDate);
asLog.close();
break;
case R.id.rbDinner:
DinnerLog dinnerLog = new DinnerLog(Bread_White.this);
dinnerLog.open();
dinnerLog.createEntry(mealname, strAnswer, strDate);
dinnerLog.close();
break;
case R.id.rbEveningSnack:
EveningSnackLog esLog = new EveningSnackLog(Bread_White.this);
esLog.open();
esLog.createEntry(mealname, strAnswer, strDate);
esLog.close();
break;
}
}
catch(Exception e){
didItWork = false;
viewErrorToast();
}finally{
if (didItWork){
viewBMRSavedToast();
}
}
} // end of if else statement
break;
case R.id.tabs_back:
finish();
break;
case R.id.tabs_home:
Intent home = new Intent(this, IHealthFirstActivity.class);
home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home);
break;
}
}
private void viewBMRSavedToast() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();
}
private void viewErrorToast() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
selected = parent.getItemAtPosition(position).toString();
int amount = Integer.valueOf(etAmount.getText().toString());
total = amount * intCalories[position];
calories.setText(strCalories);
TextWatcher watcher = new TextWatcher(){
public void afterTextChanged(Editable s) {
//your business logic after text is changed
strCalories = total + " calories";
calories.setText(strCalories);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
//your business logic before text is changed
}
public void onTextChanged(CharSequence s, int start, int before, int count){
//your business logic while text has changed
}
};
etAmount.addTextChangedListener(watcher);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Please help fix this. Thanks.
Declare selectedPos as class level variable
int selectedPos = 0;
public void afterTextChanged(Editable s) {
//your business logic after text is changed
int cal = intCalories[selectedPos];
total = (Integer.parseInt(s.toString)) * cal;
calories.setText(total + " calories");
}
set your spinner selected position in defined variable.
Happy coding :)
Where is the calories view defined ? Also you might want to make that final. Could you rephrase the question. im not able to find that question :)
I keep going round in circles with this one. I have managed to set the spinner to show item in the list if it matches a record in the database, but now have an issue with getting the selected item from the spinner when I save the record. I instead get something like 'android.database.sqlite.SQLiteCursor#44fa41b0'.
In my saveInspection() method, I am using inspectedBySpinner.getSelectedItem().toString(); (as detailed in second answer in this post How do you get the selected value of a Spinner?) with no success.. (so close yet no banana!).
I'm sure this is something flippin obvious, but help much appreciated:
public class InspectionEdit extends Activity {
final Context context = this;
private EditText inspectionReferenceEditText;
private EditText inspectionCompanyEditText;
private Button inspectionDateButton;
private Spinner inspectedBySpinner;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private Button addInspectorButton;
private int mYear;
private int mMonth;
private int mDay;
private StringBuilder mToday;
private RMDbAdapter rmDbHelper;
private long inspectionId;
private String inspectedBySpinnerData;
//private String inspectors;
static final int DATE_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
setContentView(R.layout.edit_inspection);
setUpViews();
populateFields();
fillSpinner();
setTextChangedListeners();
}
private void setUpViews() {
inspectionReferenceEditText =(EditText)findViewById(R.id.inspection_reference);
inspectionCompanyEditText =(EditText)findViewById(R.id.inspection_company);
inspectionDateButton =(Button)findViewById(R.id.inspection_date);
inspectedBySpinner =(Spinner)findViewById(R.id.inspected_by_spinner);
addInspectorButton = (Button)findViewById(R.id.add_inspector_button);
saveButton = (Button)findViewById(R.id.inspection_save_button);
cancelButton = (Button)findViewById(R.id.inspection_cancel_button);
}
private void populateFields() {
if (inspectionId > 0) {
Cursor inspectionCursor = rmDbHelper.fetchInspection(inspectionId);
startManagingCursor(inspectionCursor);
inspectionReferenceEditText.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_REF)));
inspectionCompanyEditText.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_COMPANY)));
inspectionDateButton.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_DATE)));
inspectedBySpinnerData = inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_BY));
Toast.makeText(getApplicationContext(), inspectedBySpinnerData,
Toast.LENGTH_LONG).show();
}
}
private void fillSpinner() {
Cursor inspectorCursor = rmDbHelper.fetchAllInspectors();
startManagingCursor(inspectorCursor);
// create an array to specify which fields we want to display
String[] from = new String[]{RMDbAdapter.INSPECTOR_NAME};
//INSPECTOR_NAME = "inspector_name"
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter spinnerAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, inspectorCursor, from, to );
spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
inspectedBySpinner.setAdapter(spinnerAdapter);
if (inspectionId > 0) {
int spinnerPosition = 0;
for (int i = 0; i < inspectedBySpinner.getCount(); i++)
{
Cursor cur = (Cursor)(inspectedBySpinner.getItemAtPosition(i));
//--When your bind you data to the spinner to begin with, whatever columns you
//--used you will need to reference it in the cursors getString() method...
//--Since "getString()" returns the value of the requested column as a String--
//--(In my case) the 4th column of my spinner contained all of my text values
//--hence why I set the index of "getString()" method to "getString(3)"
String currentSpinnerString = cur.getString(1).toString();
if(currentSpinnerString.equals(inspectedBySpinnerData.toString()))
{
//--get the spinner position--
spinnerPosition = i;
break;
}
}
inspectedBySpinner.setSelection(spinnerPosition);
}
}
private void addInspector() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompt_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
String inspector = userInput.getText().toString();
rmDbHelper.createInspector(inspector);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private void setTextChangedListeners() {
changesMade = false;
inspectionReferenceEditText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionCompanyEditText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionDateButton.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
addInspectorButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addInspector();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
saveInspection();
finish();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cancel();
}
});
}
protected void saveInspection() {
String reference = inspectionReferenceEditText.getText().toString();
String companyName = inspectionCompanyEditText.getText().toString();
String inspectionDate = RMUtilities.compareTwoStringsNullIfSame(inspectionDateButton.getText().toString(), "Click to add");
String inspectedBy = inspectedBySpinner.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), inspectedBy,
Toast.LENGTH_LONG).show();
if (inspectionId > 0) {
rmDbHelper.updateInspection(inspectionId, reference, companyName, inspectionDate, inspectedBy);
Toast.makeText(getApplicationContext(), "Inspection updated",
Toast.LENGTH_LONG).show();
}
else {
rmDbHelper.createInspection(reference, companyName, inspectionDate, inspectedBy);
Toast.makeText(getApplicationContext(), "Inspection created",
Toast.LENGTH_LONG).show();
}
}
As you use a CursorAdapter and not an Adapter based on a List or Array of String, you'll have to use the Cursor to fetch the value of the selected item. The Spinner's getSelectedItem will call the CursorAdapter's getItem(position) which will return the Cursor object. So instead to using toString(), first cast the returned object to a Cursor and then use Cursor's get... methods to fetch the required data of the selected item.
EDIT
Based on how you fill your spinner you'll probably need this:
String inspectedBy = ((Cursor)inspectedBySpinner.getSelectedItem())
.getString(1).toString();