Counting filled EditText fields [closed] - java

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;
.
.
.
}

Related

How to get data from many EditTexts when Its added in layout programmatically in android

I'm adding EditText in linear layout and it gives a view like that in image.
I'm getting this view by using this code.
public class SearchRecipe extends AppCompatActivity {
LinearLayout parentLayout;
ImageButton searchRecipe;
private int EDITTEXT_ID = 1;
private List<EditText> editTextList;
EditText editTextItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_recipe);
setActionBar();
init();
searchRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextItem = (EditText) parentLayout.findViewById(EDITTEXT_ID);
for (int i = 0; i < editTextList.size(); i++) {
Log.e("All Values=", editTextList.get(i).getText().toString());
Toast.makeText(SearchRecipe.this, editTextItem.getText().toString() + " ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void init() {
parentLayout = (LinearLayout) findViewById(R.id.parent_layout); //make sure you have set vertical orientation attribute on your xml
searchRecipe = (ImageButton) findViewById(R.id.search_button);
editTextList = new ArrayList<EditText>();
TextView addMoreText = new TextView(this);
addMoreText.setText("Add More Ingredients");
addMoreText.setGravity(Gravity.CENTER);
addMoreText.setPadding(20, 20, 20, 20);
addMoreText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.add, 0);
addMoreText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextItem = new EditText(SearchRecipe.this);
editTextItem.setId(EDITTEXT_ID);
editTextList.add(editTextItem);
EDITTEXT_ID++;
editTextItem.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cross, 0);
editTextItem.setPadding(20, 20, 20, 20);
editTextItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
parentLayout.removeView(editTextItem);
return true;
}
});
parentLayout.addView(editTextItem, 0);
}
});
parentLayout.addView(addMoreText);
}
Now the only problem I'm facing is that. I'm not getting the text from edittext properly. Let me Explain what I want to do.
Click on Add More TextView will add one more edit text.
After adding all edittexts I will click on Search button.
By clicking search button will get the data from edittexs and save in arraylist. I tried a lot but can't do this properly. will you please help me to do this thing ? I'm stuck in from many days.
if you are createing edit text run time only for this purpose then there is no need of below tow lines
editTextItem.setId(EDITTEXT_ID);
EDITTEXT_ID++;
To retrive data from each edit box follow below things
for (EditText editText : editTextList) {
/* now you can get the value from Edit-text and save in the ArrayList
or you can append it in same string*/
yourArraList.add(editText.getText().toString()));
}
Get the editext from your list editTextList
String data = editTextList.get(index).getText().toString();
Add check for editTextList should not be null or empty.
You can iterate over list using for-each loop
for (EditText editText : editTextList) {
// now you can get the value from Edit-text and save in the ArrayList
yourArraList.add(editText.getText().toString()));
}
you can do like below if view inside fragment.
public static String getText(final Activity activity) {
final StringBuilder stringBuilder=new StringBuilder();
LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);
ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText editText = (EditText) innerLayout.findViewById(R.id.meeting_dialog_et);
msg.add(editText.getText().toString());
}
for (int j=0;j<msg.size();j++)
{
stringBuilder.append(msg.get(j)).append(";");
}
Toast t = Toast.makeText(activity.getApplicationContext(), stringBuilder.toString(), Toast.LENGTH_SHORT);
t.show();
return stringBuilder.toString();
}
there is another way is make arraylist Edittexes and add each edittext when it added to layout. then you can get like below:
for (int i = 0; i < Edittexes.size(); i++) {
if (Edittexes.get(i) == view)
{
String text=Edittexes.get(i).getText();
}
}

if statement to match users input to string answer [closed]

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()).

Android: Passing int value from one activity to another

