How to call setText() using a Float? [duplicate] - android

This question already has an answer here:
How to call setText() using a Float data type?
(1 answer)
Closed 8 years ago.
i tried to call the setText() using the float but it dosnt seem to work can somone help me fix the problem?
public class Bmi extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
final EditText h = (EditText)findViewById(R.id.editText2);
final EditText w = (EditText)findViewById(R.id.editText3);
final TextView r = (TextView)findViewById(R.id.textView4);
Button calculate = (Button) findViewById(R.id.button1);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
float height=0;
float weight=0;
float result=0;
height= Float.parseFloat(h.getText().toString());
weight= Float.parseFloat(w.getText().toString());
result = (weight/(height * height));
r.setText(result);
}
});
}
}
im trying to make a simple bmi calculator just as practice but im having issues on making it work

You should convert your float to a String by
r.setText(String.valueOf(result));
Or the quick and dirty way
r.setText("" + result);
If you want it localized (Dot or Comma seperated decimal number)
String text = NumberFormat.getInstance(YOURCONTEXT.getResources().getConfiguration().locale).format(result);
r.setText(text);
Just replace YOURCONTEXT with MainActivity.this if you are in the MainActivity or getActivity() if you are in a Fragment
If you want to set min or max fraction digits try this:
NumberFormat numberformat = NumberFormat.getInstance(YOURCONTEXT.getResources().getConfiguration().locale);
numberformat.setMaximumFractionDigits(2);
numberformat.setMaximumIntegerDigits(1);
numberformat.setMinimumFractionDigits(2);
String text = numberformat.format(result);
r.setText(text);

You can use
r.setText(String.valueOf(result));

In order to display float value inside TextView you'll need to convert it to String first.
You can convert any primitive data type(int, float, double,boolean,etc) to String by using String.valueOf(value) method.
Here value is the variable which you want to convert to String.
You can use
String str = String.valueOf(result);
r.setText(str);
Alternatively
r.setText(String.valueOf(result));
Please comment if further help is required.

Related

Math function Power from String ("2 power 3")

I have to perform a pow function while getting equation from string like "2 power 3". I know there is function Math.pow(a, b) and also I can use for loop to achieve this , but the problem is both methods needs integer and I have equation in string. I don't know how to parse this string and separate both variables. And there is another problem. my equation could get little bit complex as well. for instance it could be like "2+3*5/5 power 2"
public class CalculationActivity extends AppCompatActivity {
EditText editText;
Button btnCalc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
editText=findViewById(R.id.et_regular_dep);
btnCalc=findViewById(R.id.btnCalculate);
btnCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String equation= editText.getText().toString();
CalculateResult(equation);
}
});
}
private void CalculateResult(String equation) {
// here to perform power function
}
}
Try this :
String eq = "2 power 3";
String no2 = eq.substring(eq.indexOf("power") + 6 , eq.length());
String no1 = eq.substring(0,eq.indexOf("power")-1);
Log.d("no1",no1);
Log.d("no2",no2);
Log.d("ans",Math.pow(Double.parseDouble(no1),Double.parseDouble(no2))+"");
another easy way to do it
String eq = "2 power 3";
eq = eq.trim(); // if it has extra space at the start or end
String no1 = eq.split(" ")[0];
String no2 = eq.split(" ")[2];
Log.e("no1", no1);
Log.e("no2", no2);
Log.e("ans", Math.pow(Double.parseDouble(no1), Double.parseDouble(no2)) + "");

Running a tensorflow model in Android

