This question already has answers here:
How to convert TextView value to Integer
(2 answers)
Closed 2 years ago.
For the if statements part, it has a red mark. and it says, operator '+' can't be applied to 'TextView', 'int'. And I have a no clue what to do with that. Am I not able to use < kind of symbol for if statement?
public class result extends AppCompatActivity {
Button button3;
TextView message;
TextView SMM;
TextView BFM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
SMM = (TextView) findViewById(R.id.SMM);
BFM = (TextView) findViewById(R.id.BFM);
button3 = (Button) findViewById(R.id.button3);
button3.setClickable(true);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String musclemass = SMM.getText().toString();
String fatmass = BFM.getText().toString();
Intent intent = new Intent();
intent.putExtra("musclemass", musclemass);
intent.putExtra("fatmass", fatmass);
if(musclemass < fatmass + 50){
message.setText("kid");
}
if(musclemass > fatmass + 50){
message.setText("adult");
}
}
});
}
}
Change
if(SMM < BFM + 50){
to
if(Integer.valueOf(SMM.getText().toString())< Integer.valueOf(BFM.getText().toString())+ 50){
and similar at other locations as TextView and integer are two different datatypes. You have to first get Integer value and then compare them
Seem you don't understand what is the TextView, SMM in your case for example. You already get the string musclemass from SMM(TextView), right?
How would you describe this, SMM.getText().toString ?
Assume that you know you got a string.
Why don't you (try to) convert this string to int (Integer). You have to screen and make sure that the input is really an Integer, not other characters.
Since TextView (BFM in this case) is not an integer number, it can't be added (+) with 50.
You would better use EditText instead of TextView.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am building an app, that has Multiple EditText fields and a Button.
For information, Button is supposed to open a new Activity (I haven't got to that yet), based on filled EditText fields,
So, let Suppose
1) if 3rd Editext fields have some value, the button will open 3rd Activity
2) if 4th Editext fields have some value, button opens 4th Activity.
and this goes on for every EditText fields.
The question is, How do I count filled editText fields?
You can do it in Activity like this.. But you have to add
android:tag="et" in all your Edittext fields of layout.. Change the parent layout type in your code Accordingly. It working as Tested..
public class MainActivity extends AppCompatActivity {
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.linearLayout);
int elements = parentLayout.getChildCount();
View v = null;
for(int i=0; i<elements; i++) {
v = parentLayout.getChildAt(i);
if(v.getTag()!=null && v.getTag().equals("et")){
count= count++;
}
}
}
}
On The base of count you can take decision.
As you highlighted how to get the filled fields count below countFilledFileds() method will help you. As I understood your problem this will be the complete solution.
public class SampleActivity extends AppCompatActivity {
private EditText editText1,editText2,editText3,editText4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Button btn = findViewById(R.id.btn);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
editText3 = findViewById(R.id.editText3);
editText4 = findViewById(R.id.editText4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = SampleActivity.class;
switch (filledFileds){
case 1:
newClass = Activity1.class;
break;
case 2:
newClass = Activity2.class;
break;
case 3:
newClass = Activity3.class;
break;
case 4:
newClass = Activity4.class;
break;
default:
}
Intent intent = new Intent(SampleActivity.this, newClass);
}
});
}
private int countFilledFields() {
ArrayList<EditText> editTexts = new ArrayList<>();
editTexts.add(editText1);
editTexts.add(editText2);
editTexts.add(editText3);
editTexts.add(editText4);
int filledNumber = 0;
for(int i = 0;i < editTexts.size() ;i++){
if(editTexts.get(i).getText()!=null && !editTexts.get(i).getText().toString().matches("")){
filledNumber += 1;
}
}
return filledNumber;
}
}
Loop your EditText objects and know whether it has value or not;
For example,
EditText e1 = ....
EditText e2 = .....
.
.
.
EditText e10 = .....
EditText allText[] = new EditText[]{e1, e2, ...e10};
int filled = 0;
for(int i = 0; i < allText.length; i++) {
if(!allText[i].getText().toString().isEmpty())
filled++;
}
So your filled has the count.
You can make use of some flag to set the count of filled editText fields.
Add all your editText references to List. And use the below method to get the count.
int count =0;
private int getEditTextViewCount(List<EditText> editTexts){
for(EditText editText : editTexts){
if(!editText.getText().toString().isEmpty()){
count++;
}
}
return count;
}
I don't have Android SDK at the moment, so there might be some mistakes but you can try something like this:-
long numberOfFilledFields = Stream.of(
editText1.getText().toString(),
editText2.getText().toString(),
editText3.getText().toString()) //you can add as many as you want here
.filter(s -> !s.isEmpty())
.count();
switch (numberOfFilledFields) {
case 0:
//start activity 1
break;
case 1:
//start activity 2
break;
.
.
.
}
I'm new to android programming with very little experience, I'll try ask the correct question but I apologize if some of my understanding isn't quite up to scratch.
I'm building a basic calculator app with buttons 0 to 9. The user can use these to input that specific number into a text field.
I have the same piece of code (below) to do my button action for all 0 to 9 buttons. Just where to see the number 1 it's replaced with that buttons relevant number.
Button button1 = (Button) findViewById(R.id.button_calc_1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number_1 = ("1");
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
So i'm writing a subroutine of the same code that I can then call upon for the relevant button.
public String numberbuttons(String value){
Button button1 = (Button) findViewById(R.id.button_calc_1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number_1 = ("1");
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
}
Bear in mind this is a work in progress.
My question is basically how do I add the variable numberbuttons to the button_calc_(insert numberbuttons here)
EDIT:
Okay so from the second block of code. I want to use the numberbuttons variable within the findViewById(R.id.button_calc_1).
So in my head I picture it like this.
findViewById(R.id.button_calc_+(numberbuttons);
The same for when I call a textview. I picture it like this.
TextView Insert_Number_+(numberbuttons) = (TextView ) findViewById(R.id.editTextoutput);
The findViewById() method requires an integer, not a String, so you cannot just pass in a String with the name of the button that you are trying to use. When you use R.id.xxx you are passing a reference to the resource, which is actually just an int.
To accomplish what you want I suggest using a list of some type to store the buttons, and then looping through this. Please see an example below.
ArrayList<Button> buttons = new ArrayList<>();
buttons.add((Button) findViewById(R.id.button1)); //Do this for all the buttons.
for(Button b : buttons){
b.setText("1"); //Do whatever you need to each button in here.
}
If you wanted to use a method to manage all your buttons, you can do this too!
changeButton((Button) findViewById(R.id.button1));
private void changeButton(Button b){
//Change the button
}
EDIT:
To be more relevant to your question if I understand correctly, to add an event handler to each.
ArrayList<Button> buttons = new ArrayList<>();
buttons.add((Button) findViewById(R.id.button1)); //Do this for all the buttons.
for(int i = 0; i < buttons.size(); i++){
Button b = buttons.get(i);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number = String.valueOf(i);
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
}
This question already has an answer here:
How to receive an int through an Intent
(1 answer)
Closed 4 years ago.
I'm trying to pass an Integer (from an edittext) to another activity through an intent.
When the user clicks a button, the text in the edittext will transform into a string and then into an int, then the int will be sent through an intent to another activity, but i have to use the int after that.
Here the activity sending the intent:
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext = (EditText) findViewById ( R.id.texthome );
Button buttone = (Button) findViewById(R.id.buttone);
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Here the activity receiving it:
public class GuessOne extends ActionBarActivity {
int randone;
int contone;
int wall = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_guess_one);
wall = getIntent().getIntExtra("maxPressed", -1);
randone = (int) (Math.random()*10+1);
contone = 0;
}
Here i'm using it:
public void guessone (View view){
contone++;
textcontone.setText(getString(R.string.attempts) + "" + contone);
if (contone >= wall ){
resultaone.setText("You Failed" + " " + wall);
Toast.makeText(this, "You Failed", Toast.LENGTH_LONG).show();
}
When i use the app, the value of the int is always -1. Where i am wrong.
You can't use findViewById without setting the xml to the activity. That means you need to use findViewById method only after you have called setContentView.
Also you need to read the EditText text value once you click on the button otherwise it always will be null/empty.
Do this
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext;
Button buttone;
String maxom;
int maxam = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
maxom = conttext.getText().toString();
maxam = Integer.parseInt(maxom);
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Problem 1
Put this in the on click listener instead:
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
You want the values to be read at the time you click the button not when you open the activity, correct?
Problem 2
The following needs to be after setContentView in onCreate:
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
Keep the declarations where they are. Just the declarations:
EditText conttext;
Button buttone;
Note
Follow the same pattern in all your activities. Declare views as field variables, assign them in onCreate after setContentLayout. Get the values at the time they're needed.
public int getIntExtra (String name, int defaultValue)
Added in API level 1 Retrieve extended data from the intent.
Parameters name The name of the desired item. defaultValue the value
to be returned if no value of the desired type is stored with the
given name. Returns the value of an item that previously added with
putExtra() or the default value if none was found. See Also
putExtra(String, int)
This means that no int was found when you called getIntExtra(valueName, defaultValue); so the default value was chosen.
You should check to see what your maxam value is before you call the new activity.
In the activity you receive it:
wall = getIntent().getIntExtra("maxPressed");
SOLVED: by getInt and String.valueOf
private static final String IMGID = "ImgID";
if (getIntent().getExtras().containsKey(IMGID)) {
//Picasso.with(this).load(getIntent().getExtras().getString(IMG)).into(mImg);
Picasso.with(this).load(getIntent().getExtras().getInt(String.valueOf(IMGID))).into(mImg);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm doing a word shuffle app on android studio for a class project. I need help understanding how I can get the users input and match it to the correct String answer. I tried a few approaches and have fallen short. I tried using an if(word.equals(userAnswer)) statement but having a hard time understanding it. How can I write the if statement for text input/output to match my answer in android studio?
(Optional question) Also is public void OnClick(View v) a good approach or should I go with something else?
Any help will be greatly appreciated. Thanks in advance!
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
public void OnClick(View v){
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
Button button = (Button) v;
String word = "Animals"; // scan for word
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
String shuffledWord = new String(shuffled);
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
This will allow you to determine if they are the same
if(word.equalsIgnoreCase(userAnswer.getText().toString())) {
answerOutput.setText("Correct");
}
However, generally speaking you have a much larger problem, unless it's in code somewhere that you aren't showing us.
Somewhere in your activity onCreate/onStart you want to initialize your button with whatever view it might be.
Button checkAnswer = (Button) findViewById(//whatever your id is)
Then you want to set the onClick listener of the button. With the approach that you are using, it would end up needing two things. First this
public class MainActivity extends Activity implements View.OnClickListener {
Then in you need to set the onClick listener to your Button, probably in OnCreate.
checkAnswer.setOnClickListener(this);
Then your onClick would look something like
#Override
public void onClick(View v) {
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
}
else {
answerOutput.setText("Sorry try again.");
}
}
The logic for scrambling the word etc, probably wouldn't be in onClick here.
Also, if you have multiple things you want to set click listeners for you would do something like this
#Override
public void onClick(View v) {
switch(v.getId()) {
case(R.id.//whatever): {
//dosomething
break;
}
}
}
Where you can multiple cases for all of the views that you have set the MainActivity to handle.
Edit: Since you updated your code
public class MainActivity extends Activity implements View.OnClickListener {
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
private String word;
private String shuffledWord;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
createWord();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
private void createWord() {
word = "Animals";
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
shuffledWord = new String(shuffled);
shuffledText.setText(shuffledWord);
}
#Override
public void OnClick(View v){
if (word.equalsIgnoreCase(userAnswer.getText().toString())){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
Did you set the onClickListener of the button to your MainActivity?
Your MainActivity should implement OnClickListener too
You need to use userAnswer.getText() to get the answer. Your userAnswer variable currently is of type EditText, which means a check to see if word.equals(userAnswer) will always return false, as they are of different types. Instead, try word.equals(userAnswer.getText()) to check if their answer equals the original word. To check if their answer equals the scrambled word, use shuffledWord.equals(userAnswer.getText()).
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 9 years ago.
I just want to reverse a inputted String by using for loop.
I have tried the following code below. [ its full of mistake i think.. cause i dont know how to convert things to array or to string in this problem ]. So anyone please help me the coding here...
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
EditText input_string =(EditText) findViewById(R.id.editText1);
final String orig = input_string.getText().toString();
Button rev = (Button) findViewById(R.id.button1);
rev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int limit = orig.length();
for(int i=limit;i<=limit;i--)
{
String[] neww = orig[i].;
}
tv.setText(neww);
}}) }}
Something like this is what you're looking for.
String x = "A string";
String y = "";
for(int i = x.length()-1; i >= 0; i--){
y=y + x.charAt(i);
}
Your new string will be stored in the variable y.