I'm struggling to figure out why I can't pass an int value from one activity to another. The app will ask you to press a button to generate a random number from 1-100 which will be displayed below the button. There is also another button which will open a new activity simply showing the random number that was rolled... but I just get 0.
I've looked into similar questions asked but to no avail.
Here's my code from MainActivity
public class MainActivity extends ActionBarActivity {
int n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonRoll(View view) {
TextView textRoll = (TextView) findViewById(R.id.textview_roll);
Random rand = new Random();
n = rand.nextInt(100) + 1;
String roll = String.valueOf(n);
textRoll.setText("Random number is " + roll);
}
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
startActivity(getStats);
}
public int GetNumber (){ return n; }
}
Heres my 2nd class.
public class Stats extends Activity {
MainActivity statistics = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = statistics.GetNumber();
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
}
Is using getters the wrong way to get data from another class when using activities? Thanks for your time.
You should pass your data as an extra attached to your intent. To do this you need to first determine a global key to be used. You could do something like this in your MainActivity
public static final String SOME_KEY = "some_key";
then modify your OpenStats method to
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
getStats.putExtra(SOME_KEY, n);
startActivity(getStats);
}
and then in Stats.class onCreate method
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = getIntent().getIntExtra(MainActivity.SOME_KEY, -1);
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
You obviously should make sure that you are calling ButtonRoll at least once or that you set n so that you aren't passing a null int.
Also, as note, convention states that methods should use lower camel case formatting. That is, the first word is completely lower case and the first letter of subsequent words is upper case. That would change your methods
OpenStats() -> openStats()
ButtonRoll() -> buttonRoll()
Classes/objects are upper camel case, just to help avoid confusion.

Optimising Android/Java Code - Creating multiple instances of the same object type

I have a working application but want to optimise the code. Below is one example where I create 10 separate imagebuttons (note the incrementing objectname and XML reference for each) and set their listeners. Can anyone suggest a more optimal way of doing this, perhaps in a dynamic method/loop please? Thanks....
private void initialiseButtons() {
ImageButton imageButton1 = (ImageButton)this.findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(this);
ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(this);
ImageButton imageButton3 = (ImageButton)this.findViewById(R.id.imageButton3);
imageButton3.setOnClickListener(this);
ImageButton imageButton4 = (ImageButton)this.findViewById(R.id.imageButton4);
imageButton4.setOnClickListener(this);
ImageButton imageButton5 = (ImageButton)this.findViewById(R.id.imageButton5);
imageButton5.setOnClickListener(this);
ImageButton imageButton6 = (ImageButton)this.findViewById(R.id.imageButton6);
imageButton6.setOnClickListener(this);
ImageButton imageButton7 = (ImageButton)this.findViewById(R.id.imageButton7);
imageButton7.setOnClickListener(this);
ImageButton imageButton8 = (ImageButton)this.findViewById(R.id.imageButton8);
imageButton8.setOnClickListener(this);
ImageButton imageButton9 = (ImageButton)this.findViewById(R.id.imageButton9);
imageButton9.setOnClickListener(this);
ImageButton imageButton0 = (ImageButton)this.findViewById(R.id.imageButton0);
imageButton0.setOnClickListener(this);
}
You could use a loop and use getIdentifier() method.
int idToInitialize;
ImageButton ib;
for (int i = 0; i < 9; i++) {
idToInitialize = getResources().getIdentifier("imageButton" + i, "id", getPackageName());
ib = (ImageButton) this.findViewById(idToInitialize);
ib.setOnClickListener(this);
}
Hovewer, it is very slow if we compare to the normal method.
You can reduce the boilerplate code by using http://androidannotations.org/ which will allow you to do someting like that
#ViewById
ImageButton imageButton1;
but it would be perhaps better to use an array or a list of buttons rather than multiple references, something like that for example :
private void init() {
int[] ids=new int[]{R.id.imageButton1, R.id.imageButton2 ...};
List<ImageButton> buttons=new ArrayList<ImageButton>;
for(int id : ids) {
buttons.add((ImageButton)this.findViewById(id));
}
}
you can then easily iterate on the List, for example to set the listener
for(ImageButton button : buttons) {
button.setOnClickListener(this);
}
You can use arrays, lists ...
For example:
private static final int[] BUTTONS_IDS = new int[] {R.id.imageButton0, R.id.imageButton1, R.id.imageButton2, R.id.imageButton3, R.id.imageButton4, R.id.imageButton5, R.id.imageButton6, R.id.imageButton7, R.id.imageButton8, R.id.imageButton9};
ImageButton[] buttons = new ImageButton[BUTTON_IDS.length];
private void initialiseButtons() {
for (int i = 0; i < BUTTONS_IDS.length; i++) {
buttons[i] = (ImageButton) findViewById(BUTTONS_IDS[i]);
buttons[i].setOnClickListener(this);
}
}
You can also put the list of ids in the arrays.xml file.
I can't try it cause I have no Android Environmetn here. But I think this should work:
private void initialiseButtons() {
for(int i = 0; i < 10; i++) {
ImageButton imageButton = (ImageButton)this.findViewById(R.id.getClass().
getField("imageButton" + i).get(R.id));
imageButton.setOnClickListener(this);
}
}
If it's only for setting the onClickListener, you can get rid off your whole initialiseButtons() methods and simply add android:onClick="handleButtonClick" in your layout xml and define that method in your activity like so:
public void handleButtonClick(View view) {
switch(view.getId()) {
case R.id.imageButton1: // handle button 1 pressed ....
case R.id.imageButton2: // handle button 2 pressed ....
// ... handle further buttons
}
}

