Hot questions for Using Android EditText in button

Question:

Ive tried using TextWatcher, but if i create multiple TextWatchers(one for each EditText), the button enables when I start filling out any of the EditText.

Example:

public class MainActivity extends AppCompatActivity {

    EditText numberOneEditText;
    EditText numberTwoEditText;
    EditText numberThreeEditText;
    TextView sumTextView;

    public void calculate(View view) {


        String numberOneString = numberOneEditText.getText().toString();
        String numberTwoString = numberTwoEditText.getText().toString();
        String numberThreeString = numberThreeEditText.getText().toString();

        double numberOneDouble = Double.parseDouble(numberOneString);
        double numberTwoDouble = Double.parseDouble(numberTwoString);
        double numberThreeDouble = Double.parseDouble(numberThreeString);

        double sum = numberOneDouble + numberTwoDouble + numberThreeDouble;

        sumTextView.setText(sum.getText().toString())

   }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        numberOneEditText = findViewById(R.id.numberOneEditText);
        numberTwoEditText = findViewById(R.id.numberTwoEditText);
        numberThreeEditText = findViewById(R.id.numberThreeEditText);
        sumTextView = findViewById(R.id.sumTextView);

    }
}

Answer:

Use TextWatcher. It will solve your problem:

editText.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

       if(s.toString().trim().length()==0){
            btn.setEnabled(false);
          } else {
            btn.setEnabled(true);
          }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
    }
});

Question:

So I've been working on a small app for myself, as I realized using Microsoft Word to keep track of all the college courses I've completed towards my degree wasn't ideal. So I figured, why not make that my first app? It's simple, and it's doable for someone with no app experience like myself.

So, this was my initial idea, it's nothing special, just some EditText fields along with a CheckBox to mark each course complete. Note, there are actually seven of these, all wrapped in a "ScrollView".

Then I had a different idea. Instead of having a set amount of courses and credits EditTexts and a CheckBox, I'd rather just have a button to "Add A Course". My problem is, I'm not sure how I would achieve this. I'm still fairly new to programming, only taken two Java classes so far.

Here is my code for my "MainActivity.java":

package exporian.collegetracker;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onCheckBoxChecked(View v) {
        final EditText course1 = (EditText) findViewById(R.id.course1);
        final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
        final EditText credits1 = (EditText) findViewById(R.id.credits1);
        final EditText course2 = (EditText) findViewById(R.id.course2);
        final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
        final EditText credits2 = (EditText) findViewById(R.id.credits2);
        final EditText course3 = (EditText) findViewById(R.id.course3);
        final CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
        final EditText credits3 = (EditText) findViewById(R.id.credits3);
        final EditText course4 = (EditText) findViewById(R.id.course4);
        final CheckBox checkBox4 = (CheckBox) findViewById(R.id.checkBox4);
        final EditText credits4 = (EditText) findViewById(R.id.credits4);
        final EditText course5 = (EditText) findViewById(R.id.course5);
        final CheckBox checkBox5 = (CheckBox) findViewById(R.id.checkBox5);
        final EditText credits5 = (EditText) findViewById(R.id.credits5);
        final EditText course6 = (EditText) findViewById(R.id.course6);
        final CheckBox checkBox6 = (CheckBox) findViewById(R.id.checkBox6);
        final EditText credits6 = (EditText) findViewById(R.id.credits6);
        final EditText course7 = (EditText) findViewById(R.id.course7);
        final CheckBox checkBox7 = (CheckBox) findViewById(R.id.checkBox7);
        final EditText credits7 = (EditText) findViewById(R.id.credits7);

        ArrayList<CheckBox> checkBoxes = new ArrayList<>();
        checkBoxes.add(checkBox1);
        checkBoxes.add(checkBox2);
        checkBoxes.add(checkBox3);
        checkBoxes.add(checkBox4);
        checkBoxes.add(checkBox5);
        checkBoxes.add(checkBox6);
        checkBoxes.add(checkBox7);

        ArrayList<EditText> courses = new ArrayList<>();
        courses.add(course1);
        courses.add(course2);
        courses.add(course3);
        courses.add(course4);
        courses.add(course5);
        courses.add(course6);
        courses.add(course7);

        ArrayList<EditText> credits = new ArrayList<>();
        credits.add(credits1);
        credits.add(credits2);
        credits.add(credits3);
        credits.add(credits4);
        credits.add(credits5);
        credits.add(credits6);
        credits.add(credits7);

        int numOfCheckBoxes = 7;
        for (int i = 0; i < numOfCheckBoxes; i++) {
            if (checkBoxes.get(i).isChecked()) {
                courses.get(i).setEnabled(false);
                courses.get(i).setFocusable(false);
                courses.get(i).setInputType(InputType.TYPE_NULL);
                credits.get(i).setEnabled(false);
                credits.get(i).setFocusable(false);
                credits.get(i).setInputType(InputType.TYPE_NULL);
            } else {
                courses.get(i).setEnabled(true);
                courses.get(i).setFocusable(true);
                courses.get(i).setFocusableInTouchMode(true);
                courses.get(i).setInputType(InputType.TYPE_CLASS_TEXT);
                credits.get(i).setEnabled(true);
                credits.get(i).setFocusableInTouchMode(true);
                credits.get(i).setFocusable(true);
                credits.get(i).setInputType(InputType.TYPE_CLASS_NUMBER);
            } // End of if else
        } // End of for loop
    } // End of onCheckBoxChecked
} // End of MainActivity

I realize I've probably gone about this a very "noobish" way, and my code could probably be a lot cleaner, but I'm still fairly new to Java and even newer to Android, so please bear with me.

The biggest thing that I am stuck on is instantiating the EditTexts and CheckBox. How would I go about that? I figured, for my "numOfCheckBoxes" I would just add 1 to it every time the "Add A Course" button is clicked, so the for loop would still work correctly, but how would I create the id's for each new EditText and CheckBox, such as "course1", "course2, "course3", etc.

P.S. I'm not looking for someone to make the app for me, or for everything to be handed to me, just some insight from someone more experienced than me, thank you all in advance!


Answer:

Hi first of all you have to create your own class that extends linear layout with horizontal orientation and add to it your sub-views (edit text , text text , check box ), this will allow you to create 1 instance of your view that contains all of the 3 views .

For example :

public class MySingleLineInList extends LinearLayout {

public MySingleLineInList(Context context) {
    super(context);

      setOrientation(LinearLayout.HORIZONTAL);

      EditText courseET = new EditText(context);
      EditText creditsET = new EditText(context);
      CheckBox complteCB = new CheckBox(context);

      addView(courseET);
      addView(creditsET);
      addView(complteCB);
}
}

Then you must use ListView(which is also including scroll) with listview adapter for showing your views(MySingleLineInList), and on button click you can add more views to this list :

ListView myListView = new ListView(context);

MyListArrayAdaptapter myAdapter = new MyListArrayAdaptapter(context);

myListView.setAdapter(myAdapter);



public class MyListArrayAdaptapter extends ArrayAdapter<MySingleLineInList> {

    public MyListArrayAdaptapter(Context context){
          super(context, android.R.layout.simple_spinner_item);
    }

