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 :)
Related
//imports
public class MainActivity extends Activity implements OnCheckedChangeListener
{
int count=0,ints......;
TextView textviews...;
int itemCode,month;
ArrayList<String> Name = new ArrayList<String>();
AlertDialog alertDialog ;
SharedPreferences sp;
EditText EtItemCode;
Editor editor ;
RadioButton RbForItemCode,RbForItemName;
RadioGroup RgForItemVsName;
PopupWindow popupWindowItems;
String popUpItems[];
ProgressDialog pDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//shared prefs
sp = this.getSharedPreferences("MySharedPrefsFile", Context.MODE_PRIVATE);
editor = sp.edit();
intForShardPref= sp.getInt("NEW_INSTALLATION",1); // getting Integer(1 is for no)
if(intForShardPref==1){
Intent intent = new Intent(this,Verify.class);
startActivityForResult(intent, 1);
}
else{
//do nothing
}
EtItemCode.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ToCheckItemCodeOfEdittext = EtItemCode.getEditableText().toString();
DatabaseHandler db=new DatabaseHandler(MainActivity.this);
List<Item> Items = db.getAllItemWithSubString(ToCheckItemCodeOfEdittext,itemNumberOrNameSelectedInRadioButtonOptions);
if(EtItemCode.length()>2){
if(EtItemCode.length()>3||flagForPopUpWindow>EtItemCode.length())
popupWindowItems.dismiss();
Name.clear();
for (Item cn : Items) {
if(RbForItemCode.isChecked()==true){
Name.add(Integer.toString(cn.getItemNumber()));
}
else{
Name.add(cn.getName());
}
}
popUpItems = new String[Name.size()];
Name.toArray(popUpItems);
popupWindowItems = popupWindowItems();
***popupWindowItems.setFocusable(false);***
popupWindowItems.showAsDropDown(findViewById(R.id.et_item_code), -5, 0);
}
else{
if(flagForPopUpWindow==3&&EtItemCode.length()==2)
popupWindowItems.dismiss();
}
flagForPopUpWindow=EtItemCode.length();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
private void init() {
// TODO Auto-generated method stub
//some code
}
public PopupWindow popupWindowItems() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewItems = new ListView(this);
// set our adapter and pass our pop up window contents
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
this, //context for activity
android.R.layout.simple_list_item_1, //layout used
Name){ //Items to be displayed
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item.toString();
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
//listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
listViewItems.setAdapter(adapter);
// set the item click listener
listViewItems.setOnItemClickListener(new ItemsDropdownOnItemClickListener());
// some other visual settings
//popupWindow.setFocusable(true);
popupWindow.setWidth(EtItemCode.getWidth());
//popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);
popupWindow.setHeight(r.height()-3*EtItemCode.getHeight());
// set the list view as pop up window content
popupWindow.setContentView(listViewItems);
return popupWindow;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.phone_number:
Intent p = new Intent(MainActivity.this,PhoneNumber.class);
startActivity(p);
break;
case R.id.exit:
finish();
break;
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//some code
}
class LoadDataBase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("DataBase Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
Log.d("Reading: ", "Reading all Items..");
List<Item> Items = db.getAllItem();
//some code
//DatabaseHandler db1 = new DatabaseHandler(this);
count= db.getItemCount();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
public class ItemsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "Item is: ", Toast.LENGTH_SHORT).show();
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EtItemCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// dismiss the pop up
popupWindowItems.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
Toast.makeText(MainActivity.this, "Item is: " + selectedItemText, Toast.LENGTH_SHORT).show();
DatabaseHandler db =new DatabaseHandler(MainActivity.this);
Item item= new Item();
if(RbForItemCode.isChecked()==true){
item = db.getItem(Integer.valueOf(selectedItemText));
}
else if(RbForItemName.isChecked()==true){
item = db.getItem(selectedItemText);
}
itemCode=item.getItemNumber();
}
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(RbForItemCode.isChecked()==true){
itemNumberOrNameSelectedInRadioButtonOptions="id";
//some code
}
}
else if(RbForItemName.isChecked()==true){
//some code
}
}
}
This code is working fine on my phone galaxy note 2(custom rom of note 4.. Android 4.4.4).By fine I mean I can type in edittext and popupwidow shows up after 3rd text(because of condition I have put) and I can select an option from the popupwindow. When I try to run the code on any other phone like galaxy grand then callback to ItemsDropdownOnItemClickListener is not registered and I can only scroll the popupwindow and keep on typing in edittext but cannot select any of the options in the popupwindow. If I set popupWindowItems.setFocusable(false) to true i.e popupWindowItems.setFocusable(true), and then as soon as I type 3rd letter in edittext,edittext looses focus and popwindow gains it. Now I can select anything.. But now I cannot continue to type in edittext.I have to manually select edittext and type.
Now I want that after tying 3rd word in edittext a popupwindow should appear(which currently is appearing) and edittext doesn't loose focus(so that i can continue typing).. Further if I select anything from popupwindow ,ItemsDropdownOnItemClickListener should be called which is currently being not called in other phones when popupWindowItems.setFocusable(false);
I am doing this to load data from sqlite database and show in popupwindow once the user types 3rd word. Any suggestion is recommended
Edit: Problem solved. Now using AutoComplete TextView
I have a program in android where spinner gets the data dynamically from rest services. what i want to achieve is when the first spinner loads its value, the selected value loads the value of 2nd and third spinner. i want to disable the click of 2nd and third spinner till the spinner gets populated are loaded in all the spinner.
I call the function of populating 2nd & 3rd spinner in the end of the program.
public void addItemsOnSpinner1()
{
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null) {
String value = extras.getString("new_variable_name");
strEmployeeID = value;
}
JSONObject login = new JSONObject();
try
{
login.put("EmployeeID",strEmployeeID);
//login.put("Password", etCountry.getText().toString());
JSONObject finaldata = new JSONObject();
finaldata.put("ProjectRequest", login);
final ConnectToServer connect = new ConnectToServer();
connect.extConnectToServer(HourlyEntry.this,new ConnectToServer.Callback()
{
public void callFinished(String result)
{
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject resp = null;
try
{
resp = new JSONObject(result);
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject Login1Result = resp.getJSONObject("ProjectResult");
JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
// String strMessage = Login1Result.getString("message");
// Toast.makeText(getBaseContext(), Login1Result.getString("ProjectDetails"), Toast.LENGTH_LONG).show();
// List<String> list = new ArrayList<String>();
if (!Login1Result.getString("ProjectDetails").equalsIgnoreCase("null"))
{
//JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
m_Project_list = new ArrayList<String>();
m_projectID_list = new ArrayList<String>();
for (int i = 0; i < DepartmentDetails.length(); i++)
{
JSONObject m_DepartmentDetails = DepartmentDetails.getJSONObject(i);
// Toast.makeText(getBaseContext(),m_DepartmentDetails.toString() , Toast.LENGTH_LONG).show();
if (!m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase(""))
{
// list.add(m_DepartmentDetails.getString("ProjectName"));
m_Project_list.add(m_DepartmentDetails.getString("ProjectName"));
// Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectName"), Toast.LENGTH_LONG).show();
}
if (!m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase(""))
{
m_projectID_list.add(m_DepartmentDetails.getString("ProjectID"));
//Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectID"), Toast.LENGTH_LONG).show();
String strProjectID="";
String item2 = m_DepartmentDetails.getString("ProjectID");
strProjectID = item2;
}
}
}
s1 = (Spinner) findViewById(R.id.spinnerL);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.spin,m_Project_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
if (m_projectID_list.contains(m_ProjectID))
{
s1.setSelection(m_projectID_list.indexOf(m_ProjectID));
}
}
catch (final JSONException e)
{
}
}
}, "http://aapna.azurewebsites.net/Service1/Project", finaldata,
"POST");
connect.execute(finaldata);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
// Toast.makeText(getApplicationContext(),
// SelectedProjectID, Toast.LENGTH_LONG).show();
// Showing selected spinner item
// Toast.makeText(getApplicationContext(),
// "Selected : " + item1, Toast.LENGTH_LONG).show();
s2.setClickable(false);
s3.setClickable(false);
addItemsOnSpinner2(SelectedProjectID);
s2.setClickable(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setClickable(true);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Try this..
Change your first element from m_Project_list ArrayList as Select
And after user selecting spinner you can do other operation below codes inside onCreate
Code
s1.setSelection(0);
s1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
if(pos == 0){
s2.setEnabled(false);
s3.setEnabled(false);
}
else{
// do something
addItemsOnSpinner2(SelectedProjectID);
s2.setEnabled(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setEnabled(true);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
EDIT
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.i("=========="," handler == > ");
Toast.makeText(getBaseContext(), "handler", Toast.LENGTH_LONG).show();
}
}, 5000);
The only solution I got is to use delay function to solve this kind of spinner as told to me by hariharan.
ADD these two statements in spinner 1 function
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id)
{
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
s2.setEnabled(false);
s3.setEnabled(false);
addItemsOnSpinner2(SelectedProjectID);
addItemsOnSpinner3(SelectedProjectID);
delay1();
//
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
then use the below function
public void delay1()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run()
{
s2.setEnabled(true);
s3.setEnabled(true);
}
}, 3000);
}
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.
I want to show 5 xml layouts in random, and also i'l shuffle them on click of appropriate button each appeared xml file. Upto that the below code is working awesomely.----**I have put a delay of 0.75 seconds on each shuffle of the xml file.In this delay I have a sound to play.I have no really Idea How to achieve this.In the below code I used Switch-Case , But it is not working.My requirement is if I Click on the Button on xml file1 , I want to play Sound1, if the Button is from Xml file 5 , I want to play the corresponding Sound5 And so on....like that for 0.75 seconds and move to next XML file and the cycle repeats.*----
public class ReceivingActivity extends Activity{
Random random = new Random();
Handler handler = new Handler();
private int mPosition = 0;
private Handler mHandler = new Handler();
private List<Integer> mLayouts;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mLayouts = new ArrayList<Integer>();
mLayouts.add(R.layout.first);
mLayouts.add(R.layout.second);
mLayouts.add(R.layout.third);
mLayouts.add(R.layout.fourth);
mLayouts.add(R.layout.fifth);
Collections.shuffle(mLayouts);
setContentView(mLayouts.get(mPosition));
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
mPosition++;
}
private OnClickListener mListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "WTH is happening", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
if(mPosition >= mLayouts.size()){
int lastId = mLayouts.get(mLayouts.size() - 1);
Collections.shuffle(mLayouts);
while (lastId == mLayouts.get(0)) {
Collections.shuffle(mLayouts);
}
mPosition = 0;
}
setContentView(mLayouts.get(mPosition));
switch (mLayouts.get(mPosition)) {
case R.layout.first:
Toast.makeText(getApplicationContext(), "First", Toast.LENGTH_SHORT).show();
iv1.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.second:
Toast.makeText(getApplicationContext(), "second", Toast.LENGTH_SHORT).show();
//Some sound
iv2.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.third:
Toast.makeText(getApplicationContext(), "third", Toast.LENGTH_SHORT).show();
//Some media , Different for each Layout..
iv3.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.fourth:
Toast.makeText(getApplicationContext(), "fourth", Toast.LENGTH_SHORT).show();
iv4.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.fifth:
Toast.makeText(getApplicationContext(), "fifth", Toast.LENGTH_SHORT).show();
iv5.setBackgroundResource(R.drawable.ic_launcher);
break;
default:
break;
}
mPosition++;
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
}
}, 2050);
}
};
mPosition++;
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
}
}, 750);
}
};
}
Any kind help is highly helpful.
You may use the android:tag to differentiate between the buttons.
<Button
...
android:tag="1"/>
And then in the code retrieve the tag
mButton = (Button)findViewById(R.id.btnid);
int id = Integer.parseInt(mButton.getTag());
switch(id) {
...
}
Firstly, this is my first question here, Thanks for any reply:)
I have a fragment extends SherlockListFragment that has a list of (events) saved in database, i want when i click on any item in the list , to get all event data and fill in another activity that has editText(s) ....
this is the frgment.java code
public class EventsFragment extends SherlockListFragment {
EditText _eventName_;
EditText next_activty_text;
List<String> presidents = new ArrayList<String>();
public DBAdapter db;
String buf = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_events, container, false);
_eventName_ = (EditText) v.findViewById(R.id.editText11);
next_activty_text = (EditText) v.findViewById(R.id.editText12);
// The most Important part in action bar menus :)
setHasOptionsMenu(true);
/*
//This is how to link a button in fragment by its .xml file :Ds
Button create_btn = (Button) v.findViewById(R.id.button1);
create_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
}
});*/
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
db = new DBAdapter(getActivity());
db.open();
int i = 1;
while(db.getEvent(i).isLast()){
Cursor c = db.getEvent(i);
presidents.add(c.getString(1));
i++;
}
db.close();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_events_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
startActivity(new Intent("com.nazmy.CreateEventActivity"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
//populate(c.getString(1));
_eventName_.setText(c.getString(1));
db.close();
}
}
`
and this is the activity code
public class CreateEventActivity extends FragmentActivity {
EditText mEdit;
EditText mEdit2;
EditText mEditFromTime;
EditText mEditToTime;
int whichDateBtn;
int whichTimeBtn;
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
db.open();
Cursor c = db.getAllEvents();
if (c.moveToFirst())
{
do {
DisplayEvent(c);
} while (c.moveToNext());
}
db.close();
Button cancel_btn = (Button) findViewById(R.id.button4);
Button save_btn = (Button) findViewById(R.id.button1); //if clicked -> save in data-base
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
EditText event_name = (EditText)findViewById(R.id.editText12);
EditText event_place = (EditText)findViewById(R.id.editText13);
EditText from_date = (EditText)findViewById(R.id.editText14);
EditText from_time = (EditText)findViewById(R.id.editText15);
EditText to_date = (EditText)findViewById(R.id.EditText16);
EditText to_time = (EditText)findViewById(R.id.EditText17);
CheckBox share = (CheckBox)findViewById(R.id.checkBox1);
CheckBox alarm = (CheckBox)findViewById(R.id.checkBox2);
long id2 = db.insertEvent(event_name.getText().toString(), event_place.getText().toString(),
from_date.getText().toString(), to_date.getText().toString(),
from_time.getText().toString(),
to_time.getText().toString(),
share.isChecked(),alarm.isChecked());
db.close();
event_name.setText("");
event_place.setText("");
from_date.setText("");
to_date.setText("");
from_time.setText("");
to_time.setText("");
if (share.isChecked()) {
share.setChecked(false);
}
if (alarm.isChecked()) {
alarm.setChecked(false);
}
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
}
//This method shows the dialog when Button is clicked
public void selectFromtDate(View view) {
DialogFragment mDialog = new SelectDateFragment();
mDialog.show(getFragmentManager(), "DatePicker");
whichDateBtn = 0;
}
public void selectToDate(View view) {
DialogFragment mDialog2 = new SelectDateFragment();
mDialog2.show(getFragmentManager(), "DatePicker");
whichDateBtn = 1;
}
//This method will update the EditText field with the following code.
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.editText14); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEdit2 = (EditText)findViewById(R.id.EditText16);
if(whichDateBtn==0) {
mEdit.setText(month+"/"+day+"/"+year);
}
else if (whichDateBtn == 1) {
mEdit2.setText(month+"/"+day+"/"+year);
}
}
//This subclass includes method to display the datepicker fragment to the user.
//It also has the method to handle the event on setting the date.
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
//The onCreateDialog() method creates a calendar object.
//Using this object the current day, month and year that will be retrieved.
//This current instance will return to the activity to display the date picker with the current date by default.
//onDateSet() method calls the populateSetDate() with the selected date parameters.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Time Pickers
////////////////////////////////////////////////////////////////////////////////////////////////////////
public void selectFromTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 0;
}
public void selectToTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 1;
}
public void populateSetTime(int hour, int min) {
mEditFromTime = (EditText)findViewById(R.id.editText15); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEditToTime = (EditText)findViewById(R.id.EditText17);
if(whichTimeBtn==0) {
mEditFromTime.setText(hour+":"+min);
}
else if (whichTimeBtn == 1) {
mEditToTime.setText(hour+":"+min);
}
}
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
populateSetTime(hourOfDay, minute);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_create_event, menu);
return true;
}
public void DisplayEvent(Cursor c)
{
Toast.makeText(this,
"id : " + c.getString(0) + "\n" +
"Event Name: " + c.getString(1) + "\n" +
"Place : " + c.getString(2) + "\n" +
"From Date : " + c.getString(3)+ "\n" +
"From Time : " + c.getString(5)+ "\n" +
"To Date : " + c.getString(4)+ "\n" +
"To Time : " + c.getString(6),
Toast.LENGTH_LONG).show();
}
}
`
Thanks in advance :)
You have two choices. Either fetch the data from your database in EventsFragment.onListItemClick(), and pass that data to your second Activity as Intent extras. Or you can pass the id of the clicked item, and do the database operations in your second Activity. Either way you have to pass data using Intents
public class EventsFragment extends SherlockListFragment {
.
.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this, CreateEventActivity.class);
// OPTION 1: Fetch data here, and pass it with the intent
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
intent.putExtra("id", c.getString(1));
intent.putExtra("event_name", c.getString(2));
// Do this for all your values.
db.close();
startActivity(intent);
// OPTION 2: Pass the id of the selected item, and fetch the data in second activity
intent.putExtra("selected_id", id+1);
startActivity(intent);
}
}
In CreateEventActivity you then have to get the extras you chose to pass with the Intent.
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
Intent intent = getIntent();
// If you chose option 1, you have to get all the extras you attached to the Intent.
long id = intent.getLongExtra("id", -1)
String eventName = intent.getStringExtra("event_name", "defValue");
// Fetch all the values here..
// If you chose option 2, you fetch the id and do the database operations to retrive
// the data
long id = intent.getLongExtra("selected_id", -1);
// DB stuff here..
}