I'm trying to run a simple iris classifier in an Android app. I created a MLP in keras, converted it into .pb format and put it into an assets folder. The keras model:
data = sklearn.datasets.load_iris()
x=data.data
y=data.target
x=np.array(x)
y=np.array(y)
x_train, x_test, y_train, y_test= train_test_split(x, y, test_size = 0.25)
inputs=Input(shape=(4,))
x=Dense(10,activation="relu",name="input_layer")(inputs)
x=Dense(10,activation="relu")(x)
x=Dense(15,activation="relu")(x)
x=Dense(3,activation="softmax",name="output_layer")(x)
model=Model(inputs,x)
sgd = SGD(lr=0.05, momentum=0.9, decay=0.0001, nesterov=False)
model.compile(optimizer=sgd, loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train,y_train,batch_size=20, epochs=100, verbose=0)
The code in AndroidStudio(I have 4 fields for input numbers,1 output field and 1 Button. The predictClick method gets called when the button gets clicked):
static{
System.loadLibrary("tensorflow_inference");
}
String model_name ="file:///android_asset/iris_model.pb";
String output_name = "output_layer";
String input_name = "input_data";
TensorFlowInferenceInterface tfinterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tfinterface = new TensorFlowInferenceInterface(getAssets(),model_name);
}
public void predictClick(View v){
TextView antwort = (TextView)findViewById(R.id.antwort);
EditText number1 = (EditText)findViewById(R.id.number1);
EditText number2 = (EditText)findViewById(R.id.number2);
EditText number3 = (EditText)findViewById(R.id.number3);
EditText number4 = (EditText)findViewById(R.id.number4);
Button predict = (Button)findViewById(R.id.button);
float[] result = {};
String zahl1 = number1.getText().toString();
String zahl2 = number2.getText().toString();
String zahl3 = number3.getText().toString();
String zahl4 = number4.getText().toString();
float n1 = Float.parseFloat(zahl1);
float n2 = Float.parseFloat(zahl2);
float n3 = Float.parseFloat(zahl3);
float n4 = Float.parseFloat(zahl4);
float[] inputs={n1,n2,n3,n4};
//im pretty sure these lines cause the error
tfinterface.feed(input_name,inputs,4,1);
tfinterface.run(new String[]{output_name});
tfinterface.fetch(output_name,result);
antwort.setText(Float.toString(result[0]));
}
The build runs without error, but when I hit the predict button the app chrashes. When I leave the the lines
tfinterface.feed(input_name,inputs,4,1);
tfinterface.run(new String[]{output_name});
tfinterface.fetch(output_name,result);
out the app runs correctly, so I think that's were the error comes from.
Your model's input layer is named "input_layer" in the python code, but "input_data" in the Java code.
Also check your logcat output. You should get an error message stating, that the model doesn't have the input layer you're searching for.

Calculator based on one field

I'm working on Android Studio, to make one field calculator
It will be just one Text field, button, and another text view.
If I put "2+5*6" for example it must understand the operation.
Can anyone help me?
Check out my code please
public class MainActivity extends AppCompatActivity {
public static final String equation = "[0-9]";
String opr = " ";
int[] result;
int castedInt;
String temp;
String[] separated;
EditText txte;
TextView txtv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buResult(View view) {
txte = (EditText)findViewById(R.id.editText);
for (int i = 0; i < txte.length(); i++) {
if (Pattern.matches(txte.toString(), equation)) {
separated[i] = txte.toString();
temp = separated[i];
castedInt = Integer.parseInt(temp.toString());
result[i] = castedInt;
}
else {
opr = txte.toString();
}
txtv.setText(result[i] + opr + result[i]);
}
}
}
You should implement reverse polish notation for string.
Example code could be find here https://codereview.stackexchange.com/questions/120451/reverse-polish-notation-calculator-in-java
As defined in the documentation regex must be a regular expression. You need to transform the user input into a regular expression.
Pattern.matches(String regex, CharSequence input)
Also you are always using the whole user input:
separated[i] = txte.toString();
All "separated" indexes will contain the same.
If it's Ok to use language support (instead of creating algorithm from scratch) you can use like this:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
...
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
txtv.setText(engine.eval(txte.toString()));
*credits : stackoverflow.com/a/2605051/936786

How to save number from user input?