    public void addViewToList(MySingleLineInList l){
        add(l);
        notifyDataSetChanged();
    }
}

Then on button click just use :

Button b = new Button(context);
      b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            myAdapter.addViewToList(new MySingleLineInList());

        }
    });

Please note this is only the concept of doing it , for more information about list view and how it works please read here :

http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=92

Or just google for custom listview.

  • about the id's thing you can set id to any view in android for later use, for example :

      MySingleLineInList demo = new MySingleLineInList(context);
      demo.setId(1);
    
    
      int thisCourseId  = demo.getId();
    

Question:

I am building an app where you can upload images to my company server

My problem is that I have a login screen with Email, Password and Client ID(in LoginActivity)

Now The data you enter there is passed to another Activity(CameraActivity) and that is used to build a URL with Uri.Builder. The data is being saved within the edittext boxes BUT it is only being passed(using intents) to the other activity on the button click so, you have to go back to the login screen and click the button to reSubmit the data for every upload and everytime you start the app(The Data is stored within the textboxes but it is not being passed to the other activity without the button click), for the URI.Builder to work and give the entered information to the URL.

I want the client to enter that information ONCE and click the Button ONCE and then it is stored and used everytime regardless of the app being exited etc.

Login Activity, This activity has the edittext boxes and the entered information is being saved but not passed to the other activity without the button click

  public class LoginActivity extends AppCompatActivity {
String ID = "id";
String EMAIL = "email";
String PASS = "pass";
private SharedPreferences mPreference;
EditText email, password, id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    email=findViewById(R.id.emailtext);
    password=findViewById(R.id.pwdtext);
    id=findViewById(R.id.clientid);
    Button loginBtn=findViewById(R.id.button);

    mPreference = PreferenceManager.getDefaultSharedPreferences(this);

    id.setText(mPreference.getString(ID, ""));
    email.setText(mPreference.getString(EMAIL, ""));
    password.setText(mPreference.getString(PASS, ""));

    loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           EMAIL =email.getText().toString();
         PASS =password.getText().toString();
          ID =id.getText().toString();

            mPreference.edit().putString(ID,ID).apply();
            mPreference.edit().putString(EMAIL, EMAIL).apply();
            mPreference.edit().putString(PASS, PASS).apply();

            Intent intent=new Intent(LoginActivity.this,
                    CameraActivity.class);
            intent.putExtra("clientId", ID);
            intent.putExtra("email", EMAIL);
            intent.putExtra("password", PASS);
            startActivity(intent);
            }
        });
    }
}

Answer:

As suggested in the question comment, SharedPreferences is a good option.

SharedPreferences getPreferences(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context);
}

void setEmail(Context context, String email) {
    SharedPreferences.Editor editor = getPreferences(context).edit();
    editor.putString("EMAIL", email);
    editor.apply();
}

String getEmail(Context context) {
    return getPreferences(context).getString("EMAIL", "");
}

Above is an example of how you can put things and retrieve things from the shared preferences. Since you have more than an email to store (user ID, etc...) you could even store an object as a gson so you would have to call only one function. But of course this is your call.

Question:

I am making a budget app and each time the user enters a new expense, I just append a TextView. I need to add each expense together, but I'm not sure how to do this on each click.

First, I thought to simply add all the numbers from the TextView, but I couldn't find a way to do this since they're all in just one TextView (as opposed to creating a new TextView on each click). So, I decided to simply parse the expense each time the user types it then add them together. But how can I add them after parsing in this way?

Thanks so much for the help

 addExpenseButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //TODO: Transfer this info to line in scroll view showing expenses
                if (TextUtils.isEmpty(enterExpensesEditText.getText()) || TextUtils.isEmpty(enterExpensesNamesEditText.getText())) {
                    Toast.makeText(Expenses.this, "Expense Amount or Name Empty", Toast.LENGTH_SHORT).show();
                } else {
                    String income = enterExpensesEditText.getText().toString() + "\n";
                    String incomeName = enterExpensesNamesEditText.getText().toString() + "\n";
                    expenseAmountTextView.append(income);
                    expenseNameTextView.append(incomeName);
                    //parse income to double in order to add it and later feed to EverydayBudget
                    totalIncome = Double.parseDouble(income);
                }
                enterExpensesNamesEditText.setText("");
                enterExpensesEditText.setText("");

            }
        });

Answer:

You parse only the current expense : totalIncome = Double.parseDouble(income);

maybe replace by totalIncome += Double.parseDouble(income);

Sorry guys but i don't understand your question where is the problem ? you append your textview when you have a new expense no ?

And why not use a ListView rather TextView ?

Question:

I am designing a registration form where I have one EditText field for Categories. This list of categories is opened as a radio group in separate Popup activity when we click in EditText field. It is working fine till popup. However, I am not able to get the value back in the EditText field after selecting the RadioButton in the Popup activity.

Activity.java

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import java.security.PublicKey;

public class Industry extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_industry );

        DisplayMetrics dm = new DisplayMetrics ();
        getWindowManager ().getDefaultDisplay ().getMetrics ( dm );

        int width = dm.widthPixels;
        int height = dm.heightPixels;

        getWindow ().setLayout ( (int)(width*.9),(int)(height*.85) );

        WindowManager.LayoutParams params = getWindow ().getAttributes ();
        params.gravity = Gravity.CENTER;
        params.x = 0;
        params.y = -20;

        getWindow ().setAttributes ( params );



    }

}

.XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Industry">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RadioGroup
            android:id="@+id/rbtnGroupIndus"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RadioButton
                android:id="@+id/rdbtnind1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Agriculture And Allied Industries"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Automobiles"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Auto Components"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Aviation"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Banking"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind6"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Cement"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind7"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Consumer Durables"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind8"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Ecommerce"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind9"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Education And Training"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind10"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Engineering And Capital Goods"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind11"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Financial Services"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind12"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Fmcg"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind13"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Gems And Jewellery"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind14"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Healthcare"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind15"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Infrastructure"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind16"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Insurance"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind17"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="It / Ites"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind18"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Manufacturing"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind19"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Media And Entertainment"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind20"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Metals And Mining"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind21"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Oil And Gas"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind22"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Pharmaceuticals"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind23"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Ports"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind24"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Power"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind25"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Railways"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind26"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Real Estate"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind27"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Renewable Energy"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind28"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Retail"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind29"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Roads"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind30"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Science And Technology"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind31"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Services"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind32"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Steel"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind33"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Telecommunications"
                android:onClick="selectID"
                />
            <RadioButton
                android:id="@+id/rdbtnind35"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tourism And Hospitality"
                android:onClick="selectID"
                />

        </RadioGroup>

    </ScrollView>


</android.support.constraint.ConstraintLayout>

Answer:

You can simply try with using SharedPreference object.... save the data in your sharedpreference object on Radio Button Click and get data from sharedpreference where you want.

If you share the code I can help more.

Question:

Can't seem to find a post/video on the net that explains adding new EditText fields with a button. I need to use the edittexts later. Can someone please explain to me how to create this system? Or link a video/post that explains this. I've been searching for a long time but I still haven't found a good explanation. Thanks.