How do I get this string array to pass over to the next class and be used

This is kind of hard to explain. Basically it's kind of like a simple game. I want the people to input their names (currently the submit button is not working correctly) hit submit for each name and when all names are in they hit play. It then opens up the next class. It needs to get the string array from the prior class as well as the number of players. It then needs to select each persons name in order and give them a task to do (which it randomly generates). Then it allows the other people to click a button scoring how they did. (I am not sure how to set up the score system. Not sure if there is a way to assign a score number to a particular array string) I would then like it after 5 rounds to display the winner. If you have any input or could help me out I would be extremely grateful. Thanks for taking the time... here are the two classes i have.
Class 1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < players; i++)
{
names[i] = input.getText().toString();
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Class2.class);
done.putExtra("players", players);
done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Class 2
public class Class2 extends Activity
{
int players, counter, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class2);
Intent game = getIntent();
players = game.getIntExtra("players", 1);
names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "task1";
tasks[1]= "task2";
tasks[2]= "task3";
tasks[3]= "task4";
tasks[4]= "task5";
tasks[5]= "task6";
tasks[6]= "task7";
tasks[7]= "task8";
tasks[8]= "task9";
tasks[9]= "task10";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
//not sure what to put here to get the scores set up
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
//not sure what to put here to get the scores set up
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
//not sure what to put here
}
});
counter++;
}
}
I'm sure this thing is riddled with errors. And I'm sorry if it is I'm not that well experienced a programmer. Thanks again
You can pass a string array from one activity to another using a Bundle.
Bundle bundle = new Bundle();
bundle.putStringArray("arrayKey", stringArray);
You can then access this stringArray from the next activity as follows:
Bundle bundle = this.getIntent().getExtras();
String[] stringArray = bundle.getStringArray("arrayKey");
I'm not sure if this is the only thing you intend to do. I hope it helps. Also, to assign a score to a particular string array, assuming your scores are int's you could use a HashMap as follows,
HashMap<String[],int> imageData = new HashMap<String[],int>();
But I'm not sure how you would pass this Map to another activity if you intend to do so.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,%20java.lang.String[])
Use this cheat:
In Class2, convert you array string (tasks) to string (strSavedTask)by adding "|" separator. After that, pass your strSavedTask into Bundle and start to Class1.
When return to Class1, read strSavedTask from Bundle, split it by "|".
That's my cheat to pass array between 2 activity ^^
Hope this way can help you!

Categories