I need to connect the spinner with editText to get the result for converter
There is no connection between spinner and my converter.
public class A01Acre extends Activity {
Spinner spinnerarea;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.a01acre);
final EditText editAcre = (EditText) findViewById(R.id.editAcre);
final EditText editHectar = (EditText) findViewById(R.id.editHectar);
final EditText editSquareinch = (EditText) findViewById(R.id.editSquareinch);
final EditText editSquarekm = (EditText) findViewById(R.id.editSquarekm);
final EditText editSquaremeter = (EditText) findViewById(R.id.editSquaremeter);
final EditText editSquaremile = (EditText) findViewById(R.id.editSquaremile);
final EditText editSquareyard = (EditText) findViewById(R.id.editSquareyard);
Button buttonConvert = (Button) findViewById (R.id.buttonConvertAcre);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//try
try {
//
double acre = Double.valueOf (editAcre.getText().toString());
double hectar = acre * 0.404686;
double squareinch = acre * 6.273e+6;
double squarekm = acre * 0.00404686;
double squaremeter = acre * 4046.86;
double squaremile = acre * 0.0015625;
double squareyard = acre * 4840;
editHectar.setText (String.valueOf(hectar));
editSquareinch.setText (String.valueOf(squareinch));
editSquarekm.setText (String.valueOf(squarekm));
editSquaremeter.setText (String.valueOf(squaremeter));
editSquaremile.setText (String.valueOf(squaremile));
editSquareyard.setText (String.valueOf(squareyard));
//catch
} catch (NumberFormatException ex) {
// write a message to users
editHectar.setText ("");
}
}
});
spinnerarea = (Spinner) findViewById(R.id.spinnerarea);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.spinnerTestArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerarea.setAdapter(adapter);
spinnerarea.setOnItemSelectedListener(new MyOnItemSelectdListerne());
}
#Override
public void onDestroy(){
super.onDestroy();
}
public class MyOnItemSelectdListerne implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> patent,
View view, int pos, long id) {
String str = patent.getItemAtPosition(pos).toString().toUpperCase();
}
#Override
public void onNothingSelected(AdapterView parent) {
}
}
}
Add a switch statement to your onItemSelected() method - switching on pos.
For each unit (each case), you can recalculate and then output the value to the user.
Something like,
switch(pos) {
case 0:
//acre - redo calculation
break;
case 1:
//hectare - redo calculation
break;
case 2:
//squareinch - redo calculation
break;
//...
default:
throw new UnexpectedException();
}
//display results to user
Related
I am wanting to get the string value from the spinner. I am currently using Volley in passing data but then it wasn't successful then. This is my RegisterActivity class:
public class RegUserPassClient extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_user_pass_client);
final Spinner spinner = findViewById(R.id.genderSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.genderString, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
final EditText regUserClient= (EditText) findViewById(R.id.regUserClient);
final EditText regPassClient= (EditText) findViewById(R.id.regPassClient);
final EditText regClientName = (EditText) findViewById(R.id.registerClientName);
final EditText regClientNumber = (EditText) findViewById(R.id.registerClientNumber);
final EditText regClientAddress = (EditText) findViewById(R.id.registerClientAddress);
final EditText regClientOccupation = (EditText) findViewById(R.id.registerClientOccupation);
final EditText regClientGender = (EditText) findViewById(R.id.registerClientGender);
final EditText regClientBirthDate = (EditText) findViewById(R.id.registerClientBirthDate);
final TextView clientUser = (TextView) findViewById(R.id.clientUserType);
final Button regClientBtn = (Button) findViewById(R.id.regClient);
final CheckBox toggle = (CheckBox) findViewById(R.id.checkBoxLog);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
regPassClient.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else{
regPassClient.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
regClientBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = regUserClient.getText().toString();
final String password = regPassClient.getText().toString();
final String name = regClientName.getText().toString();
final String number = regClientNumber.getText().toString();
final String gender = spinner.toString();
final String address = regClientAddress.getText().toString();
final String occupation = regClientOccupation.getText().toString();
final String birthDate = regClientBirthDate.getText().toString();
final String userType = clientUser.getText().toString();
if(!username.isEmpty() && !password.isEmpty() &&
!name.isEmpty() && !address.isEmpty() &&
!occupation.isEmpty() && !gender.isEmpty() &&
!birthDate.isEmpty() && !number.isEmpty()) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegUserPassClient.this, LoginRegister.class);
RegUserPassClient.this.startActivity(intent);
Toast.makeText(RegUserPassClient.this,"SuccessFully Registered! Log in your details now!",Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegUserPassClient.this);
builder.setMessage("Username Has already been taken!")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegUserPassClientRequest registerRequest = new RegUserPassClientRequest(username, password, name, number, gender, address, occupation, birthDate, userType, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegUserPassClient.this);
queue.add(registerRequest);
}else if(username.isEmpty()){
regUserClient.setError("Please insert a username");
}else if(password.isEmpty()){
regPassClient.setError("Please put your password");
}else if(name.isEmpty()){
regClientName.setError("Please input your name");
}else if(number.isEmpty()){
regClientNumber.setError("Put your phone number please");
}else if(address.isEmpty()){
regClientGender.setError("Please state your gender");
}else if(occupation.isEmpty()){
regClientAddress.setError("Please put your address");
}else if(gender.isEmpty()){
regClientOccupation.setError("Please state occupation");
}else if(birthDate.isEmpty()){
regClientBirthDate.setError("Please select your Birth Date");
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
final String text = parent.getItemAtPosition(i).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
My functions for getting the spinner value are under the volleyrequest. I guess that is where my code is wrong but I don't really know what to put and where is the wrong thing.
It was just
final String gender = spinner.getSelectedItem().toString();
after all! Thanks anyways for viewing guys!
I am new to Android Studio. I have gone through the official developer.android.com training and I decided to create a new and simple app called Grocery+ in which user will enter the price and quantity of particular item and app will display total sum.
I have done all UI based work then today I switched to programming. I am an experienced programmer of Java. I have also done all the work in it but:
1- my app crashes when I try to enter the first .
Then I have to enter any other value first then first value.
2- even after above hack my app doesn't display anything on 'grand total
Plese help :(((
package com.amostrone.akash.grocery;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int Quantity[] = new int[4];
static float Price[] = new float[4];
public static double total=0;
static TextView txtValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtValue = (TextView) findViewById(R.id.txtExample);
}
/////////// QUANTITY
public void input_Quantity(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity);
calc();
}
public void input_Quantity2(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity2);
Quantity[1] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity3(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity3);
Quantity[2] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity4(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity4);
Quantity[3] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity5(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity5);
Quantity[4] = Integer.parseInt(x.toString());
calc();
}
/////////////// Quantity
////////////// Price
public void input_Price(View view) {
EditText x = (EditText) findViewById(R.id.editPrice);
Price[0] = Float.parseFloat(x.toString());
calc();
}
public void input_Price2(View view) {
EditText x = (EditText) findViewById(R.id.editPrice2);
Price[1] = Float.parseFloat(x.toString());
calc();
}
public void input_Price3(View view) {
EditText x = (EditText) findViewById(R.id.editPrice3);
Price[2] = Float.parseFloat(x.toString());
calc();
}
public void input_Price4(View view) {
EditText x = (EditText) findViewById(R.id.editPrice4);
Price[3] = Float.parseFloat(x.toString());
calc();
}
public void input_Price5(View view) {
EditText x = (EditText) findViewById(R.id.editPrice5);
calc();
}
///////////// Price
/////////////// Calculate
public static void calc()
{
for(int i=0;i<=4;i++)
total += (Quantity[i] * Price[i]);
String str = Double.toString(total);
txtValue.setText(str);
}
////////////// Calculate }
Looking at your code it appears your are triggering EditText value get and calculation on click event (via xml). This does not work this way as they are triggered immediately. One of the approaches to solve this problem is to go the TextWatcher route. Check the below code built around that, I also refactored it a bit (should be lesser prone to memory leaks now):
public double mTotal;
private TextView mTextView;
private EditText[] mQuantityEditTexts = new EditText[5];
private EditText[] mPriceEditTexts = new EditText[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.txtExample);
mQuantityEditTexts[0] = (EditText) findViewById(R.id.editQuantity);
mQuantityEditTexts[1] = (EditText) findViewById(R.id.editQuantity2);
mQuantityEditTexts[2] = (EditText) findViewById(R.id.editQuantity3);
mQuantityEditTexts[3] = (EditText) findViewById(R.id.editQuantity4);
mQuantityEditTexts[4] = (EditText) findViewById(R.id.editQuantity5);
mPriceEditTexts[0] = (EditText) findViewById(R.id.editPrice);
mPriceEditTexts[1] = (EditText) findViewById(R.id.editPrice2);
mPriceEditTexts[2] = (EditText) findViewById(R.id.editPrice3);
mPriceEditTexts[3] = (EditText) findViewById(R.id.editPrice4);
mPriceEditTexts[4] = (EditText) findViewById(R.id.editPrice5);
for (int i = 0; i < 5; i++) {
mQuantityEditTexts[i].addTextChangedListener(mTextWatcher);
mPriceEditTexts[i].addTextChangedListener(mTextWatcher);
}
}
private TextWatcher mTextWatcher = 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) {
calc();
}
#Override
public void afterTextChanged(Editable s) {
}
};
public void calc()
{
try {
for (int i = 0; i <= 4; i++)
mTotal += Integer.parseInt(mQuantityEditTexts[i].getText().toString()) *
Double.parseDouble(mPriceEditTexts[i].getText().toString());
String str = Double.toString(mTotal);
mTextView.setText(str);
} catch (NumberFormatException e) {
Toast.makeText(this, "WTF! Enter valid numbers!", Toast.LENGTH_SHORT).show();
}
}
I have created custom edittext which does not hangs.
SearchTimerEditText
I'm struggling to create a very simple app. There are Product Names with matching Product Numbers. User enters a Number and the corresponding Name appears.
editTextField1 = the number user types
button1 = the search button
editTextField2 = the product name appears
Now my code is working but there is only one problem, when the user doesn't enter anything and clicks on button1 the app crashes. So I need some sort of exception handler maybe? Im struggling to get my head around it. I know how I'm coding, by declaring loads of variables, is long-winded lol.
public class MainActivity extends AppCompatActivity {
private Button button1;
private EditText editText1;
private EditText editText2;
private int a = 123;
private String b = "TV";
private int c = 333;
private String d = "Radio";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
double pNumber = Double.parseDouble(editText1.getText().toString());
if(pNumber == a){
editText2.setText(b);
}
else if (pNumber == c){
editText2.setText(d);
}
else
editText2.setText("Invalid Product Number");
}
};
button1.setOnClickListener(myOnClickListener);
In Addition to Spartas Answer, it would also be a good idea to check for a valid Double input:
try {
double pNumber = Double.parseDouble(text);
catch(NumberFormatException e){
//Do ExceptionHandling
}
Use this:
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText1.getText().toString();
if(!TextUtils.isEmpty(text)) {
// EditText1 is not empty
try {
double pNumber = Double.parseDouble(text);
if(pNumber == a)
editText2.setText(b);
else if (pNumber == c){
editText2.setText(d);
else
editText2.setText("Invalid Product Number");
}
catch(NumberFormatException e) {
// Invalid input, not a double
editText2.setText("Invalid double input");
}
}
else {
// EditText1 is empty
editText2.setText("EditText1 is empty");
}
}
};
There are basically 2 ways how you can handle this
1) Use try - catch
try{
double pNumber = Double.parseDouble(editText1.getText().toString());
}catch(NumberFormatException e){
//show a message to user
}
2) Use input sanitation
String number = editText1.getText().toString();
boolean isNumber = number.matches("^-?\\d+$"));//haven't tried this though
if(!isNumber) //if not number
//show a message to user
The app force shuts when i enter a number in edittext. I want the app to automatically calculate the BMI when values are entered without pressing on a button.
I know nothing about TextWatcher yet i researched and came up with this code. Its not working though. Whats wrong with it?
public class BodyMassIndex extends Activity implements View.OnClickListener,
TextWatcher {
double result;
EditText age, height, weight;
ToggleButton sex, cmin, kglb;
TextView tvResult;
double heightInt = 1;
double weightInt = 0;
int ageInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
initialize();
sex.setOnClickListener(this);
cmin.setOnClickListener(this);
kglb.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
age = (EditText) findViewById(R.id.etAge);
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
sex = (ToggleButton) findViewById(R.id.tbSex);
cmin = (ToggleButton) findViewById(R.id.tbCMIN);
kglb = (ToggleButton) findViewById(R.id.tbKGLB);
tvResult = (TextView) findViewById(R.id.tvResult);
age.addTextChangedListener(this);
height.addTextChangedListener(this);
weight.addTextChangedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.tbCMIN:
heightInt = heightInt * 0.0254;
break;
case R.id.tbKGLB:
weightInt = weightInt * 0.45359237;
break;
}
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
calculate();
}
private void calculate() {
// TODO Auto-generated method stub
Editable H = height.getText(), W = weight.getText();
if(H != null)
heightInt = Double.parseDouble(H.toString());
if (W != null)
weightInt = Double.parseDouble(W.toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
#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
}
}
'
From http://developer.android.com/reference/android/text/TextWatcher.html about afterTextChanged method: "but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively....you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) "
you already have :
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
only change calculate() method:
private void calculate()
{
//remove the Editable thing declaration...
heightInt = Double.parseDouble(height.getText().toString());
wightInt = Double.parseDouble(weight.getText().toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
P.S: Here we're assuming that EditText contains only a number and not letters. Letters will force close the app. So you'll have to check for that.
I want to add a wait till, Button (Enter) is pressed function to my code But i am still new to this.
I know there are some errors in my code I was playing around with it, But what I want to do is when I press the line Button I want it to display Input X,Y,Z then wait till enter is pressed to execute the rest of my code I want to add in. How would I implement something like this in my code?
Here is my MainActivity Class:
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button enter = (Button) findViewById(R.id.enter);
Button line = (Button) findViewById(R.id.line);
Button arc = (Button) findViewById(R.id.arc);
line.setOnClickListener(this);
enter.setOnClickListener(this);
arc.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView vector = (TextView) findViewById(R.id.point);
TextView index = (TextView) findViewById(R.id.index);
TextView info = (TextView) findViewById(R.id.info);
EditText cl = (EditText) findViewById(R.id.editText1);
DrawingUtils call = new DrawingUtils();
switch (v.getId()) {
case R.id.line:
info.setText("Input X,Y,Z");
// This Is Where the Wait Function Will GO
vector.setText(call.addVertice());
index.setText("1");
break;
case R.id.enter:
String In = cl.getText().toString();
call.setInputCoords(In);
break;
case R.id.arc:
info.setText("Enter Vertice1 ");
// Code for entering Vertice1(Also has wait function)
info.setText("Enter Vertice2");
// Code for entering Vertice2(Also has wait function)
info.setText("Enter Height");
//Code for entering Height(Also has wait function)
}
}
}
Here is my DrawingUtils Class:
public class DrawingUtils {
String inputCoords;
String[] vertice;
public String getInputCoords() {
return inputCoords;
}
public void setInputCoords(String inputCoords) {
this.inputCoords = inputCoords;
}
public String addVertice() {
int i = 0;
vertice = inputCoords.split(",");
return vertice[i];
}
}
I think this is what you are after. Apologies if not!
Use a boolean flag to handle state within your app. This way you can execute different code if something has happened.
boolean enterPressed = false;
#Override
public void onClick(View v) {
TextView vector = (TextView) findViewById(R.id.point);
TextView index = (TextView) findViewById(R.id.index);
TextView info = (TextView) findViewById(R.id.info);
EditText cl = (EditText) findViewById(R.id.editText1);
DrawingUtils call = new DrawingUtils();
switch (v.getId()) {
case R.id.line:
if (enterPressed) {
vector.setText(call.addVertice());
index.setText("1");
}
else {
info.setText("Input X,Y,Z");
}
break;
case R.id.enter:
String In = cl.getText().toString();
call.setInputCoords(In);
enterPressed = true;
break;
case R.id.arc:
info.setText("Enter Vertice1 ");
// Code for entering Vertice1
info.setText("Enter Vertice2");
// Code for entering Vertice2
}
}