Answer:

Button mButton = (Button) findViewById(R.id.my_button);
mButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        EditText t = new EditText(myContext);
        t.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        root.addView(t);
    } 
});

root: is the root layout where you want to add the EditText.

Question:

I'm relatively new to java and new to android studio, so any explanation would be greatly appreciated.

I want to create an app that allows the user to enter someones name and assign them to one of two teams. I am at the point where the user can add one name to each team but I am unsure how to add multiple names to each team.

In my XML I have a EditText field to enter the name, two buttons to put them in Team 1 or Team 2 and two TextViews to display all the people in each team.

    <EditText
        android:layout_width="106dp"
        android:layout_height="wrap_content"
        android:id="@+id/NameText"/>

    <Button
        android:id="@+id/Team1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Team 1"/>

    <Button
        android:id="@+id/Team2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Team 2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/team1_person1"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/team1_person2"
        android:layout_column="1"/>

Here is my java code, I have set each button to add the name entered to the TextView for team 1 or team 2, depending on what button was selected.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button t1button = (Button) findViewById(R.id.Team1);
        Button t2button = (Button) findViewById(R.id.Team2);


        t1button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // --- find the text view --
                EditText inputText = (EditText) findViewById(R.id.NameText);
                String str = inputText.getText().toString();
                TextView newText = (TextView) findViewById(R.id.team1_person1);
                newText.setText( str);
            }
        });

        t2button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // --- find the text view --
                EditText inputText = (EditText) findViewById(R.id.NameText);
                String str = inputText.getText().toString();
                TextView newText = (TextView) findViewById(R.id.team1_person2);
                newText.setText( str);
            }
        });



    }
}


I know I'll need to add more TextViews for each new name, but I'm not sure how this works with only one button. 
Thanks

Answer:

Easy way to implement this is to dynamically create a new Textview whenever each of the buttons is clicked

First of all, you might need to create two LinearLayout for each team.

And onClick method should be changed like this code.

TextView textView = new TextView(this); // create a new textview
textView.setText(inputText.getText().toString());
myLinearLayout.addView(textView); // add the textview to the linearlayout

Then it will be added to each layout dynamically when you click the button.

Question:

My app is taking a number input from an EditText when user presses "OKAY" button. Then some EditTexts are created based on that input number. But when user rotates the screen the newly/dynamically created EditTexts get removed which I want to be saved when user rotates the screen.

I used onSaveInstanceState() and onRestoreInstanceState() to save the EditTexts' state but it didn't work(app crashes on phone rotation). May be, I couldn't use these methods in a right way.

I am giving my xml and java code:

My xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enter No of EditText:"
        android:textSize="24sp"
        android:textColor="@color/colorPrimaryDark"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edtNoCreate"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="No of EditText"
            android:inputType="number"/>

        <Button
            android:id="@+id/btnCreate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OKAY"/>

    </LinearLayout>


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:background="#EDE9E9">

        <LinearLayout
            android:id="@+id/lnrDynamicEditTextHolder"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        </LinearLayout>

    </ScrollView>


</LinearLayout>

My java code:

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import java.util.*;
import static java.lang.Integer.parseInt;

public class MainActivity extends AppCompatActivity {

    private LinearLayout lnrDynamicEditTextHolder;
    private EditText edtNoCreate;
    private Button btnCreate;

    List<EditText> allEditText = new ArrayList<EditText>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lnrDynamicEditTextHolder = (LinearLayout) findViewById(R.id.lnrDynamicEditTextHolder);
        btnCreate = (Button) findViewById(R.id.btnCreate);
        edtNoCreate = (EditText) findViewById(R.id.edtNoCreate);

        btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    if(edtNoCreate.getText().toString().length()>0 && parseInt(edtNoCreate.getText().toString())!=0) {
                        if(edtNoCreate.getText().toString().length()==0){
                            edtNoCreate.setError("This Item Cannot be Empty");
                            return;
                        }
                        allEditText.clear();
                        lnrDynamicEditTextHolder.removeAllViews();

                        int length = parseInt(edtNoCreate.getText().toString());

                        for (int i=0;i<length;i++){
                            EditText editText = new EditText(MainActivity.this);
                            editText.setId(i+1);
                            editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            allEditText.add(editText);
                            lnrDynamicEditTextHolder.addView(editText);
                        }
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                    edtNoCreate.setError("This Item Cannot be Empty");
                }
            }
        });
    }


    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);

        int mViewsCount = 0;
        for(EditText view : allEditText)
        {
            savedInstanceState.putInt("mViewId_" + mViewsCount, view.getId());
            mViewsCount++;
        }

        savedInstanceState.putInt("mViewsCount", mViewsCount);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        int mViewsCount = savedInstanceState.getInt("mViewsCount");;
        for(int i = 0; i <= mViewsCount; i++)
        {
            EditText view = allEditText.get(i);

            int viewId = savedInstanceState.getInt("mViewId_" + i);
            view.setId(viewId);

            mViewsCount++;
        }
    }
}


Answer:

Both of the existing answers using ViewModels and manually handling the configChange do help.

However personally I would be cautious with setting the configChanges in the manifest. Even the documentation warns:

Caution: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

Using a ViewModel would really be a great way for general handling of orientation change. However one could argue that it does not fit well in your scenario since you are dynamically creating Views and the ViewModel should not know about those Views.

Anyway here is how I would handle it in your situation:

  • First of all save the id's of your EditText's in an ArrayList<Int>
  • When adding a new EditText just set your id to your id-List's size and add an element to the list with the value of it's size
  • Then in onSaveInstanceState add those id's to your savedInstanceState Bundle (using the putIntegerArrayList function so you don't have to save each id seperately)
  • In onCreate just check if savedInstanceState is null or not
  • If savedInstanceState is not null, get the id's from it and iterate over them creating an EditText for with each id (just like you would on a button press)
  • That's all there is to it :)

Just as a tiny background information: When rotating the device, the Activity gets recreated which means all programmatically added Views are "gone" (since the layout is inflated again). But if you add those Views with their respective id again, the state is preserved.

Enough talking here is the code:

public class MainActivity extends AppCompatActivity {

    private LinearLayout lnrDynamicEditTextHolder;
    private EditText edtNoCreate;
    private Button btnCreate;
    private static final String KEY_IDS = "IDS";

    List<EditText> allEditText = new ArrayList<EditText>();
    ArrayList<Integer> allIds = new ArrayList<Integer>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lnrDynamicEditTextHolder = (LinearLayout) findViewById(R.id.lnrDynamicEditTextHolder);
        btnCreate = (Button) findViewById(R.id.btnCreate);
        edtNoCreate = (EditText) findViewById(R.id.edtNoCreate);

        if (savedInstanceState != null) {
            allIds = savedInstanceState.getIntegerArrayList(KEY_IDS)

            for (int i=0;i<allIds.size();i++){
                EditText editText = new EditText(MainActivity.this);
                editText.setId(allIds.get(i));
                editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                allEditText.add(editText);
                lnrDynamicEditTextHolder.addView(editText);
            }
        }

        btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    if(edtNoCreate.getText().toString().length()>0 && parseInt(edtNoCreate.getText().toString())!=0) {
                        if(edtNoCreate.getText().toString().length()==0){
                            edtNoCreate.setError("This Item Cannot be Empty");
                            return;
                        }
                        allEditText.clear();
                        lnrDynamicEditTextHolder.removeAllViews();

                        int length = parseInt(edtNoCreate.getText().toString());

                        for (int i=0;i<length;i++){
                            EditText editText = new EditText(MainActivity.this);
                            editText.setId(allIds.size());
                            allIds.add(allIds.size());
                            editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            allEditText.add(editText);
                            lnrDynamicEditTextHolder.addView(editText);
                        }
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                    edtNoCreate.setError("This Item Cannot be Empty");
                }
            }
        });
    }


    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putIntegerArrayList(KEY_IDS, allIds);
    }
}

Question:

I want to use One Button as backspace for 2 seperate Edit Text I mean when focus on the (edit text) can i use the button on it.....

I can't use if statement with it (i am new on android developing)

This is my code

        bak.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             if (et1.hasFocus()) {
              }
            String str = et1.getText().toString();
            if (str.length() > 1) {
                str = str.substring(0, str.length() - 1);
                et1.setText(str);
            } else if (str.length() <= 1) {
                et1.setText("");
            }
        }

    });
    bak.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (et2.hasFocus()){
             }
            String str2 = et2.getText().toString();
            if (str2.length() > 1) {
                str2 = str2.substring(0, str2.length() - 1);
                et2.setText(str2);
            } else if (str2.length() <= 1) {
                et2.setText("");
            }
        }
    });

but my another code for for another button work fine (why?)

   BT9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (et2.hasFocus()) {
                et2.append("9");
            }
            if (et1.hasFocus()) {
                et1.append("9");
            }
            if (ans.hasFocus()) {
                ans.append("9");
            }

        }
    });

Answer:

The problem in your code is that you are setting OnClickListener on same button two times. The second OnClickListener will overwrite first one. So we need to do it in single OnClickListener. Pls try below code

 bak.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText focusEditText=et1;
            if (et1.hasFocus()) {
                focusEditText=et1;
            }
            if (et2.hasFocus()){
                focusEditText=et2;
            }
            String str = focusEditText.getText().toString();
            if (str.length() > 1) {
                str = str.substring(0, str.length() - 1);
                focusEditText.setText(str);
            } else if (str.length() <= 1) {
                focusEditText.setText("");
            }
        }

    });

Question:

**I have used four radio buttons for adding and subtraction the amount in the wallet. whenever i open the app it crashes .Whenever i open the app it crashes i don't what is error please someone help me. i am new to android. In this app i have used four radio buttons for add the amount and subtracting the amount. **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/form"
    tools:context="com.sivaneshsg.wallet.MainActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Amount"
        android:textSize="25sp"
        android:textStyle="italic"
        android:textColor="@android:color/black"
        android:paddingTop="5dp"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"/>
    <EditText
        android:id="@+id/inputamount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Amount in Rs."
        android:paddingTop="5dp"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:inputType="number"
        android:ems="10"
        />
    <RadioGroup
        android:id="@+id/rgroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp"

        >
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Income"
        android:textStyle="italic"
            android:textSize="20sp"
        android:textColor="@android:color/black"
            android:paddingBottom="10dp"/>
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    <RadioButton
                android:id="@+id/cash1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Cash"
                android:textSize="15dp"
                android:paddingRight="10dp"

        android:textColor="@android:color/black"
                />
    <RadioButton
                android:id="@+id/card1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Card"

        android:textColor="@android:color/black"
                />
        </LinearLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Expense"
            android:textSize="20dp"
            android:textStyle="italic"
            android:textColor="@android:color/black"
            android:paddingBottom="10dp"/>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <RadioButton
                android:id="@+id/cash2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Cash"
                android:textColor="@android:color/black"
                android:textSize="15sp"

                android:paddingRight="10dp"
                />

    <RadioButton
        android:id="@+id/card2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Card"
        android:textSize="15sp"

        android:textColor="@android:color/black"
        />
        </LinearLayout>
        </RadioGroup>
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OK"

        />


    <TextView
        android:id="@+id/amountcard"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:text="Amount in Card : RS. 0"
        android:textSize="25sp"
        android:padding="10dp"/>
    <TextView
        android:id="@+id/amountcash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Amount in Cash : Rs. 0"
        android:textSize="25sp"
        android:textColor="@android:color/black"
        android:padding="10dp"/>
    <TextView
        android:id="@+id/amountwallet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Total Amount in Wallet : RS. 0"
        android:textSize="23sp"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:padding="10dp"/>

</LinearLayout> 









 package com.sivaneshsg.wallet;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

public class MainActivity extends AppCompatActivity {

    int cashamount = 0;
    int cardamount = 0;
    int totalamount;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        EditText et = (EditText) findViewById(R.id.inputamount);
        final int amount = Integer.parseInt(et.getText().toString());
        RadioGroup rg = (RadioGroup) findViewById(R.id.rgroup);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.card1) {
                    cardamount = cardamount + amount;
                } else if (checkedId == R.id.cash1) {
                    cashamount = cashamount + amount;
                } else if (checkedId == R.id.cash2) {
                    cashamount = cashamount - amount;
                } else if (checkedId == R.id.card2) {
                    cardamount = cardamount - amount;
                }

            }
        });
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView cash = (TextView) findViewById(R.id.amountcash);
                TextView card = (TextView) findViewById(R.id.amountcard);
                TextView wallet = (TextView) findViewById(R.id.amountwallet);
                cash.setText("Amount in Cash : RS. " + cashamount);
                card.setText("Amount in Card : RS. " + cardamount);
                totalamount = cashamount + cashamount;
                wallet.setText("Total Amount in Wallet : RS. " + totalamount);

            }
        });
    }
}

**Whenever i open the app it crashes i don't what is error please someone help me. i am new to android. In this app i have used four radio buttons for add the amount and subtracting the amount. ** 

Answer:

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;


public class teste extends AppCompatActivity {

int cashamount = 0;
int cardamount = 0;
int totalamount;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.iuiu);


    EditText et = (EditText) findViewById(R.id.inputamount);
    final String amount = (et.getText().toString());
    RadioGroup rg = (RadioGroup) findViewById(R.id.rgroup);
    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.card1) {
                cardamount = Integer.parseInt(cardamount + amount);
            } else if (checkedId == R.id.cash1) {
                cashamount = Integer.parseInt(cashamount + amount);
            } else if (checkedId == R.id.cash2) {
                cashamount -= Integer.parseInt(amount);
            } else if (checkedId == R.id.card2) {
              cardamount -= Integer.parseInt(amount);
            }

        }
    });
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView cash = (TextView) findViewById(R.id.amountcash);
            TextView card = (TextView) findViewById(R.id.amountcard);
            TextView wallet = (TextView) findViewById(R.id.amountwallet);
            cash.setText("Amount in Cash : RS. " + cashamount);
            card.setText("Amount in Card : RS. " + cardamount);
            totalamount = cashamount + cashamount;
            wallet.setText("Total Amount in Wallet : RS. " + totalamount);

        }
    });
}

}

