I want to take the depth input by the user and mathematically operate on it to obtain cost and then display it to the user. How do I go about doing that?(If didn't notice already, I don't know Java). Thanks.
private void estimateCost(View view){
EditText depth = findViewById(R.id.depth);
TextView cost = findViewById(R.id.cost);
String x = depth.getText().toString().trim();
cost.setText(x);
}
You need to parse your String obtained from EditText, then perform some operations.
private void estimateCost(View view){
EditText depth = findViewById(R.id.depth);
TextView cost = findViewById(R.id.cost);
String x = depth.getText().toString().trim();
// parse to a number, i.e. int
int depthValue = Integer.parseInt(x);
// calculate total cost
int totalCost = ...
cost.setText(String.valueOf(totalCost));
}
You can create a button to obtain the value. For example:
<Button
android:id="#+id/bt_calc"
android:text="calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Then you can catch the click event (put it inside onCreate method):
EditText depth = (EditText) findViewById(R.id.depth);
TextView cost = (TextView) findViewById(R.id.cost);
Button btCalc = (Button) findViewById(R.id.bt_calc);
int costValue;
btCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//in here you can
//get the depth from the EditText:
int depthValue = Integer.valueOf(depth.getText().toString());
//do the operations (example):
costValue = depthValue + 1;
//and display the cost in the TextView:
cost.setText(String.valueOf(costValue));
}
});
Good luck!
If your input contains letters as well you won't get int from it with Integer.parseInt()
Use this
int x = 0;
for (int i=0; i < str.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') continue;
x = x * 10 + c - '0';
}
Related
I am new to programming and started android few week back.
public class MainActivity extends AppCompatActivity {
int a,i,j,k;
/*char [][] s1= new char[][]
{
{'A','B','C','D'},
{'E','F','G','H'},
{'I','J','K','L'},
{'M','N','O','P'},
{'Q','R','S','T'},
{'U','V','W','X'},
{' ','Y','Z',' '}};*/
char [][] s2=new char[8][8];
char[][] s3=new char[8][8];
int[] getlist= new int[10];;
char choice,choice1;
int x,b,c,d;
String[] messageText = new String[10];
String[] messageEdit = new String[10];
public void letterNo(View view) { // Method to show screen for getting number of letters
setContentView(R.layout.displaylettersno);
}
public void getNumber(View view) { // Method to get Numbers of Letter
EditText et = (EditText) findViewById(R.id.editText);
String s = et.getText().toString();
x = Integer.parseInt(s);
if (x > 0 && x < 9) {
et.setText("");
} else {
Toast.makeText(getApplicationContext(), "Wrong Entery... Enter again", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.gettingcolumnno);
// Toast.makeText(getApplicationContext(),"Click on Column No in Which 1st Letter Appear",Toast.LENGTH_LONG).show();
TextView textView = (TextView) findViewById(R.id.textView8);
for (i = 0; i < x; i++){
textView.setText("Enter Column No. in which Your letters of name is
present:" );
}
}
public void buttondone(View view) {
EditText op = (EditText) findViewById(R.id.operator2);
String num = op.getText().toString();
for (i = 0; i < x; i++)
{
getlist[i] = Integer.parseInt(String.valueOf(op.getText()));
}
Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I want to develop a Name guess game
1- it will ask user to enter the no. of letters he thought
2- it will ask user to enter the column no in which his letter present ( i want this to run according to user enter the no of letter .
suppose user enter 4 digits and it will ask to enter the column no 4 times.
and similarly it has a edit box where user enter column no .
i am using for loop for this purpose but it only show 1 time i am stuck here for 1 week . help me if you understand what i am trying to do . following is my code
Done button has to be pressed number of letters time to get columns.
TextView textView = (TextView) findViewById(R.id.textView8);
int numberOfColumnsEntered = 0;
public void getNumber(View view) {
// get number logic then
textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
}
public void buttondone(View view) {
EditText op = (EditText) findViewById(R.id.operator2);
String num = op.getText().toString();
getlist[numberofColumnsEntered] = Integer.parseInt(num);
numberofColumnsEntered++;
textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
if(numberofColumnsEntered == x) {
Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}
}
So, I'm developing an app for my graduation final project and in my app I have a layout with an imageView and a textView, to set the content of these elements I receive an ArrayList as a parameter and use the setText(), and it works.
But my Arraylist has more than one element, and my big problem is that I want to change the content of the imageView and the textView when I click in a button.
The way I was thinking was that when I click the button it will increment the value and change the content of the objects for the next element inside the arrayList.
I've faced problems with global variables inside onClickListeners, but I solved them with auxiliar methods, but this time that doesn't work since I need to increment the value of the iteration inside the button event.
Can you guys please help me with suggestions or tell me what I'm I doing wrong?
I hope you understand my problem, and I'm sorry if I didn't explain me well, feel free to ask any questions and request more blocks of code if what I post isn't enough.
Thanks in advance to all you guys, i apreciate all the help you can give me!
To get the data from my db and store it into an arraylist
private ArrayList<Exercises> getExercisesSelectedPlan() {
ArrayList<ProgramExercises> arrayList_programExercises = new ArrayList<();
ArrayList<Exercises> arrayList_exercises = new ArrayList<>();
Button btnNext = (Button) findViewById(R.id.btnFinishAquecimento);
//with the id of the selected plan, select all the exercises from the plan and load them into the layout
int idProgram = getIdPlan();
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
String queryProgramExercises = "SELECT * FROM PROGRAM_EXERCISES WHERE PROGRAM_ID_PROGRAM = " + "'" + idProgram + "'" + " ORDER BY ORDER_EX ASC";
Cursor cursorProgramExercises = db.rawQuery(queryProgramExercises, null);
int numRows = cursorProgramExercises.getCount();
if (numRows > 0) {
cursorProgramExercises.moveToFirst();
while (numRows > 0) {
for (int i = 0; i < cursorProgramExercises.getCount(); i++) {
ProgramExercises nProgramExercises = new ProgramExercises();
nProgramExercises.setIdProgramExercises(cursorProgramExercises.getInt(0));
nProgramExercises.setOrder(cursorProgramExercises.getString(1));
nProgramExercises.setRepetition(cursorProgramExercises.getInt(2));
nProgramExercises.setIdExercises(cursorProgramExercises.getInt(3));
arrayList_programExercises.add(nProgramExercises);
numRows--;
}
}
}
//for each select result from program_exercises i have to select the exercise with the id correspondent to nProgramExercies.getidExercises
for (int i = 0; i < arrayList_programExercises.size(); i++) {
String queryExercises = "SELECT * FROM EXERCISES WHERE ID_EXERCISES = " + "'" + arrayList_programExercises.get(i).getIdExercises() + "'";
Cursor cursorExercises = db.rawQuery(queryExercises, null);
cursorExercises.moveToNext();
if (cursorExercises.getCount() > 0) {
Exercises exercises = new Exercises();
for (int j = 0; j < cursorExercises.getCount(); j++) {
exercises.setIdExercises(cursorExercises.getInt(0));
exercises.setMedia(cursorExercises.getString(1));
exercises.setDesignation(cursorExercises.getString(2));
exercises.setIdExercisesPhase(cursorExercises.getInt(3));
arrayList_exercises.add(exercises);
cursorExercises.moveToNext();
}
cursorExercises.close();
}
}
cursorProgramExercises.close();
db.close();
databaseHelper.close();
}
Where I want to change the content of the textview and increment the iteration when I click btnNext
public void prepareExercise(final ArrayList<Exercises> exercises) {
setContentView(R.layout.activity_execute_ex_warmup);
TextView txtPrepare = (TextView) findViewById(R.id.tvAquecimento);
ImageView imageExercise = (ImageView) findViewById(R.id.ivAquecimento);
Button btnNext = (Button) findViewById(R.id.btnFinishAquecimento);
txtPrepare.setText(exercises.get(1).getDesignation());
imageExercise.setImageResource(R.drawable.imgTest);
for (int i = 0; i < exercises.size(); i++) {
if (exercises.get(i).getIdExercisesPhase() == 1) {
txtPrepare.setText(exercises.get(i).getDesignation());
System.out.println("------ TEST" + exercises.get(i).getDesignation());
}
}
//Click Next Button
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//for (int i = 1; i < exercises.size(); i++) {
//TextView txtPrepare = (TextView) findViewById(R.id.tvAquecimento);
//txtPrepare.setText(exercises.get(finalI).getDesignation());
//}
//executeExercise(); //next Exercise
}
});
}
How I invoke the previous method
prepareExercise(getExercisesSelectedPlan());
Hopefully I'm understanding correctly.
If you just want to update the views each time the button is clicked the easiest way would be just to create a variable and store the position of the array list.
public int listIncrement = 0;
private TextView txtPrepare;
private ImageView imageExercise;
Then in your prepareExercise() method
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listIncrement <= excersises.size()) {
executeExercise(excersises, listIncrement); //next Exercise
listIncrement++;
}
}
});
and then in executeExercise(ArrayList exercises, int position) //guessed method name, can be whatever you like
txtPrepare.setText(exercises.get(position).getDesignation());
imageExercise.setImageResource(R.drawable.imgTest);
private TextView info;
private EditText input;
private Button getInfo;
long answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInfo = (Button) findViewById(R.id.button1);
getInfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
input = (EditText) findViewById(R.id.editText1);
String s2 = input.getText().toString();
long inputNumber = Integer.parseInt(s2);
for (int i = 0; i <= inputNumber; i++) {
answer = fibonacci(i);
}
input.setText(answer + "");
}
});
}
public static long fibonacci(long n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
I made a program which generates fibonacci series for the number I give input through edit text and display the output value in edittext .Issue is when I enter 30 it generates fibonacci series but when I enter 50 or 100 app does not respond and stops .
I think it is because you have a lot of calculation on UI thread.
Try calculate it in AssyncTask, for example.
I'm trying to develop an app that compares the user's input number to a randomly generated number from the computer, depending on whether the input number is higher, lower or the same as the generated number, there is a different message output. However the app crashes (with this stacktrace) whenever I try and run it. Here is my code for my method:
If anyone can recognise why it's crashing it would be great - new to Android so it's hard to see errors.
public void guessingGame (View v)
{
EditText guess = (EditText) findViewById(R.id.ETguess);
TextView guessError = (TextView) findViewById(R.id.guessError);
TextView compGuess = (TextView) findViewById(R.id.tvCompGuess);
int guessValue = Integer.parseInt(guess.getText().toString());
if (guessValue > 20)
{
guessError.setVisibility(View.VISIBLE);
guess.getText().clear();
}
else if (guessValue < 1)
{
guessError.setVisibility(View.VISIBLE);
guess.getText().clear();
}
else
{
int min = 1;
int max = 20;
Random r = new Random();
int i = r.nextInt(max - min + 1) + min;
int computerNumber = i;
compGuess.setText(i);
if (computerNumber > guessValue)
{
guessError.setText("Too low!");
}
else if (computerNumber < guessValue)
{
guessError.setText("Too high!");
}
else if (computerNumber == guessValue)
{
guessError.setText("Good Guess!");
}
}
}
compGuess.setText(i);
You cannot use TextView.setText(int) to set the text to an arbitrary integer. The integer must be the resource ID of a string (typically defined in res/values/strings.xml, or imported from one of your upstream dependencies).
If you want to set a TextView's contents to a string representing an integer you should do it like this
compGuess.setText(Integer.toString(i));
I made a program that computes the geometric mean and my program is already working but i have some sort of errors. Whenever i click the btnCalculate with an empty input in my inputValues my program stops working. how am I going to deal with this error? Thanks:)
final AutoCompleteTextView inputValues = (AutoCompleteTextView) findViewById(R.id.txt_input);
final TextView txtTotalNum = (TextView) findViewById(R.id.txt_totalNumber);
final TextView GeoMean= (TextView) findViewById(R.id.txt_GeoMean);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
});
Button btnclear = (Button)findViewById(R.id.btnclear);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
inputValues.setText("");
txtTotalNum.setText("");
GeoMean.setText("");
}
You are getting errors because your code is trying to split on empty strings or null and then accessing values[] that really have no index at all. Just check if the string fetched by the EditText has a length>0.
#Override
public void onClick(View agr0) {
String fetchedValues = ( inputValues.getText().toString());
if(fetchedValues.length>0)
{
String []values = fetchedValues.split(",");
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
else
{
//alert the user that the field is empty
}
}
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
if(values !=NULL){
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
// try this
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
if(inputValues.getText().toString().length()>0){
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
});
Your program stops at
convertedValues[a] =Integer.parseInt(values[a]);
because for an empty input the split array has no values, so its length is 0. And when you try to access values[0]you get an ArrayIndexOutOfBoundsException.
Just check if the input is emty, before splitting it.
if(!inputValues.getText().toString().equals("")){
... // do your stuff
} else {
// show a message
}