Recently I've started to mess around with Android Studio and decided to make an app. I've made the most of my app, but I encounter a little problem. I need to memorize in a variable a number from user input, but I don't know how to that, I've tried solutions found on the internet, even here but I get an error.
Can somebody help me with some ideas or the code edited which I must put in my app ?
This is the java code for the activity:
public class calc_medie_teza extends ActionBarActivity implements View.OnClickListener {
EditText adaug_nota;
static final int READ_BLOCK_SIZE = 100;
TextView afisare;
TextView afisare2;
Button calc;
EditText note_nr;
EditText nota_teza;
int suma;
double medie;
double medieteza;
int nr_note = 0;
int notamedie;
int notateza;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc_medie_teza);
afisare = (TextView) findViewById(R.id.afisare);
afisare2 = (TextView) findViewById(R.id.afisare2);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(this);
note_nr = (EditText) findViewById(R.id.note_nr);
nota_teza = (EditText) findViewById(R.id.nota_teza);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_calc_medie_teza, menu); // creare meniu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); // meniu
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void onClick(View v) // afisare medie
{
calcul_medie();
}
public void buton_adauga(View v)
{
if(note_nr == )
suma = suma + notamedie;
nr_note = nr_note + 1;
}
public double calcul_medie() // calculul mediei
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
Here is a photo with the activity: http://onlypro.ro/img/images/ootllv2f55hnwdgi0xlv.png
Basically the app needs to add the input number to variable when I press the "Adauga nota" [Add grade] button and then I have to insert the "teza" number and when press the "Calculeaza media" [Calculate] the app will then calculate the calcul_medie() and return a decimal number. Between "Introduceti notele aici" [Add grades here] and "Adaugata nota"[Add grade] I have a Number enter text, the same is between "Introduceti teza aici" [Add thesis bere] and "Calculeaza media" [Calculate]. I don't know how to store the number the user puts in and sum it in "notamedie" variable.
I hope you understand my problem.
For any questions you'll have I'll respond as soon as I can.
Thanks in advance !
Well, I think your probably asked how to get the input of the String from the UI and translate them into Integer/BigDecimal. If so, here is some solution:
first, you get get the string from the UI:
String input = note_nr.getText().toString().trim();
change the string input to integer/BigDecimal:
int number1 = Integer.parseInt(input);
BigDecimal number2 = new BigDecimal(input);
Correct me if misunderstood your questions. Thanks.
I did not understand the problem at all. Please clearly define the problem and use english if you can. As fas the I understood there will be a Edittext to which the user will input the value. Gets its value in the activity and then use it.
EditText edittext;
editext = (EditText) findViewById(R.id.editext);
String value = edit text.getText().toString(); // the value that the user inputted in String data format
// Here for addition you will need the value in int or decimal for that
int valueInt = Integer.parse(value); // this will be the value in int type
double valueInt = = Double.parseDouble(value); // this will be the value (user inputted) in double data type ( which you will need if you want to use decimal numbers).
When you press a button just retrieve the appropriate value from the edittext in the following way
edittext = (EditText)layout.findViewById(R.id.txtDescription);
String string = edittext.getText().toString();
to retrieve the text do this
String string = note_nr.getText().toString();
// Converting String to int
int myValue =Integer.parseInt(string);
I tried that one more time, but the IDE says that the variable I used for "string" is never used, but I've used it.
number1= (EditText) findViewById(R.id.number1);
String number_1 = number1.getText().toString();
number2= (EditText) findViewById(R.id.number2);
String number_2= number2.getText().toString();
R3muSGFX, can you post the whole codes?
String number_1 = number1.getText().toString(); this line codes just mean that you initialized a String variable "number_1".
and you will used it when app perform a math function, like you wrote in the beginning:
public double calcul_medie()
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
but if you did not use "number_1" at all, IDE will imply you the warning message
:the variable I used for "string" is never used

how do i get the product of the inputted values in two edittext?

I want to get the product of the inputted values in two editTexts.
For example I will input [1,2,3,4,5] in xValues then I will input also [6,7,8,9,10] in freqValues then it will multiply (1*6),(2*7),(3*8),(4*9),(5*10). How will i do that? Please help me. Thank you in advance:)
final AutoCompleteTextView xValues = (AutoCompleteTextView) findViewById(R.id.x_Values);
final AutoCompleteTextView freqValues = (AutoCompleteTextView) findViewById(R.id.frequency_Values);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int[]convertedx=new int[x.length];
int[]convertedfreq=new int[freq.length];
}
});
You'll have to do some error catching to make sure only numbers are inputted but once you get that figured out, do something like this:
...
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int product = 0;
for(int i = 0; i < x.length(); i++) {
int tempX = Integer.parseInt(x[i]);
int tempFreq = Integer.parseInt(freq[i]);
product += (tempX * tempFreq);
}
Assuming that the arrays are split correctly and only contain integers, this loop will grab the first int from X[] and Freq[] and then multiply them together, and add it to product, then grab the 2nd int from these arrays, parse the string into an int, and then multiply those and loop through until the end of the array.

Categories

Resources