try the above code your problem was here

 final int amount = Integer.parseInt(et.getText().toString());

Question:

Could anyone tell me why my button isn't disabled when the text in the edittext is empty? I've tried to do this so many ways but it never works! This is the simplified code I have at the minute.

Code:

public class MapStartActivity extends FragmentActivity {

    EditText mapName;
    Button NextPageStart;


    private TextWatcher textWatcher = 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) {
            checkFieldsForEmptyValues();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    private void checkFieldsForEmptyValues(){
        String s1 = mapName.getText().toString();

        if (s1.trim().isEmpty()) {
            NextPageStart.setEnabled(true);
        } else {
            NextPageStart.setEnabled(false);
            NextPageStart.setAlpha(.5f);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_start);

        NextPageStart = (Button) findViewById(R.id.NextStatLocBut);
        mapName = (EditText) findViewById(R.id.MapNameText);


        //Click Listener for button
        NextPageStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mapName.addTextChangedListener(textWatcher);

            }
        });
    }
}

Answer:

Add text watcher outside click listener like this

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_start);

        NextPageStart = (Button) findViewById(R.id.NextStatLocBut);
        mapName = (EditText) findViewById(R.id.MapNameText);

        // To disable the button intially
        NextPageStart.setEnabled(false);

        mapName.addTextChangedListener(textWatcher);

        //Click Listener for button
        NextPageStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // You can do some click action here

            }
        });
    }

Question:

I am creating a simple calculator that has 5 buttons, 2 edit texts and a textview, the user inputs a value for number1 then number 2 then presses eithor, add, subtract, multiply, divide or clear. The value is then shown in the textview. How can I get the clear button to remove the values for num1 and num 2? Here is what I have,

package com.example.moiz_.calculator;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

TextView result;
EditText number1, number2;
Button add, subtract, divide, multiply, Clear;
float result_num;
float num1, num2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    result = (TextView) findViewById(R.id.Result);

    number1 = (EditText) findViewById(R.id.Number1);
    number2 = (EditText) findViewById(R.id.Number2);

    add = (Button) findViewById(R.id.Sum);
    subtract = (Button) findViewById(R.id.Subtract);
    divide = (Button) findViewById(R.id.Divide);
    multiply = (Button) findViewById(R.id.Multiply);
    Clear = (Button) findViewById(R.id.Clear);

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num1 = Integer.parseInt(number1.getText().toString());
            num2 = Integer.parseInt(number2.getText().toString());

            result_num = num1 + num2;
            result.setText(String.valueOf(result_num));

        }
    });

    subtract.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num1 = Integer.parseInt(number1.getText().toString());
            num2 = Integer.parseInt(number2.getText().toString());

            result_num = num1 - num2;
            result.setText(String.valueOf(result_num));
        }
    });

    divide.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num1 = Integer.parseInt(number1.getText().toString());
            num2 = Integer.parseInt(number2.getText().toString());

            result_num = num1 / num2;

            result.setText(String.valueOf(result_num));
        }
    });

    multiply.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num1 = Integer.parseInt(number1.getText().toString());
            num2 = Integer.parseInt(number2.getText().toString());

            result_num = num1 * num2;
            result.setText(String.valueOf(result_num));
        }
    });

    Clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num1 = Integer.parseInt(number1.getText().toString());
            num2 = Integer.parseInt(number2.getText().toString());


            result.setText("0");
        }
    });


}

}

Answer:

Make an on click listener for the clear button and in the function write

number1.setText("0")

and same for number 2

Question:

I created a class for font named Myfont its working fine on TextView but it's not working in EditText and Button. here is my xml code <mypackagename.Myfont android:id="@+id/input_password" android:hint="@string/hint_email" />


Answer:

This is the way to set the font programmatically:

Edittext et = (Edittext) findViewById(R.id.appname); Typeface face = Typeface.createFromAsset(getAssets(),"fonts/epimodem.ttf"); et.setTypeface(face);

you can also change font of textview and button by this way.

Question:

I'm a newbie guy learning android programming to help be more efficient at work. I have a very simple problem that I think should have a simple answer, I just can't find anything that works in my searching of eddittext, listener and edittext to variable.

Basically I have a Edittext field that should be updated by pressing a + or - button or by userinput. I need that edittext field put into a variable so that I can use it in a calculation. I want the calculation to occur after I hit either the + or - button and after (maybe during if it is easier) the user entering the text.

At the moment when I press the + or - button the resulting edit text is based on my int variable fuel but completely ignores the user input (because I can't get that user input to update my fuel variable).

What I need is. 1) The fuel variable to update based on user input so that when a subsequent + or - button is pressed the fuel variable is adjusted relative the the user input. i.e. send the user input to the fuel variable.

fuel is a global int variable. fuelCalc is a method where I plan to do some calculations based on the fuel variable.

Here is an excerpt of my code:

The XML:

              <EditText
                android:id="@+id/Fuel_load_field"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:hint="Fuel Load"
                android:inputType="number"
                android:imeOptions="actionDone"
                android:maxLength="5"
                android:textSize="16sp"/>

            <Button
                android:layout_width="64dp"
                android:layout_height="match_parent"
                android:text="+"
                android:textAllCaps="true"
                android:onClick="addOneHundredtoFuel"
                android:textSize="16sp" />

            <Button
                android:layout_width="64dp"
                android:layout_height="match_parent"
                android:text="-"
                android:textAllCaps="true"
                android:onClick="subtractOneHundredtoFuel"
                android:textSize="16sp" />

Here is the java:

public void addOneHundredtoFuel(View view) {

        fuel = fuel + 100;

        TextView fuelField = (TextView) findViewById(R.id.Fuel_load_field);
        fuelField.setText(String.valueOf(fuel));
        fuelCal(fuel);
    }

    public void subtractOneHundredtoFuel(View view) {

        fuel = fuel - 100;


        TextView fuelField = (TextView) findViewById(R.id.Fuel_load_field);
        fuelField.setText(String.valueOf(fuel));

        fuelCal(fuel);
    }

    public void fieldEntryFuel(View view) {

        EditText inputText = (EditText) findViewById(R.id.Fuel_load_field);
        String fuelString = inputText.getText().toString();

        fuel = Integer.parseInt(fuelString);


        TextView fuelField = (TextView) findViewById(R.id.Fuel_load_field);
        fuelField.setText(String.valueOf(fuel));

        fuelCal(fuel);

    }

Thanks for the help.

Airfix


Answer:

I'm not 100% sure that I understand your question... You want a variable to be updated as the user enters text into an EditText, correct? If so, you probably want to just out TextWatcher; it does exactly what you are looking to do if I understand correctly.

Example:

private final TextWatcher fuelWatcher = new TextWatcher(){
    EditText fuelLoadField = (EditText)findViewById(R.id.Fuel_load_field);

    @Override
    afterTextChanged(Editable s){
        fuel =  = Integer.parseInt(fuelLoadField.getText());
    }
}

Make sure you register that listener to your EditText object in your onCreate() by calling fuelField.addTextChangedListener(fuelWatcher);

Question:

I am learning the basics about Android programming.

I followed an online class and created this.

It's a very simple application and I am stuck in opening a new activity, after clicking on a button.

The error my emulator returns is "Unfortunately, JogoNumeros has stopped"

My code is the following:

MainActivity.java:

package com.example.carneiro.jogonumeros;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

MainActivityFragment.java:

package com.example.carneiro.jogonumeros;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        Button btnNumberGuessGame = (Button) rootView.findViewById(R.id.btnNumberGuessGame);

        btnNumberGuessGame.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), NumberGuessGame.class);
                getActivity().startActivity(intent);
            }
        });
        return rootView;
    }
}

NumberGuessGame.java:

package com.example.carneiro.jogonumeros;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;


public class NumberGuessGame extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number_guess_game);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_number_guess_game, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

NumberGuessGameFragment.java:

package com.example.carneiro.jogonumeros;

import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.AlertDialog;

public class NumberGuessGameFragment extends Fragment {

    Button btnNew = null;
    Button btnGuess = null;
    EditText inputGuess = null;
    TextView textMessage = null;
    Integer tentativas = 0;

    boolean gameFinished = false;
    int secretNumber = 0;

    public NumberGuessGameFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView =inflater.inflate(R.layout.fragment_number_guess_game, container, false);

        btnNew = (Button) rootView.findViewById(R.id.btnNew);

        btnNew.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View view) {
                actionNewGame();
            }
        });

        btnGuess = (Button) rootView.findViewById(R.id.btnGuess);

        btnGuess.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View view) {
                processGuess();
            }
        });

        inputGuess = (EditText) rootView.findViewById(R.id.inputGuess);

        textMessage = (TextView) rootView.findViewById(R.id.textMessage);

        newGame();
        return rootView;
    }

    private void processGuess(){
        String strGuess = inputGuess.getText().toString();
        inputGuess.setText("");
        if (strGuess.length() == 0)
            return;

        int guess = Integer.valueOf(strGuess);

        if (guess > secretNumber) {
            textMessage.setText(R.string.message_is_smaller);
            tentativas++;
        } else if (guess < secretNumber){
            textMessage.setText(R.string.message_is_bigger);
            tentativas++;
        } else {
            tentativas++;
            textMessage.setText(R.string.message_right_1 + tentativas + R.string.message_right_2);
            gameFinished = true;
        }

    }

    private void actionNewGame(){
        if (gameFinished) {
            newGame();
            return;
        }

        new AlertDialog.Builder(getActivity())
                .setMessage(R.string.confirm_new_game)
                .setCancelable(false)
                .setNegativeButton(R.string.nao, null)
                .setPositiveButton(R.string.sim, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        NumberGuessGameFragment.this.newGame();
                    }
                });
    }

    private void newGame(){
        secretNumber = (int) (Math.random() * 100);
        textMessage.setText("");
        gameFinished = false;

    }

}

logcat / errors:

09-14 15:45:57.802    4570-4570/com.example.carneiro.jogonumeros I/art﹕ Not late-enabling -Xcheck:jni (already on)
09-14 15:45:57.802    4570-4570/com.example.carneiro.jogonumeros I/art﹕ Late-enabling JIT
09-14 15:45:57.806    4570-4570/com.example.carneiro.jogonumeros I/art﹕ JIT created with code_cache_capacity=2MB compile_threshold=1000
09-14 15:45:57.858    4570-4570/com.example.carneiro.jogonumeros W/System﹕ ClassLoader referenced unknown path: /data/app/com.example.carneiro.jogonumeros-2/lib/x86
09-14 15:45:58.058    4570-4585/com.example.carneiro.jogonumeros D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
09-14 15:45:58.068    4570-4570/com.example.carneiro.jogonumeros D/﹕ HostConnection::get() New Host Connection established 0xabdefcf0, tid 4570
09-14 15:45:58.188    4570-4585/com.example.carneiro.jogonumeros D/﹕ HostConnection::get() New Host Connection established 0xabdefe70, tid 4585
09-14 15:45:58.207    4570-4585/com.example.carneiro.jogonumeros I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-14 15:45:58.285    4570-4585/com.example.carneiro.jogonumeros W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-14 15:45:58.285    4570-4585/com.example.carneiro.jogonumeros W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xabebf180, error=EGL_SUCCESS

Then, clicking on button:

09-14 15:46:02.425    4570-4570/com.example.carneiro.jogonumeros D/AndroidRuntime﹕ Shutting down VM
09-14 15:46:02.425    4570-4570/com.example.carneiro.jogonumeros E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.carneiro.jogonumeros, PID: 4570
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.carneiro.jogonumeros/com.example.carneiro.jogonumeros.NumberGuessGame}: android.view.InflateException: Binary XML file line #1: Binary XML file line #1: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: android.view.InflateException: Binary XML file line #1: Binary XML file line #1: Error inflating class fragment
            at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
            at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
            at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
            at com.example.carneiro.jogonumeros.NumberGuessGame.onCreate(NumberGuessGame.java:14)
            at android.app.Activity.performCreate(Activity.java:6237)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
            at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
            at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
            at com.example.carneiro.jogonumeros.NumberGuessGame.onCreate(NumberGuessGame.java:14)
            at android.app.Activity.performCreate(Activity.java:6237)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText
            at com.example.carneiro.jogonumeros.NumberGuessGameFragment.onCreateView(NumberGuessGameFragment.java:55)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1185)
            at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1287)
            at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2243)
            at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
            at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:278)
            at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
            at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:78)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
            at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
            at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
            at com.example.carneiro.jogonumeros.NumberGuessGame.onCreate(NumberGuessGame.java:14)
            at android.app.Activity.performCreate(Activity.java:6237)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-14 15:46:04.425    4570-4570/com.example.carneiro.jogonumeros I/Process﹕ Sending signal. PID: 4570 SIG: 9

Answer:

Here's the error:

Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText

And here's what's causing it:

inputGuess = (EditText) rootView.findViewById(R.id.inputGuess);

Either modify the code so it's a TextView, or modify xml layout so the view is an EditText. Not sure which one suits you.

Question:

I have created dynamically edittext on my android application like below:

protected void onCreate(Bundle savedInstanceState) {

RelativeLayout layout = (RelativeLayout) findViewById(R.id.linearLayout1);
        final EditText[] Et = new EditText[10];
        int prevTextViewId = 0;
        int add = 0;
        int add1 = 0;
        for (int a = 0; a < Arr.length; a++) {

            Et[a] = new EditText(this);
            RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
                    (int) LayoutParams.WRAP_CONTENT,
                    (int) LayoutParams.WRAP_CONTENT);
            param.leftMargin = 25;
            param.topMargin = (a + 1) * (100 + add1);
            Et[a].setPadding(5, 23, 5, 5);
            Et[a].setLayoutParams(param);
            Et[a].setSingleLine(false);
            Et[a].setHorizontalScrollBarEnabled(false);
            Et[a].setWidth(280);
            Et[a].getText().toString();
            layout.addView(Et[a]);
            add = add + 25;
            add1 = add1 + 15;
        }
}

And I want to get text from dynamically created edittext into a button like below:

btn_doneAnswer = (Button) findViewById(R.id.btn_doneAnswer);
        btn_doneAnswer.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                   for (int a = 0; a < Arr.length; a++) {
                        Et[a] = new EditText(this);
                        String text += Et[a].getText().toString();
                    }
                    Bundle bundle = new Bundle();
                    Intent i_backToAddItem = new Intent(
                            AnswerActivityMultiText.this,
                            QuestionActivityDynamic.class);
                    bundle.putString("text", text);
                    bundle.putString("MultiQues", MultiQues);
                    i_backToAddItem.putExtras(bundle);
                    startActivity(i_backToAddItem);

            }
        });

But I am getting error below in the button onclick method at this line Et[a] = new EditText(this);:

The constructor EditText(new View.OnClickListener(){}) is undefined

another below error at this line += in the button onclick method:

Syntax error on token "+=", = expected

Kindly suggest me how I am getting text from dynamically created edittext into a button.

Waiting for reply.

Thanks


Answer:

you dont have to initialize the EditText again in the onClick. You should directly use the EditText object to get the text. So the line

Et[a] = new EditText(this);

is not required at all!

And for the error with '+=' operator, you are declaring the string and using the operator(+=) in one line. you have to split up the the declaration part out of the for loop and then use '+='. Here's the complete code :

btn_doneAnswer = (Button) findViewById(R.id.btn_doneAnswer);
    btn_doneAnswer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                String text;
               for (int a = 0; a < Arr.length; a++) {
                    text += Et[a].getText().toString();
                }
                Bundle bundle = new Bundle();
                Intent i_backToAddItem = new Intent(
                        AnswerActivityMultiText.this,
                        QuestionActivityDynamic.class);
                bundle.putString("text", text);
                bundle.putString("MultiQues", MultiQues);
                i_backToAddItem.putExtras(bundle);
                startActivity(i_backToAddItem);

        }
    });

Question:

In my android application, I have an edittext and below that there are two buttons. The first one is add button and another is send button. When user clicks on add button, then it should create another edittext just below the first one. This is fine if I have to create known number of edittexts and I can use for loop like this :

for(int i = 0; i < 20; i++) 
{
    Edittext et= new Edittext(this);
    ll.addView(et);
}

But the problem is if user clicks multiple times then it should be insert multiple edtitexts there which is unknown. Means user can click 100's or 200's or more times. So don't know exactly how many times user will click that add button. Can anybody please help me to how to do this..??


Answer:

It is simple. Add one click listener and your job done. Hope it will help you.

Button addButton= (Button) findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       Edittext et= new Edittext(your_activity_name.this); //Replace with your activity name
       ll.addView(et);
    }
});

Question:

i have five edittext fields which is checking the fields and restricts some data when entered wrong as shown below code but now if i enter wrong data in edittext then it will enter the information into database so i want to disable the button if there are errors in any edittext . The error might be in 1 to 5 edittext it has to disable the send button. It has to only enable the send button when there are no errors in the edittext fields

public class MaINActivity extends Activity {

    String result = null;
    InputStream is = null;
    String valid_email = null;
    String valid_name = null;
    String valid_last = null;
    String valid_age = null;
    String v5,v1,v2,v3,v4,v6;
    String valid_confirm = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_subscribe);

    final EditText editText = (EditText)findViewById(R.id.firstname);

    final EditText editText1 = (EditText)findViewById(R.id.lastname);

    final EditText editText2 = (EditText)findViewById(R.id.age1);

    final EditText editText3 = (EditText)findViewById(R.id.email);

    final EditText editText4 = (EditText)findViewById(R.id.confirm);

    editText2.addTextChangedListener(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) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            Is_Valid_Age(editText2);
        }

        private void Is_Valid_Age(EditText editText2) {

            if(editText2.length() == 0 || editText2.equals("") || editText2 == null || "".equals(editText2.getText().toString())) {
                valid_age = null;
            }else {
                valid_age = editText2.getText().toString();
            }
        }

    });
    editText1.addTextChangedListener(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) {


        }

        @Override
        public void afterTextChanged(Editable s) {
            Is_Valid_Last_Name(editText1);

        }

        private void Is_Valid_Last_Name(EditText editText1) throws NumberFormatException {

            if (editText1.getText().toString().length() <= 0) {
                editText1.setError("Accept Alphabets Only.");
                valid_last = null;
            } else if (!editText1.getText().toString().matches("[a-zA-Z ]+")) {
                editText1.setError("Accept Alphabets Only.");
                valid_last = null;
            } else if(editText1.length() == 0 || editText1.equals("") || editText1 == null || "".equals(editText1.getText().toString())) {
                valid_last = null;
            }else {
                valid_last = editText1.getText().toString();
            }

        }

    });

    editText.addTextChangedListener(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) {


        }

        @Override
        public void afterTextChanged(Editable s) {
            Is_Valid_First_Name(editText);

        }

        private void Is_Valid_First_Name(EditText editText) throws NumberFormatException {

            if (editText.getText().toString().length() <= 0) {
                editText.setError("Accept Alphabets Only.");
                valid_name = null;
            } else if (!editText.getText().toString().matches("[a-zA-Z ]+")) {
                editText.setError("Accept Alphabets Only.");
                valid_name = null;
            } else if(editText.length() == 0 || editText.equals("") || editText == null || "".equals(editText.getText().toString())) {
                valid_name = null;
            }else {
                valid_name = editText.getText().toString();
            }

        }
    }); 

    editText3.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            Is_Valid_Email_Address(editText3);
        }

        public void Is_Valid_Email_Address(EditText editText3) {
            if (editText3.getText().toString() == null) {
                editText3.setError("Invalid Email Address");
                valid_email = null;
            } else if (isEmailValid(editText3.getText().toString()) == false) {
                editText3.setError("Invalid Email Address");
                valid_email = null;
            } else if(editText3.length() == 0 || editText3.equals("") || editText3 == null || "".equals(editText3.getText().toString())) {
                valid_email = null;
            }else {
                valid_email = editText3.getText().toString();
            }
        }
    });

    editText4.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {


        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {


        }

        @Override
        public void afterTextChanged(Editable s) {

            Is_Valid_Confirm_Address(editText4);
        }


        public void Is_Valid_Confirm_Address(EditText editText4) {
            if (editText4.getText().toString() == null) {
                editText4.setError("Invalid Email Address");
                valid_confirm = null;
            } else if (isEmailValid(editText4.getText().toString()) == false) {
                editText4.setError("Invalid Email Address");
                valid_confirm = null;
            } else if (editText4.getText().toString().equals(editText3.getText().toString())) {

                valid_confirm = editText4.getText().toString();
            } else if(editText4.length() == 0 || editText4.equals("") || editText4 == null || "".equals(editText4.getText().toString())) {
                valid_confirm = null;
            } else {
                editText4.setError("Confirm Email is Not Matching");
                valid_confirm = null;
            } 

        }
    });

    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new View.OnClickListener(){

        @SuppressLint("NewApi")
        @Override
        public void onClick(View view) {

            v1 = editText.getText().toString();
            v2 = editText1.getText().toString();
            v3 = editText2.getText().toString();
            v4 = editText3.getText().toString();
            v5 = editText4.getText().toString();  


            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("firstname",v1));
            nameValuePairs.add(new BasicNameValuePair("lastname",v2));
            nameValuePairs.add(new BasicNameValuePair("age",v3));
            nameValuePairs.add(new BasicNameValuePair("email_address",v4));
            nameValuePairs.add(new BasicNameValuePair("confirm_email_address",v5));



            StrictMode.setThreadPolicy(policy);

            try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("localhost/Android/Insert.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

                Log.e("log_tag", "connection success ");
                Toast.makeText(getApplicationContext(), "Subscription Successfull.Thank You for Subscribing you have now been added to our Mailing Lists", Toast.LENGTH_LONG).show();
            }
            catch(Exception e)
            {
                Log.e("log_tag", "Error in http connection "+e.toString());
                Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
            }
            try
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) 
                {
                        sb.append(line + "\n");
                        Intent i = new Intent(getBaseContext(),SecondActivity.class);
                        startActivity(i);
                }
                is.close();

                result=sb.toString();
            }
            catch(Exception e)
            {
               Log.e("log_tag", "Error converting result "+e.toString());
            }
            try
            {   
                    JSONObject json_data = new JSONObject(result);
                    CharSequence w= (CharSequence) json_data.get("result");

                    Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();
            }
            catch(JSONException e)
            {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                    Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
            }
        }


    });

}

    private boolean isEmailValid(String email) {

        return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }}

Answer:

Try this way,hope this will help you to solve your problem.

activity_subscribe.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="5dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <EditText
                android:id="@+id/edtFirstName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="FirstName"
                android:layout_marginTop="5dp"/>

            <EditText
                android:id="@+id/edtLastName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="LastName"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtAge"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Age"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email"
                android:inputType="textEmailAddress"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Password"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtConfirmPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Confirm Password"
                android:layout_marginTop="5dp"/>
            </LinearLayout>
        </ScrollView>
    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"/>

</LinearLayout>

SubscribeActivty.java

public class SubscribeActivty extends Activity {

    InputStream is = null;
    private EditText edtFirstName;
    private EditText edtLastName;
    private EditText edtAge;
    private EditText edtEmail;
    private EditText edtPassword;
    private EditText edtConfirmPassword;
    private Button btnSubmit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subscribe);

        edtFirstName = (EditText) findViewById(R.id.edtFirstName);
        edtLastName = (EditText) findViewById(R.id.edtLastName);
        edtAge = (EditText) findViewById(R.id.edtAge);
        edtEmail = (EditText) findViewById(R.id.edtEmail);
        edtPassword = (EditText) findViewById(R.id.edtPassword);
        edtConfirmPassword = (EditText) findViewById(R.id.edtConfirmPassword);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        btnSubmit.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View view) {

                boolean isValid = true;
                if (edtFirstName.getText().toString().length() <= 0) {
                    edtFirstName.setError("Value  Required");
                    isValid = false;
                } else if (!edtFirstName.getText().toString().matches("[a-zA-Z ]+")) {
                    edtFirstName.setError("Accept Alphabets Only.");
                    isValid = false;
                }

                if (edtLastName.getText().toString().length() <= 0) {
                    edtLastName.setError("Value  Required");
                    isValid = false;
                } else if (!edtLastName.getText().toString().matches("[a-zA-Z ]+")) {
                    edtLastName.setError("Accept Alphabets Only.");
                    isValid = false;
                }

                if (edtEmail.getText().toString().length() <= 0) {
                    edtEmail.setError("Value  Required");
                    isValid = false;
                } else if (!isEmailValid(edtEmail.getText().toString())) {
                    edtLastName.setError("Invalid Email.");
                    isValid = false;
                }

                if (edtAge.getText().toString().length() <= 0) {
                    edtAge.setError("Value  Required");
                    isValid = false;
                } else if (!edtAge.getText().toString().matches("[0-9 ]+")) {
                    edtAge.setError("Accept Numbers Only.");
                    isValid = false;
                }

                if (edtPassword.getText().toString().length() <= 0) {
                    edtPassword.setError("Value  Required");
                    isValid = false;
                }

                if (edtConfirmPassword.getText().toString().length() <= 0) {
                    edtConfirmPassword.setError("Value  Required");
                    isValid = false;
                } else if (!edtConfirmPassword.getText().toString().equals(edtPassword.getText().toString())) {
                    edtConfirmPassword.setError("Password Mismatch.");
                    isValid = false;
                }


                if (isValid) {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                    nameValuePairs.add(new BasicNameValuePair("firstname", edtFirstName.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("lastname", edtLastName.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("age", edtAge.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("email", edtEmail.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("password", edtPassword.getText().toString()));

                    submitDataOnServer(nameValuePairs);
                }
            }

        });

    }

    public void submitDataOnServer(final ArrayList<NameValuePair> nameValuePairs){
        new AsyncTask<Void,Void,String>(){
            @Override
            protected String doInBackground(Void... params) {
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("localhost/Android/Insert.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();

                    Log.e("log_tag", "connection success ");
                    Toast.makeText(getApplicationContext(), "Subscription Successfull.Thank You for Subscribing you have now been added to our Mailing Lists", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Log.e("log_tag", "Error in http connection " + e.toString());
                    Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
                }
                try {

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();

                    return sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Error converting result " + e.toString());
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                try {
                    JSONObject json_data = new JSONObject(result);
                    CharSequence w = (CharSequence) json_data.get("result");

                    Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Log.e("log_tag", "Error parsing data " + e.toString());
                    Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }


    public boolean isEmailValid(final String mailAddress) {
        Pattern pattern;
        Matcher matcher;
        final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(mailAddress);
        return matcher.matches();
    }
}

Question:

I want to change the text in an EditText widget when the user clicks on a button. For example: When button1 is pressed, "1" should be displayed in the EditText field but if button2 is pressed then "2" should be displayed.


Answer:

Make sure to have an ID for your edittext field and have a onclick methods for your buttons. Then you can use .setText() on your edittext field in your java.

Your XML:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/yourId"/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1"
    android:onClick="button_1"/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 2"
    android:onClick="button_2"/>

Your Java:

public void button_1(View view) {
    //Button 1 is clicked
    ((EditText)findViewById(R.id.yourId)).setText("1");
}
public void button_2(View view) {
    //Button 2 is clicked
    ((EditText)findViewById(R.id.yourId)).setText("2");
}

This changes the text in the edittext field to respectivly 1 and 2 when button 1 or button 2 is clicked.

Question:

I have 2 EditText and a button. When I click the button I want to print a text in the editText which is selected.. How I can do this??


Answer:

Try to use this:

Get Cursor Position in Android in Edit Text?

In your onClick ask for the myEditText.getSelectionStart(); if is not null thats your EditText.

I hope this helps.

UPDATE

It looks more complicated than i thought at first, you are looking for a focus state. See if any of this answers helps you.

How can I detect focused EditText in android?