Hot questions for Using Android EditText in input

Question:

I've an edittext , it only gets numeric without decimal numbers.

android:inputType="number"

I want to separate thousands while I'm typing . For example 25,000 .

I know I should use TextWatcher and I've used this code but I couldn't make it work :

@Override
        public void afterTextChanged(Editable viewss) {
            String s = null;
            try {
                // The comma in the format specifier does the trick
                s = String.format("%,d", Long.parseLong(viewss.toString()));
            } catch (NumberFormatException e) {
            }

        }

Could you help me to do so ?


Answer:

Test this example:

import java.text.DecimalFormat;
import java.text.ParseException;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class NumberTextWatcher implements TextWatcher {

    private DecimalFormat df;
    private DecimalFormat dfnd;
    private boolean hasFractionalPart;

    private EditText et;

    public NumberTextWatcher(EditText et)
    {
        df = new DecimalFormat("#,###.##");
        df.setDecimalSeparatorAlwaysShown(true);
        dfnd = new DecimalFormat("#,###");
        this.et = et;
        hasFractionalPart = false;
    }

    @SuppressWarnings("unused")
    private static final String TAG = "NumberTextWatcher";

    @Override
    public void afterTextChanged(Editable s)
    {
        et.removeTextChangedListener(this);

        try {
            int inilen, endlen;
            inilen = et.getText().length();

            String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
            Number n = df.parse(v);
            int cp = et.getSelectionStart();
            if (hasFractionalPart) {
                et.setText(df.format(n));
            } else {
                et.setText(dfnd.format(n));
            }
            endlen = et.getText().length();
            int sel = (cp + (endlen - inilen));
            if (sel > 0 && sel <= et.getText().length()) {
                et.setSelection(sel);
            } else {
                // place cursor at the end?
                et.setSelection(et.getText().length() - 1);
            }
        } catch (NumberFormatException nfe) {
            // do nothing?
        } catch (ParseException e) {
            // do nothing?
        }

        et.addTextChangedListener(this);
    }

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

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
        {
            hasFractionalPart = true;
        } else {
            hasFractionalPart = false;
        }
    }

}

To use it, add a TextChangedListener to the EditText component.

editText.addTextChangedListener(new NumberTextWatcher(editText));

Question:

I am developing a Point Of Sales app.

So I would like to let user to enter the purchase amount

  1. Let's say User input 100000 but I want it to automatically show up 100,000. and 1000000 become 1,000,000

  2. The second problem is that, I don't want user to be able to input . themselves.

  3. Third problem is that since this is money, we can't let user to enter 0 in the beginning.

Any ideas?

So far I can only come up with inputType=numberDecimal which is not really helpful.

Thank you very much

P.S.: I do not need any decimal places


Answer:

if you want use in currency add addTextChangedListener to your desired edittext then monitor changes and reformat it , here is sample code

private String current = "";
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if(!s.toString().equals(current)){
       [your_edittext].removeTextChangedListener(this);

       String cleanString = s.toString().replaceAll("[$,.]", "");

       double parsed = Double.parseDouble(cleanString);
       String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));

       current = formatted;
       [your_edittext].setText(formatted);
       [your_edittext].setSelection(formatted.length());

       [your_edittext].addTextChangedListener(this);
    }
}

Question:

I'm trying to build a simple app that provides resources for an initial dyslexia evaluation in my language, so the original string is in Bulgarian, I've changed it to a sample text here.

Here's the situation:

  • I have an EditText so users can input the name or nickname of the child, since it will later on send (hopefully) the results on e-mail and I want to have a personal touch in there
  • after that EditText is filled I want to take its value without a button click and get it to update the string for the questions in the test. (example: the child's name input is "Amy", I want the questions to be "When playing ____ is easily distracted" and after the name input to get them to change to "When playing Amy is easily distracted".

I've looked for solutions and the closest thing I could find to what I need is written below. Nothing changes on input though.

I don't mind if answers require a change in my plans - adding a button for example. But I would really love to be able to update it dynamically somehow.

My DyslexiaTestActivity.java

EditText childName;
String savedName;

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

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int width = dm.widthPixels;
    int height = dm.heightPixels;

    getWindow().setLayout((int) (width * .9), (int) (height * .8));
    childName = (EditText) findViewById(R.id.name_input);
    savedName = childName.getText().toString();
    String text = String.format(R.string.dyslexia_question_one, savedName);
}

}

My EditText

<EditText
        android:id="@+id/name_input"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:hint=""/>

The string I'm trying to get the EditText to show up:

<string name="dyslexia_question_one">String text  <xliff:g id="name" example="Amy">%1$s</xliff:g> more string text here</string>

Answer:

you can add a listener to listen when EditText loses focus.

 childName.addTextChangedListener(new TextWatcher() {

      public void afterTextChanged(Editable s) {

         String question= //....get the question;
         String sWithName = 
         question.replace("xxx",yourEditText.getText().toString())
         yourTextView.setText(sWithName);

      }

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

      public void onTextChanged(CharSequence s, int start, int before, int count) {}
   });
}

modify the String and add XXX to the place where you want to put the name.

change "XXX" to dots (....) for example.or whatever you like.

Question:

i am coding a small calculator. I have 3 edittext fields which are written like this:

<EditText
            android:id="@+id/zField"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:hint="c"
            android:ems="10"
            android:gravity="right|bottom"
            android:inputType="numberDecimal" />

When i try to input a negativ decimal, the "-" just won't appear so i can't input any negativ numbers. How do i fix this?


Answer:

specify numberSigned input type as below

android:inputType="numberSigned|numberDecimal"

Question:

The program should display the second toast "Please introduce a real letter" in the case of an input number from 0 to 9.

The only thing that worked was this code:

if(letter.equals("0")) {
  Toast.makeText(this, "Please introduce a real letter",Toast.LENGTH_SHORT).show();
}

But I could only set it up for one letter.

This is the full code:

EditText myEditText = (EditText) findViewById(R.id.editTextLetter);
String letter = myEditText.getText().toString();

if(letter.length() == 1) {
  checkLetter(letter);
}

if( ) {
  Toast.makeText(this, "Please introduce a real letter",Toast.LENGTH_SHORT).show();
} else {
  Toast.makeText(this, "Please introduce a letter",Toast.LENGTH_SHORT).show();
}
}

Answer:

Use the method Character.isDigit();

char letter = input.charAt(0);
if(Character.isDigit(letter))
{
    //good input
}
else
{
    //bad input
}

If however you are looking to validate a number, not just 0-9, use Integer.parseInt(input).

Question:

One button adds the strings in 2 EditTexts and shows the result in the TextView. Then the second button is supposed to compare these strings to 2 separate words that are hard coded. "Hello" "World". I can't even get the strings to concatenate and show output in the Textview. Here is my code

public class MainActivity extends AppCompatActivity {
    //The stings to hold the user input
    EditText str1;
    EditText str2;
    //string to hold the output
    TextView display1;


    EditText enter1;
    EditText enter2;
    TextView WDisplay;
    Button add;
    Button display;


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


        str1 = (EditText)findViewById(R.id.enter1);
        str2 = (EditText)findViewById(R.id.enter2);
        add = (Button) findViewById(R.id.add);
        display = (Button) findViewById(R.id.display);
        display1 = (TextView)findViewById(R.id.WDisplay);


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str1 = enter1.getText().toString();
                String str2 = enter2.getText().toString();
                display1.setText(str1);



            }
        });

        display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str1 = enter1.getText().toString();
                String str2 = enter2.getText().toString();
                display1.setText(str1);

                /*String check1;

                {
                    check1 = "Hello";
                }

                String check2;

                {
                    check2 = "World";
                }*/
            }
        });
    }'

I just can't seem to connect the basic to what I need for my program. Please help!


Answer:

to concatenate your strings just do the following

add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String enter1= str1 .getText().toString();
                String enter2= str2 .getText().toString();
                display1.setText(enter1+" "+enter2);
            }
        });

and for the button that compares the strings...what do you want to do after the comparision

    display.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str1 = enter1.getText().toString();
                    String str2 = enter2.getText().toString();
                    display1.setText(str1);
    //comparision can be done as
    if (str1.equals("Hello"){
//do anything
}

 if (str2.equals("World"){
//do anything
}

                }
            });

hope this helps....happy coding

Question:

I want to know if a number that a user inputted into an "EditText" actually exists inside an array, here is my current code:

 final String[] gameArray = {("1"), ("2"), ("3"), ("4"), ("5")};


public void startGame(View v) {

    if (Arrays.asList(gameArray).contains((text))) {

        Outputs1.setText("You typed in: " + text + ", which is the correct number!");

    } else {

        Outputs1.setText("No number 1-5 detected, please type in a number 1-5.");

    }

}

When a user types in a number, it checks if that number exists inside an array by using an If-Statement, and if it does it displays a message, if it doesn't it displays another message.

Sadly, this does not work (Since it only displayed the other message even though I typed in 1-5), and the other questions and answers also did not work either.

Any response will be great.


Answer:

I hope this might help

 final String[] numberArray = {("1"), ("2"), ("3"), ("4"), ("5")};

    myEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if(s.length() == 0) return;

            String text = s.toString().substring(s.length() - 1);
            if (Arrays.asList(numberArray).contains((text))) {
                Toast.makeText(getActivity(),"You typed in: " + text + ", which is correct!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(),"Please type in a number 1-5.", Toast.LENGTH_SHORT).show();
            }
        }

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

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

Question:

I'm trying to force the numeric keypad to show when my activity and EditText load. It seems there's a pretty straightforward answer given here and elsewhere: you say

EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

Fine then. So I do this and I include the imports:

import android.content.Context;
import android.os.Bundle;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

But when we get to showSoftInput, Studio goes red and says "Cannot resolve symbol showSoftInput". Shouldn't it be getting that symbol when I import the InputMethodManager? showSoftInput doesn't seem to be deprecated or anything.


Answer:

Keyboard is not opening because it needs some delay ,

Follow this code

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);
       /* */

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            editText.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
        }
    },100);
    }
}

and XML

 <EditText
    android:id="@+id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:focusable="true"
    android:inputType="number"
    android:text="">

    <requestFocus></requestFocus>
</EditText>

Question:

I have an EditText with "textPassword" inputType in my app and I tried to set a non-english password but the inputType didn't allow me to choose another language. Maybe my app users prefer to set a persian password.

See The Picture, Please

Any Ideas?


Answer:

inputType is considered as a hint to the keyboard app on how to treat a specific text-field, even if some keyboards do allow non-english passwords, you can't count on all keyboard apps to behave like that.

Instead of using the inputType, set the password field to true, this will cause the characters to be hidden from the screen, but will allow you to get any input, you should probably also turn off suggestions (using the inputType field):

<EditText
    android:id="@+id/password"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text|textShortMessage|textNoSuggestions"
    android:password="true"/>

UPDATE

You can create a plain EditText with some textual inputType, and just set the characters to appear as dots instead of plain text:

EditText passwordView = (EditText) layout.findViewById(R.id.password);
passwordView.setTransformationMethod(PasswordTransformationMethod.getInstance());

Question:

My issue is I can't keep my EditText input from accepting alpha-numeric. This is on Android and it for an app I'm working on. I only want it to accept numbers.

I create the EditText on the fly. Below is the code to create them. This is the code for the entire Java file.

public class PartDetail extends Activity implements View.OnClickListener{

    private final int NUM_COL = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.part_detail);
        Bundle bundle = getIntent().getExtras();
        String btnName = bundle.getString("btnNameStored");
        String btnOrig = bundle.getString("btnOrig");

        TextView textView = (TextView) findViewById(R.id.txtBtnPushed);
        textView.setText(btnOrig);
        BufferedReader reader;
        InputStream is = null;

        // Get the name of the part picked and then grab the dimensions that are needed for that
        // part.

        try {

            is = getAssets().open(btnName);

            reader = new BufferedReader(new InputStreamReader(is));

            String line = reader.readLine();
            int lineLength = (line.length());

            //Used for debugging ---------------------------
            //System.out.println(" -- Text on Button --  " + btnName + " -- Line Length -- " +
            //        lineLength);
            // ------------------------------------

            TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);

            while (line != null){

                TableRow tblRow = new TableRow(this);
                tblRow.setPadding(5, 30, 5, 5);
                table.addView(tblRow);
                line = line.toUpperCase();

                // sets the max number of col to 2 and iterates through the number of lines.
                // filling each cell with a Text Box with the name of each dimension of the part
                // that was picked.

                for (int col = 0; col < NUM_COL; col++) {
                    //This is the label of what measurement needs to be enter.
                    TextView lblName = new TextView(this);
                    // This is the number you enter for the measurement.
                    EditText txtPartMeasurement = new EditText(this);

                    // Set all the input attributes for the text boxes.
                    if (line == "QTY") {
                        txtPartMeasurement.setInputType(InputType.TYPE_CLASS_NUMBER);
                    }
                        else {
                        txtPartMeasurement.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    }

                    txtPartMeasurement.setTextSize(14);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        txtPartMeasurement.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
                    }
                    txtPartMeasurement.setEnabled(true);

                    // Set all the input attributes for the labels of what needs to be entered.
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        lblName.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                    }
                    lblName.setBackgroundColor(getResources().getColor(R.color.colorPartMeasurements));
                    lblName.setFocusable(true);
                    lblName.setText(line);
                    lblName.setTextSize(14);

                    // Add the labels and text boxes to the grid.
                    tblRow.addView(lblName);
                    tblRow.addView(txtPartMeasurement);

                    // Get the next line in the file if there one.
                    line = reader.readLine();
                }
            };

        }
        catch (IOException e) {
            //Used for debugging --------------------------------------------
            //System.out.println("In the catch of the On Catch in PartDetail  --  " + btnName);
            // ----------------------------------------------------------
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {

    }
}

Notice I set TYPE_CLASS_NUMBER of the lbl for that EditText is QTY, else I want it to boe TYPE_NUMBER_FLAG_DECIMAL.

But this doesn't seem to be working. I've tried it on my emulator, and my real phone. No go. Please let me know what I'm doing wrong. Thanks.

Here's the xml. Remember, I create most of the objects on the fly.

  <?xml version="1.0" encoding="utf-8"?>
     <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ~ Copyright (c) 2016. Unless otherwise noted, all my code is open source
-->

<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
          android:layout_width = "match_parent"
          android:layout_height = "match_parent" >

<TextView
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:text = "New Text"
    android:id = "@+id/txtBtnPushed"
    android:textSize = "42sp"
    android:layout_alignParentTop = "true"
    android:layout_centerHorizontal = "true" />

<ImageView
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:id = "@+id/imgPartPicked"
    android:layout_below = "@+id/txtBtnPushed"
    android:layout_centerHorizontal = "true"
    android:src = "@mipmap/straight_tap"
    android:minWidth = "150dp"
    android:minHeight = "150dp" />
<ScrollView
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:layout_below = "@+id/imgPartPicked"
    android:layout_alignParentLeft = "true"
    android:layout_alignParentStart = "true">

    <TableLayout
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:stretchColumns="*"
        android:id = "@+id/tblLayoutContent">
    </TableLayout >

</ScrollView >
</RelativeLayout >

Answer:

write android:inputType="number" in your xml attribute or android:inputType="numberDecimal"

android:inputType="number" only accept int number, android:inputType="numberDecimal" accept decimal number.

You may refer this.

Question:

I need to add automatically thousand seperators as number input.

I try to write some code, but it is not work. When I programatically set text to edit text it's work fine, but when the user type number thousand separators not added. Here is my code:

EditText etEdit;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etEdit = findViewById(R.id.et_edit);
        setListeners();
        etEdit.setText("500000");

    }

    private void setListeners() {
        etEdit.addTextChangedListener(new TextWatcher() {
            int after = 0;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if ((i1 + i2) > charSequence.length()) {
                    after = i2;
                } else {
                    after = i + i2;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    Pattern mPattern = Pattern.compile("([1-9][0-9]*?)");
                    Matcher matcher = mPattern.matcher(editable.toString().replace(String.valueOf((char) 160), "").trim());
                    if (!matcher.matches()) {
                        if (!(etEdit.getText().toString().equals(""))) {
                            etEdit.setText(etEdit.getText().subSequence(0, etEdit.getText().length() - 1));
                            etEdit.setSelection(etEdit.getText().length());
                        }
                    }
                    if (after != 0) {
                        etEdit.setSelection(after);
                    }
                    if (!(etEdit.getText().toString().equals(""))) {
                        etEdit.removeTextChangedListener(this);
                        etEdit.setText(thousandSeparators(Double.valueOf(etEdit.getText().toString().replace(String.valueOf((char) 160), "").trim())));
                    }
                }
            }
        });
    }

private   String thousandSeparators(double value) {
    DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.getDefault());
    formatSymbols.setGroupingSeparator((char) 160);
    DecimalFormat format = new DecimalFormat("#,###,###", formatSymbols);
    return format.format((int) value);
}

Please help me solve this problem.


Answer:

You removed the textChangedListener before setting text in afterTextChanged, but didn't add it afterwards.

if (!(etEdit.getText().toString().equals(""))) {
  etEdit.removeTextChangedListener(this);
  etEdit.setText(thousandSeparators(Double.valueOf(etEdit.getText().toString().replace(String.valueOf((char) 160), "").trim())));
  etEdit.addTextChangedListener(this);
}

P.S - You should also remove and add the listener before setting text in the matcher if condition block (to prevent it from getting into an infinite loop).

  etEdit.removeTextChangedListener(this);
  etEdit.setText(etEdit.getText().subSequence(0, etEdit.getText().length() - 1));
  etEdit.addTextChangedListener(this);

Question:

I have created a project in which, I have a class that extends fragments, in which the frame layout consist two edit text. Problem here is whenever I click/touch on any edit text, the soft input keyboard popups which I don't want to popups. I tried the following method to disable the soft input keyboard.

In androidmanifest.xml file, I have also used the property android:windowSoftInputMode="stateHidden"

public class Convert extends Fragment{ 

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.converter_data_layout, container, false);

        screen_v1 = (EditText) viewGroup.findViewById(R.id.data_value1);
        screen_v2 = (EditText) viewGroup.findViewById(R.id.data_value2);

        screen_v1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                hideKeyboard(getContext());
            }
        });

        screen_v2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                  hideKeyboard(getContext());
            }
        });

        return viewGroup;
    }

    public void hideKeyboard(Context context){
        InputMethodManager inputMethodManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = ((Activity)context).getCurrentFocus();
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

My xml file code

<FrameLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="rahuldadoriya.mathsolver.convert.Convert"
    android:id="@+id/frame_data">
    <EditText
        android:maxLength="15"
        android:id="@+id/data_value1"
        style="@style/EdittextStyle"
        android:layout_weight="2.8"
        android:gravity="right"
        android:paddingRight="15dp"
        android:paddingTop="25dp"
        android:inputType="numberDecimal"
        android:clickable="true"/>

    <EditText
        android:maxLength="15"
        android:id="@+id/data_value2"
        style="@style/EdittextStyle"
        android:layout_weight="2.8"
        android:gravity="right"
        android:paddingRight="15dp"
        android:paddingTop="25dp"
        android:inputType="numberDecimal"
        android:clickable="true"/>
</FrameLayout>

Thanks in advance.


Answer:

thanks for your help, I have solved my problem but not fully satisfied with the solution, because what i have used for not popping up the soft input keyboard is setting setInputType(0) for both the edittext, i.e.

screen_v1.setInputType(0);

similarly for the other edittext but the issues here is after using the above method on both the edittext, cursor is not visible on either of the edittext. So if any one have any reason why it is happening so please help me.

Thanks

Question:

This part of my program is supposed to be a user input field for the quantity of an item to purchase. What I'm unable to do is to make it so when the program finally runs on the emulator and I change the textfield number in the EditText, named "etxtQuantity" in my case, the number I use is ignored and it reverts to using the default entry. Also my if statement isn't working like I expect either, it accepts everything.

private void setupAddRecordButton() {

    Button button = (Button) findViewById(R.id.btnAddCart);

    button.setOnClickListener(new View.OnClickListener() {

        final TextView countText = (TextView) findViewById(R.id.txtAddCartCount);
        EditText quantity = (EditText) findViewById(R.id.etxtQuantity);
        String quantity2 = quantity.getText().toString();
        final TextView text2 = (TextView) findViewById(R.id.txtQuantityCheck); 

        @Override
        public void onClick(View v) {

            if (! quantity2.equals(".") || quantity2.equals("") || quantity2.equals("-")) {
                count++;
                long newId = myDb.insertRow("GTX 950", 140, quantity2);
                myDb.getRow(newId);
                countText.setText("Successfully added " + count + " Times");
            }
            else
            {
                text2.setText("Quantity needed!");
            }
        }
    });
}

Answer:

initailize your edit text in onCreate() callback function of your activity and use String quantity2 = quantity.getText().toString(); in onClick() function of your button

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EditText quantity = (EditText) findViewById(R.id.etxtQuantity);
    Button button = (Button) findViewById(R.id.btnAddCart);
    TextView text2 = (TextView) findViewById(R.id.txtQuantityCheck); 
    TextView countText = (TextView) findViewById(R.id.txtAddCartCount);

     button.setOnClickListener(new View.OnClickListener() {
          String quantity2 = quantity.getText().toString();

          @Override
          public void onClick(View v) {
          if (! quantity2.equals(".") || quantity2.equals("") ||quantity2.equals("-")) {
            count++;
            long newId = myDb.insertRow("GTX 950", 140, quantity2);
            myDb.getRow(newId);
            countText.setText("Successfully added " + count + " Times");
          }
          else
          {
            text2.setText("Quantity needed!");
          }
       }
    });
   }

Question:

I have a class that wraps a DatePicker and TimePicker dialoagues into a single view pager view so that the user can choose both a date and time. This methods returns a calendar object.

public class DialogUtils {
    public static Calendar showDateAndTimeDialog(final Context context) {

        View view = LayoutInflater.from(context).inflate(R.layout.dialog_date_time,null, false);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker);
        final ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
        final Calendar calendar = Calendar.getInstance();
        viewPager.setAdapter(new PagerAdapter() {

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                return viewPager.getChildAt(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "Date";
                    case 1:
                        return "Time";
                }
                return super.getPageTitle(position);
            }

            @Override
            public int getCount() {
                return viewPager.getChildCount();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
        });
        final TabLayout layoutTab = (TabLayout) view.findViewById(R.id.layout_tab);
        layoutTab.setupWithViewPager(viewPager);

        final AlertDialog dateAndTimeDialog = new AlertDialog.Builder(context)
                .setView(view)
                .setPositiveButton("OK", null)
                .setNegativeButton("Cancel", null)
                .create();
        dateAndTimeDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(final DialogInterface dialog) {

                /*
                    We override the default BUTTON_POSITIVE OnClickListener to prevent the dialog
                    from dismissing when the user presses OK
                 */

                dateAndTimeDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(
                        new View.OnClickListener() {

                            public void onClick(View v) {
                                if (viewPager.getCurrentItem() == 0) {
                                    viewPager.setCurrentItem(1);
                                    return;
                                }

                                calendar.set(Calendar.MONTH, datePicker.getMonth());
                                calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
                                calendar.set(Calendar.YEAR, datePicker.getYear());

                                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
                                calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());

                                // We must dismiss the dialog as we have overriden the default behavior
                                dialog.dismiss();
                            }
                        });
            }
        });
        dateAndTimeDialog.show();
        return calendar;
    }
}

This is called in my Activity class in two places. The first

public Calendar launchDateAndTimePicker(View view) {
       return DialogUtils.showDateAndTimeDialog(this);
    }

and also in the onCreate method of my Activity inside a click listener like so

mEditDueDate = ((EditText) findViewById(R.id.task_due_date));
        mEditDueDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal;
                cal = launchDateAndTimePicker(v);
                // Bitmask used to determine timestamp format
                int displayMask = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;

                // Resultant timestamp
                String timestamp = DateUtils.formatDateTime(getApplicationContext(), cal.getTimeInMillis(), displayMask);
                mEditDueDate.setText(timestamp);
            }
        });
    }

Even after I select a new date and time, my EditText field displays the current date and time. I feel like how i am initialising a calendar object is clobbering the values set by the Picker widgets. How should i extract the calendar values from the calendar object returned by showDateAndTimeDialog?

Edit for Solution

I updated the DialogUtils class to take an Activity in its constructor and update the EditText field directly.

public Activity editActivity;
    public static EditText mEditDueDate;

    public DialogUtils(Activity editActivity) {
        this.editActivity = editActivity;
    }

and then find the EditText field

 mEditDueDate = (EditText) editActivity.findViewById(R.id.task_due_date);

and later update the EditText field.

// Bitmask used to determine timestamp format
                                int displayMask = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
                                String timestamp = DateUtils.formatDateTime(editActivity.getApplicationContext(), calendar.getTimeInMillis(), displayMask);
                                mEditDueDate.setText(timestamp);

                                // We must dismiss the dialog as we have overriden the default behavior
                                dialog.dismiss();

Answer:

By the time the timestamp is extracted and set to the EditText, the user has not yet entered a date.

You should move

// Resultant timestamp
String timestamp = DateUtils.formatDateTime(getApplicationContext(), cal.getTimeInMillis(), displayMask);
mEditDueDate.setText(timestamp);

to a DialogInterface.OnClickListener.onClick maybe implemented within the surrounding class.

And when you build your dialog add the listener to the positive button of the dialog:

final AlertDialog dateAndTimeDialog = new AlertDialog.Builder(context)
            .setView(view)
            .setPositiveButton("OK", this)
            .setNegativeButton("Cancel", null)
            .create();

Of course you will have make the result Calendar object available in the OnClickListener.

Question:

I' ve extend edittext class, how can create a custom input type to accept just this characters (M,C,D,X,V,I)? This is my class that extend EditText

import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;

public class DecimalEditText extends EditText{

    public DecimalEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub


    }
    public int getArabic(String roman){
        ConversioneTest ca = new ConversioneTest();
        int i = ca.convertToDecimal(roman);
        return i;

    }

}


Answer:

You'll want to implement an InputFilter to restrict the input to the acceptable characters and assign that to the EditText. In first iteration, this is really simple. Take a look at the source code of LoginFilter.UsernameFilterGeneric for an example. You'll have this set up in minutes.

If that's all you need, great, stop there! Unfortunately, this may be all you need. There are some grammatical rules to roman numerals, for instance XXCI is (100-20)+1=81, but IXXC is not 100-(20-1)=81. If you want to cover that, then InputFilter is too crude. You'll still use the InputFilter to make the initial filtering, but you'll have to implement TextWatcher on top of that to handle the advanced input validation. The PhoneNumberFormattingTextWatcher (source) gives you some clues on how to do that. It's an awful lot more work than just the InputFilter, because you'll have to deal with all sorts of weird multi-character inputs, such as clipboard paste-to-replace-selection.

Question:

So I try to compare 2 values, one is the "coinAmount" from Firebase, it's a Long value, and an EditText input (Which is a String).

Basically what I'm trying to achieve is, I want to show a warning if the input exceeds the coin amount that the user have.

        String coinAmount = coinWrapper.getEditText().getText().toString();

        if (Long.parseLong(coinAmount) >= coinValue) {

          Toast.makeText(getApplicationContext(), "You don't have enough coins!",
              Toast.LENGTH_SHORT).show();
        } else {

          Intent intent = new Intent(getActivity(), FriendActivity.class);
          intent.putExtra("coin", coinAmount);
          intent.putExtra("choice", choice);
          startActivity(intent);
        }

The reason I get the user input as String is because I'm going to display that value as a text later, so while I'm comparing I parsed it to Long. However, when I run the app I get this NullPointerException:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: ege.mevzubahis, PID: 13369
java.lang.NullPointerException
    at ege.mevzubahis.Fragments.BetsDialogFragment.onClick(BetsDialogFragment.java:135)
    at ege.mevzubahis.Fragments.BetsDialogFragment_ViewBinding$4.doClick(BetsDialogFragment_ViewBinding.java:70)
    at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
    at android.view.View.performClick(View.java:4478)
    at android.view.View$PerformClick.run(View.java:18698)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)

Here is the part where I try to get coinAmount from Firebase:

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    userID=sharedPreferences.getString("userIDKey",null);


    mDatabase.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {

        coinValue = (Long) dataSnapshot.child("coin").getValue();

      }

      @Override
      public void onCancelled(DatabaseError databaseError) {

        //Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

      }
    });

error is in this part:

if (Long.parseLong(coinAmount) >= coinValue) {

Full code
public class BetsDialogFragment extends DialogFragment implements View.OnClickListener {

  @BindView(R.id.tv_match) TextView tv_match;
  @BindView(R.id.textView2) TextView textView2;
  @BindView(R.id.textInputLayout) TextInputLayout textInputLayout;
  @BindView(R.id.radioButton4) RadioButton radioButton4;
  @BindView(R.id.radioButton5) RadioButton radioButton5;
  @BindView(R.id.radioButton6) RadioButton radioButton6;
  @BindView(R.id.button2) Button sendButton;

  String matchName;
  private DatabaseReference mDatabase;
  private RadioGroup radioGroup;
  private String choice;
  private EditText editText;
  private TextInputLayout coinWrapper;
  public Long coinValue;

  SharedPreferences sharedPreferences;
  private String userID;

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.custom_dialog, null);
    matchName = getArguments().getString("betNameInPosition");
    mDatabase = FirebaseDatabase.getInstance().getReference();
    radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
    editText = (EditText) view.findViewById(R.id.editText);
    coinWrapper = (TextInputLayout) view.findViewById(R.id.textInputLayout);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    userID=sharedPreferences.getString("userIDKey",null);


    mDatabase.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {

        coinValue = (Long) dataSnapshot.child("coin").getValue();

        Log.v("coin value: ", coinValue.toString());

      }

      @Override
      public void onCancelled(DatabaseError databaseError) {

        //Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

      }
    });

    mDatabase.child("Bets")
        .child("Sports")
        .child(matchName)
        .addListenerForSingleValueEvent(new ValueEventListener() {
          @Override public void onDataChange(DataSnapshot dataSnapshot) {
            try {
              Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
              String value = (String) map.get("matchname").toString();
              tv_match.setText(value);
              String durationValue = (String) map.get("duration").toString();
              textView2.setText("Due to: " + durationValue);

              coinValue = (Long) dataSnapshot.child("coin").getValue();
            } catch (Throwable t) {
              Log.e("trycatchFAIL", "b");
            }
          }

          @Override public void onCancelled(DatabaseError databaseError) {

          }
        });

    ButterKnife.bind(this, view);
    return view;
  }

  @OnClick({ R.id.radioButton4, R.id.radioButton5, R.id.radioButton6})
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.radioButton4:
        choice = "home";
        Toast.makeText(getApplicationContext(), "choice: Home", Toast.LENGTH_SHORT).show();
        break;
      case R.id.radioButton5:
        choice = "draw";
        Toast.makeText(getApplicationContext(), "choice: Draw", Toast.LENGTH_SHORT).show();
        break;
      case R.id.radioButton6:
        choice = "away";
        Toast.makeText(getApplicationContext(), "choice: Away", Toast.LENGTH_SHORT).show();
        break;

    }
  }

  @OnClick(R.id.button2)
  public void onClickSendButton(View view){
    String coinAmount = coinWrapper.getEditText().getText().toString();

    Log.v("coinAmount",coinAmount);

    if (Long.parseLong(coinAmount) >= coinValue) {

      Toast.makeText(getApplicationContext(), "You don't have enough coins!",
          Toast.LENGTH_SHORT).show();
    } else {

      Intent intent = new Intent(getActivity(), FriendActivity.class);
      intent.putExtra("coin", coinAmount);
      intent.putExtra("choice", choice);
      startActivity(intent);
    }


  }
}

Answer:

if (Long.parseLong(coinAmount) >= coinValue).  

there is the problem: if coinAmount is null, will throw java.lang.NumberFormatException: null so it looks like coinValue is null. because of using ">=", Java will try to change Long - > long. if the item is null, jvm will throw java.lang.NullPointerException.

Question:

Am developing an android chat application. Everything works well but except for one thing; I want to set the visibility of a layout to gone and then set a different layout to visible when user starts typing in the edittext like the one implemented on whatsapp. But I cant seem to figure it out. Any help will be appreciated

Basically, what I want to do is set the visibility of a layout which contains an image button to upload image to gone and then show a layout which contains an image button to send the message or text in the edittext to visible when the user starts typing


Answer:

Can you explain in detail? Do you wan edit text to come up when keyboard is hoped up. then use below in your manifest.

<activity
        android:name=".Activityname"

        android:windowSoftInputMode="adjustPan">

If not, then please explain your question in more detail

Question:

My xml has an EditText:

<EditText
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="@dimen/margin_padding_size_small"
android:layout_marginLeft="@dimen/margin_padding_size_small"
android:background="@android:color/transparent"
android:drawableStart="@drawable/ic_envelope"
android:drawableLeft="@drawable/ic_envelope"
android:drawablePadding="4dp"
android:gravity="center_vertical"
android:hint="@string/email_hint"
android:maxLines="1"
android:textColorHint="@color/colorHintText"
android:inputType="textEmailAddress"/>

Now I was writing UI tests using the Espresso library and it cannot type text into this EditText using typeText() or typeTextIntoFocusedView() and my test method is:

 @Test
    public void onSubmitClickedWithAnInvalidEmail(){
        onView(withId(R.id.et_email)).perform(scrollTo(), click(), typeText("test")); //invalid email
        onView(withId(R.id.btn_submit)).perform(click());
        onView(withId(R.id.et_email)).check(matches(hasErrorText(mActivityTestRule.getActivity().getString(R.string.invalid_email_prompt))));
    }

The test runs but cannot type into the email edittext. It gets stuck after scrolling to and clicking on the EditText. One thing that I noticed is that my email addresses are suggested on the email EditText by google in a Spinner looking thing. I strongly think that is the reason why espresso is not able to type into the EditText.

The message that I get in the Run is:

java.lang.RuntimeException: Waited for the root of the view hierarchy to have window focus and not request layout for 10 seconds. If you specified a non default root matcher, it may be picking a root that never takes focus. Root:
Root{application-window-token=android.view.ViewRootImpl$W@d881111, window-token=android.view.ViewRootImpl$W@d881111, has-window-focus=false, layout-params-type=1, layout-params-string={(0,0)(fillxfill) ty=BASE_APPLICATION wanim=0x10302f8
fl=LAYOUT_IN_SCREEN LAYOUT_INSET_DECOR SPLIT_TOUCH HARDWARE_ACCELERATED DRAWS_SYSTEM_BAR_BACKGROUNDS
pfl=FORCE_DRAW_STATUS_BAR_BACKGROUND}, decor-view-string=DecorView{id=-1, visibility=VISIBLE, width=1080, height=1920, has-focus=true, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params={(0,0)(fillxfill) ty=BASE_APPLICATION wanim=0x10302f8
fl=LAYOUT_IN_SCREEN LAYOUT_INSET_DECOR SPLIT_TOUCH HARDWARE_ACCELERATED DRAWS_SYSTEM_BAR_BACKGROUNDS
pfl=FORCE_DRAW_STATUS_BAR_BACKGROUND}, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}}
at androidx.test.espresso.base.RootViewPicker.waitForRootToBeReady(RootViewPicker.java:111)
at androidx.test.espresso.base.RootViewPicker.pickRootView(RootViewPicker.java:149)
at androidx.test.espresso.base.RootViewPicker.get(RootViewPicker.java:91)
at androidx.test.espresso.ViewInteractionModule.provideRootView(ViewInteractionModule.java:77)
at androidx.test.espresso.ViewInteractionModule_ProvideRootViewFactory.provideRootView(ViewInteractionModule_ProvideRootViewFactory.java:37)
at androidx.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:27)
at androidx.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:10)
at androidx.test.espresso.base.ViewFinderImpl.getView(ViewFinderImpl.java:63)
at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:223)
at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:65)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:158)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:155)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

EDIT:

Test method

@Test
    public void onSubmitClickedWithAnInvalidEmail() {
        onView(withId(R.id.et_email)).perform(scrollTo(), typeText("test")); //invalid email
        onView(withId(R.id.btn_submit)).perform(click());
        onView(withId(R.id.et_email)).check(matches(hasErrorText(mActivityTestRule.getActivity().getString(R.string.invalid_email_prompt))));
    }

Error Log:

androidx.test.espresso.PerformException: Error performing 'type text(test)' on view 'with id: com.example.myapp:id/et_email'.
at androidx.test.espresso.PerformException$Builder.build(PerformException.java:86)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:87)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:59)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:322)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:178)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:119)
at com.exmple.myapp.activities.ForgotPasswordActivityTest.onSubmitClickedWithAnInvalidEmail(ForgotPasswordActivityTest.java:45)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:531)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2337)
Caused by: androidx.test.espresso.InjectEventSecurityException: java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission
at androidx.test.espresso.base.InputManagerEventInjectionStrategy.injectKeyEvent(InputManagerEventInjectionStrategy.java:119)
at androidx.test.espresso.base.EventInjector.injectKeyEvent(EventInjector.java:88)
at androidx.test.espresso.base.UiControllerImpl$2.call(UiControllerImpl.java:192)
at androidx.test.espresso.base.UiControllerImpl$2.call(UiControllerImpl.java:189)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission
at android.os.Parcel.createException(Parcel.java:1950)
at android.os.Parcel.readException(Parcel.java:1918)
at android.os.Parcel.readException(Parcel.java:1868)
at android.hardware.input.IInputManager$Stub$Proxy.injectInputEvent(IInputManager.java:575)
at android.hardware.input.InputManager.injectInputEvent(InputManager.java:880)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.test.espresso.base.InputManagerEventInjectionStrategy.injectKeyEvent(InputManagerEventInjectionStrategy.java:113)
... 9 more
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.input.InputManagerService.injectInputEventInternal(InputManagerService.java:627)
at com.android.server.input.InputManagerService.injectInputEvent(InputManagerService.java:601)
at android.hardware.input.IInputManager$Stub.onTransact(IInputManager.java:143)
at android.os.Binder.execTransact(Binder.java:752)

Please suggest some workaround or point if I am doing something wrong. thanks.


Answer:

Try removing the click action:

onView(withId(R.id.et_email)).perform(scrollTo(), typeText("test"));

The click and typeText actions don't go well together. When the typeText action is being performed, it will tap to focus on the EditText before it injects string. So having both actions together will result two single-clicks, and may trigger contextual menu on some devices, which prevents Espresso to inject strings.

If typeText only still pops contextual menu, then alternatively use ViewActions.replaceText.

Question:

I have create a edit text and a spinner, Into the spinner there are more than one selection those are Permanent and temporary. If i input "Brand" in edit text then in the spinner it should show only Permanent not to show temporary but if i input any other word it should display permanent or temporary

I've tried that if i enter the integer then it return the month name. E.g: If I enter 6 then in the spinner it display June.

Main Activity code

        edit = (EditText) findViewById(R.id.editText);
        spinner = (Spinner) findViewById(R.id.spinner);

        String[] months = new DateFormatSymbols().getMonths();


        ArrayAdapter adapter = new ArrayAdapter<String>(this, 
        android.R.layout.simple_spinner_item,months);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new 
        AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, 
            int position, long id)
            {
                edit.setText(String.valueOf(position + 1));
            }


        });

        edit.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void afterTextChanged(Editable s)
            {
                try
                {

                  int nPosition = Integer.parseInt(s.toString());
                    if (nPosition >= 1 && nPosition <= 12)
                    {
                        spinner.setSelection(nPosition - 1);
                    }
                }
                catch(NumberFormatException nfe)
                {

                }
            }
        });

Answer:

Try this one...

public class Main2Activity extends AppCompatActivity {

Spinner sp1;

ArrayAdapter<String> sAdapter1;
ArrayAdapter<String> sAdapter2;
String s1[] = {"Permanent"};
String s2[] = {"Permanent", "Temporary"};

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

    sp1 = (Spinner) findViewById(R.id.spinner1);
    EditText et = (EditText) findViewById(R.id.editText1);

    sAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, s1);
    sAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    sAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, s2);
    sAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    et.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.toString().equals("Brand")) {
                sp1.setAdapter(sAdapter1);
            } else {
                sp1.setAdapter(sAdapter2);
            }
        }
    });

}
}

Question:

I have an activity called ParticleActivity in my Android Studio project.

public class ParticleActivity extends AppCompatActivity  {

public final static String EXTRA_MESSAGE = "pso.algo.MESSAGE";
private ProgressDialog pd;
private double[] results = {-1.0, -1.0, -1.0};
EditText particles = (EditText) findViewById(R.id.particles);
EditText iterations = (EditText) findViewById(R.id.iterations);
static EditText solution;
public static double userSolution = Double.parseDouble(solution.getText().toString());
static EditText battery;
public static double batteryLevel = Double.parseDouble(battery.getText().toString());

The userSolution and batteryLevel are declared so that the user input in those fields can be accessed by another class, customUseCase.

public class CustomUseCase extends Test {

public ArrayList<Double> costData = MainActivity.costDATA; //costs that the user enters for each resource
public ArrayList<Double> costWlan = MainActivity.costWLAN;
public ArrayList<Double> costUtilities = MainActivity.costUTILITY;
public double batteryCost = ParticleActivity.batteryLevel; //battery cost user enters
public double userSolution = ParticleActivity.userSolution; //user's predicted solution
private int maxIter;
private int noParticles;

I know this isn't a good way of writing code as it says on Android Studio that I will get a memory leak because the Android components shouldn't be declared as static variables. But this is the only way (from my little knowledge of Android) that I can think off where I can access the user input from the EditText fields in ParticleActivity so that it can be used in my customUseCase class. Can someone give me a good way I can write this out? Thank you.


Answer:

Try using Intent class and its putExtra method see the docomentation here https://developer.android.com/reference/android/content/Intent.html

example usage

Intent i = new Intent(ParticleActivity.this,CustomUseCase.class)
                     i.putExtra("myShow","one");

then on your CustomUseCase class

Intent i=getIntent();
String show=i.getStringExtra("myShow");

Question:

I'm new to SO and a fairly new to Java so please don't hate on me. I have multiple editText boxes that are supposed to function like an excel spreadsheet. Here is some code from this simple application:

EditText tradeDif = (EditText) findViewById(R.id.tradeDif);    

TextWatcher tradeWatch = new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {
        calcTrade();

    }

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

    }

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

    }

};

private void calcTrade() throws NumberFormatException {
Editable eValue1 = newPrice.getText(), eValue2 = tradeIn.getText(), eValue3 = acc.getText();
Double value1 = 0.0, value2 = 0.0, value3 = 0.0, result = 0.0;


if (eValue1 != null)
    value1 = Double.parseDouble(eValue1.toString());
if (eValue2 != null)
    value2 = Double.parseDouble(eValue2.toString());
if (eValue3 != null)
    value3 = Double.parseDouble(eValue3.toString());
if (value1 != null && value2 != null && value3 != null)
    result = value1 - (value2 + value3);
    tradeDif.setText(result.toString());

}

The EditText field TradeDif needs to be able to display the variable result. When I run this it crashes, and I THINK it's because the tradeDif editText is empty. Also, I need to be able to use what is displayed in the tradeDif EditText for further calculations with further editTexts. I'm assuming I would need to use some kind of try catch block, but I'm kind of unsure how to implement it. Any help is appreciated.


Answer:

Double.parseDouble() throws a NumberFormatException if the provided String does not contain a valid double value. This includes empty String.

To pass that error, I suggest to check, if the string is empty by creating a new method:

private double toDouble(final Editable editable) {
    final String content = editable.toString();
    if (content.isEmpty()) {
        return 0;
    }
    return Double.parseDouble(content);
}

And then change your code to:

if (eValue1 != null)
    value1 = toDouble(eValue1);
if (eValue2 != null)
    value2 = toDouble(eValue2);
if (eValue3 != null)
    value3 = toDouble(eValue3);

The new method avoids code doubling and it could easily be maintained.

You could also think about catching the Exception, but I prefer avoiding them in the first place. Especially for this kind of reason (empty String).

Question:

I need to set one of my EditText to enter three alpha value and four digits Ex:- ABC1234. So I need to change automatically input type from Text to phone when user typed three alphas. I came up with following code and but its not change to phone input type and text type is remains for any text length.

editText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            String text = editText.getText().toString();
           if(text.length()==1 || text.length()==2 || text.isEmpty()){
               editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
               System.out.println("Length Text type : " + text.length());

           }else{
               editText.setRawInputType(InputType.TYPE_CLASS_PHONE);

               System.out.println("Length phone type : " + text.length());

           }
        }

What I have done wrong.


Answer:

setRawInputType() is usually used when you initialize the view, in a constructor of a custom view or in onCreate() method of an activity.

In your case you have to call setInputType() change the mode of the soft keyboard.

Question:

I'm kinda new to android. So I'm trying calculate the price of something using EditText instead of ListView, and I have increment and decrement buttons included to increase the value on the EditText component.

So the increment and decrement buttons are working okay. They are decrementing and incrementing the value in EditText, and are calculating the price just fine, but when I type in the EditText instead of using the buttons the value I typed doesn't get used.

Here's my Code.

XML

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

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/latte" />

    <TextView
        android:id="@+id/quantitytxt_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Quantity ( Cup(s) )"
        android:textAllCaps="true"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <Button
        android:id="@+id/decrementButton"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/quantitytxt_textview"
        android:onClick="decrement"
        android:text="-"
        android:textSize="15sp" />

    <EditText
        android:id="@+id/quantity_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/quantitytxt_textview"
        android:layout_toRightOf="@id/decrementButton"
        android:padding="10dp"
        android:inputType="text"
        android:text="0"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <Button
        android:id="@+id/incrementButton"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/quantitytxt_textview"
        android:layout_toRightOf="@id/quantity_textview"
        android:onClick="increment"
        android:text="+"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/pricetxt_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/quantity_textview"
        android:padding="10dp"
        android:text="Price (1 Cup = KES 5)"
        android:textAllCaps="true"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/price_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/pricetxt_textview"
        android:padding="10dp"
        android:text="KES 0"
        android:textColor="@android:color/white"
        android:textSize="16sp" />


    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/price_textview"
        android:onClick="submitOrder"
        android:text="Order"
        android:textSize="15sp" />

</RelativeLayout>

Java

package com.teqqli.justjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.text.NumberFormat;


/**
 * This app displays an order form to order coffee.
 */
public class MainActivity extends AppCompatActivity {

    int quantity = 0;

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

    /**
     * This method is called when the order button is clicked.
     */
    public void submitOrder(View view) {
        int price = quantity*5;
        displayPrice(price);
    }

    public void increment (View view) {
        quantity = quantity + 1;
        display(quantity);
    }

    public void decrement (View view) {
        if (quantity>0){
            quantity = quantity - 1;
            display(quantity);
        }
    }

    /**
     * This method displays the given quantity value on the screen.
     */
    private void display(int number) {
        EditText quantityText = (EditText) findViewById(R.id.quantity_textview);
        quantityText.setText("" + number);
    }

    /**
     * This method displays the given price on the screen.
     */
    private void displayPrice(int number) {
        TextView priceTextView = (TextView) findViewById(R.id.price_textview);
//        priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
        priceTextView.setText("KES " + number);
    }
}

Kindly can anyone assist me?


Answer:

Use quantityText.getText() function to get the value and store it in a variable and then do the increment and decrement operation on this value.

Something like this:

int value = Integer.parseInt(quantityText.getText().toString().trim());

and then pass this value to your increment and decrement functions.

Question:

I was wondering if it was possible to ouput xml elements such as editText and textView based off user input. For example I'm making a simple game app and in the app you get taken to a new activity where it asks the amount of players. Based off the input (e.g. 5) I woulld like to display editText's and textViews so the players can be given names. Is this possible with Java and if so, how?


Answer:

Sure is, though without having to go through XML. Pass the number of players to the next activity as an argument. Then make sure you have a ViewGroup (LinearLayout for example) in the second activity's layout.

Then loop through and create the Views dynamically:

ViewGroup container = findViewById(R.id.linearLayout);

for( int i = 0; i < numberOfPlayers; i++ ){
    EditText et = new EditText(this);
    et.setHint(R.string.new_player_hint);// String providing a hint to the user
    container.addView(et);
}

You can put the EditTexts in a List or if that's all you'll have you can directly cycle over the ViewGroup's children to get their values later on:

for( int i = 0; i < container.getChildCount(); i++ ){

    String playerName = ((EditText) container.getChildAt(i)).getText().toString();

}

If you're going to have many possible players you should wrap the LinearLayout in a ScrollView.

Because you'll likely use this in onCreate remember that you can't rely on the EditText to save its own data in case the Activity is destroyed, so save them yourself and feed them back in when re-creating.

Question:

I want to create a simple application on Android Studio that can compute the Mean or the Average of the data. The thing is I will only use one EditText to input Multiple set of data.

This is my example

So in the picture shown above when I click the result button the average of the numbers that I input in the edittext will be display to the MeanTextView. I do have my codes to compute for the Mean or the average. Here is my code:

public static double mean(double[] m){
double sum = 0;
for (int i = 0; i<m.length; i++){
sum + = m[i];
}
return sum / m.length;
}

So how can I input Multiple set of data in one EditText separated only by a comma that I can use to compute for the average?


Answer:

Make use of android.text.TextUtils

for eg:

double[] doubleList = new double[2];
doubleList[1] = 1221312312;
doubleList[2] = 1231231231;

List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);

List<String> stringList = new ArrayList<>();
stringList.add("2");
stringList.add("3");

final String doubleSeparateCommaString =
  android.text.TextUtils.join(",", new double[][] { doubleList });

final String intSeparatedCommaString = android.text.TextUtils.join(",", intList);

final String stringSeparatedCommaString =  android.text.TextUtils.join(",", stringList);

hoping it may help you.

Question:

I'm in the beginning of my learning how to make apps. I want to make an app which should display randomized inputted tasks to do for the user. Firstly user should choose how many tasks would like to create and then write down tasks in EditText. I am able to create particular amount of EditText but I have no clue how to display all EditText input after pressing button. I have many versions of the code but non of them work. I got stuck and I need advice.

Here is one of my code version for the second activity.

public class TaskActivity extends AppCompatActivity {

LinearLayout containerLayout;
TextView receiverTV;
TextView tv;
TextView displayTaskTv;

EditText et;

Button btn;
Button randomTaskBtn;

int i = 0;
int size;

String inputEditText;
String inputTextView;

String stringsEt[];
String stringsTv [];


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task);
    containerLayout = (LinearLayout) findViewById(R.id.linear_layout);


    receiverTV = (TextView) findViewById(R.id.receiver_textView);


    Intent intent = getIntent();
    int number = intent.getIntExtra("Number", defaultValue);
    receiverTV.setText("You have chosen to add: " + number + " tasks!");

    createEtTvBtn(number);
    createBtn();
    createTextView();

}

public void createEtTvBtn(int number) {

    for (i = 1; i <= number; i++) {
        tv = new TextView(this);
        tv.setText("Task nr: " + i);
        tv.setPadding(16, 16, 16, 16);
        tv.setTextColor(Color.parseColor("#008b50"));
        tv.setTextSize(20);
        tv.setId(i + value);
        containerLayout.addView(tv);


        et = new EditText(this);
        et.setHint("Enter task nr: " + i);
        et.setId(i + value);
        et.setLines(2);
        containerLayout.addView(et);

        btn = new Button(this);
        btn.setText("Confirm task nr: " + i);
        btn.setId(i + value);
        containerLayout.addView(btn);

        final List<EditText> allEditText = new ArrayList<EditText>();
        final List<TextView>allTextView = new ArrayList<TextView>();
        final List<Button>allButton = new ArrayList<Button>();

        String[] stringsEditText = new String[(allEditText.size())];
        String[] stringsTextView = new String[(allTextView.size())];
        String[] stringsBtn = new String[(allButton.size())];


        for(int i=0; i < allEditText.size(); i++){
            stringsEditText[i] = allEditText.get(i).getText().toString();

        }
        for (int i=0; i < allTextView.size(); i++) {
            stringsTextView[i] = allTextView.get(i).getText().toString();
            size = allTextView.get(i).getText().toString().length();
        }
        for(int i=0; i < allButton.size(); i++){
            stringsBtn[i] = allButton.get(i).getText().toString();

        }

        allTextView.add(tv);

        allEditText.add(et);

        allButton.add(btn);

        allButton.get(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                inputEditText = allEditText.get(0).getText().toString();
                stringsEt = new String[] {allEditText.get(0).getText().toString()};


                if (inputEditText.length() > 0) {
                allTextView.get(0).setText(inputEditText);

                    allEditText.add(allEditText.get(0));
                    allEditText.get(0).setText("");

                    }
                    else if (inputEditText.length() ==0){
                    Toast.makeText(TaskActivity.this, "You need to write down your task", Toast.LENGTH_LONG).show();
                    }
                inputTextView = allTextView.get(0).getText().toString();
                stringsTv = new String[] {allTextView.get(0).getText().toString()};
                if (inputTextView.length() > 0) {
                    allTextView.get(0).getText();
                    allTextView.add(allTextView.get(0));
                }
            }
        });

    }
}

    private Button createBtn() {
    randomTaskBtn = new Button(this);
    randomTaskBtn.setText("Task");
    containerLayout.addView(randomTaskBtn);

        randomTaskBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            double luckyTask = Math.random();
            luckyTask *=size;
            int luckyIndex = (int)luckyTask;
            displayTaskTv.setText(stringsTv[luckyIndex]);
                }
        });
        return randomTaskBtn;

            }
    private TextView createTextView() {
    displayTaskTv = new TextView(this);
    displayTaskTv.setTextSize(20);
    displayTaskTv.setTextColor(Color.parseColor("#dd2626"));
    displayTaskTv.setText("");
    containerLayout.addView(displayTaskTv);
        return displayTaskTv;

}

}

Thank you for any constructive advices.

I am sure my code is big mess. I wanted to created more methods but I didn't succeed.


Answer:

This is what you should do

Step 1 - Create multiple EditTexts and store each one of them in an ArrayList say myEditTextList.

Step 2- Take data from all edit texts

String str = ""
for(EditText et: myEditTextList) {
   str += et.getText().toString();
}

Step 3- Display data in str wherever you want.

Question:

I have an editText in android and i'ld like to listen for when an input or text has been added.

i am setting the text dynamically and i want a situation where once that is done, a new event is triggered.

 code.setText(savedcode);

code.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    Toast.makeText(Verification.this, "New Input" , Toast.LENGTH_SHORT ).show();
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });

i've used the text watcher but it doesn't trigger event when input is set dynamically unless i edit the field then it does. i know in javascript, on input listener can do that so i'm looking for its android equivalent. Thank you


Answer:

Well, the thing is that your code seems to be correct, the one thing that is done wrong is the order.

Practically,you want to know when the textView's text has changed,but you change it before adding a text to it.

So the logical way to go is this:

TextView TV;

TV = (TextView) rootView.findViewById(R.id.theID);

TV.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Toast.makeText(Verification.this, "New Input" , Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

TV.setText(savedcode);

This way, you change the text once you actually have a listener there, not before.That should fix your problem.

P.S: I am not sure how you declare your textView, don't mind the variables name, no inspiration at this moment.

Question:

I am currently working on this activity (class ChallengeNew52) wherein I have a set of RadioGroup. In this RadioGroup, I have an EditText (id.etGoalNew) that is under a RadioButton (id.rButtonwithGoal).

When this RadioButton is checked (active), it is suppose to enable the user to access/type in the EditText and also display what they typed to another activity. I think I accomplished the enabling part but the problem now is displaying it to another activity (class challengetab). I can't seem to display the string correctly from this EditText under this particular RadioButton. The (endlessMode) that is in another case in this "Switch" is displaying.

The code doesn't give an error, the app launches fine yet the it doesn't display what I want. Hope you can check what is the conflict or with the coding.

Here is the code from that activity:

import android.content.Intent;
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;

public class ChallengeNew52 extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

RadioGroup rgInputNew;
EditText etGoalNew;
EditText moIncome;
EditText etGoalNumber;
String challengetitle;
String resultString;
String goalTitle;

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

    //Strings
    final String saveTitle = getResources().getString(R.string.ctabtitle_fiftytwo);

    //Radio Group Enable EditText (goal) input
    rgInputNew = (RadioGroup) findViewById(R.id.rgGoal);
    rgInputNew.setOnCheckedChangeListener(ChallengeNew52.this);

    // EditTexts
    moIncome = (EditText) findViewById(R.id.inputIncomeBar52);
    etGoalNumber = (EditText) findViewById(R.id.inputGoalNumber52);
    etGoalNew = (EditText) findViewById(R.id.inputGoalBar52);
    actv(false);

    // Button Call
    Button startSaving = (Button) findViewById(R.id.buttonStartSaving);

    /*
    BUTTON CLICK!
     */
    startSaving.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //--Call Equation
            mathFiftyTwo();

            //--To Display to Another Activity ("challengetab" java)
            Intent iStartSaving = new Intent(getApplicationContext(), challengetab.class);

            iStartSaving.putExtra("resultShow", resultString);
            iStartSaving.putExtra("goalName", goalTitle);
            iStartSaving.putExtra("titleChallenge", challengetitle);
            iStartSaving.putExtra("resultShow", resultString);

            ChallengeNew52.this.startActivity(iStartSaving);
        }
    });//--onClickListener

    //--Call outs for the string Challenge Title
    challengetitle = saveTitle;
}//--onCreate

//--To activate Edit Text with Radio Select. (METHOD)
@Override
public void onCheckedChanged (RadioGroup rgInputNew, int rButtonWithGoal) {
    //--String
    final String endlessMode = getResources().getString(R.string.ctabnogoal);

    switch (rButtonWithGoal) {
        case R.id.rButtonWithGoal:
            actv(true);
            dsply(true);
            break;

        case R.id.rbEndlessSaving:
            actv(false);
            //--Call outs for the string Endless Saving Mode
            goalTitle = endlessMode;

            break;
    }
}//--end onCheckedChanged

//--display text method for goalTitle
private void dsply (final boolean active) {
    //--Strings
    final String goalNew = etGoalNew.getText().toString();

    etGoalNew.setEnabled(active);
    if (active) {
        goalTitle = goalNew;
    }
}

//--actv method for activating of Radio Button's EditText
private void actv(final boolean active) {

    etGoalNew.setEnabled(active);
    if (active) {
        etGoalNew.requestFocus();
    }
    etGoalNumber.setEnabled(active);
    if (active) {
        etGoalNumber.requestFocus();
    }
}
 }//--End class

Here is how I coded the other activity:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class challengetab extends AppCompatActivity {

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

        //TextView for Goals
        TextView goalView = (TextView)findViewById(R.id.cGoalName);
        goalView.setText(getIntent().getExtras().getString("goalName"));

        //TextView for Computation

        TextView resultView = (TextView)findViewById(R.id.cValueSave);
        resultView.setText(getIntent().getExtras().getString("resultShow"));

        // Text View for Title

        //TextView: Receive Challenge Title when button is clicked
        TextView incomeView = (TextView)findViewById(R.id.cTitleChallenge);
        incomeView.setText(getIntent().getExtras().getString("incomeTitle"));
        incomeView.setText(getIntent().getExtras().getString("titleChallenge"));
    }
}

Answer:

You are never getting the final value from the EditText named etGoalNew after the user is done populating it.

Try doing this in the click listener when you are setting up the Intent for the "goalName" extra:

if(rgInputNew.getCheckedRadioButtonId() == R.id.rButtonWithGoal) {
    iStartSaving.putExtra("goalName", etGoalNew.getText().toString());
} else {
    iStartSaving.putExtra("goalName", goalTitle);
}

Question:

i'm trying to print the value of input of Activity 1 (class first) in the view.loadurl() of Activity (class MainActivity).

Here is my code:

Activity 1:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/urlYoutube"
    android:layout_marginTop="95dp"
    android:layout_below="@+id/textView"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:hint="@string/guia_txt"  />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn_download"
    android:id="@+id/button"
    style="@style/AppTheme"
    android:textSize="23sp"
    android:textStyle="normal"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

first.java:

 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int str = R.id.urlYoutube;
            Intent launchResult = new Intent(first.this, MainActivity.class);
            launchResult.putExtra("dato", str);
            startActivity(launchResult);
        }
    });

MainActivity.java:

    WebView view = (WebView) this.findViewById(R.id.webkit);
    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setBuiltInZoomControls(false);
    view.getSettings().setSupportZoom(false);
    view.setWebViewClient(new MyBrowser());

    Bundle extras = getIntent().getExtras();
    int str = extras.getInt("dato");
    String s = "http://myurl.com/get.php?id=" + Integer.toString(str);
    view.loadUrl(s);

This everytime print the same value.

What this print: http://myurl.com/get.php?id=2131492970

Can help me?

Thanks in advice.


Answer:

I'm assuming you want to get the string inside that urlYoutube, right? for the EditText:

create the view like mUrlYoutube (or wherever):

mUrlYoutube = (EditText) findViewById(R.id.urlYoutube);

String str = mUrlYoutube.getText().toString();

What you're doing right now is to get the Resource ID int value from R ones the compiler does all the work.

When you have a resource, you must call it this way:

String str = getResource().getString(R.string.urlYoutube);

if int:

int str = getResource().getInteger(R.integer.urlYoutube);

Question:

I have an EditText where the user can put in a desired amount of products.

Now what i wish to do is, that the EditText input starts from the end and fills up to the beginning.

Example:

Amount: _ _ _ _ 4 5

and not

Amount: 4 5 _ _ _ _

The _ _ _ should demonstrate the EditText.

Thanks in advance.


Answer:

Set android:gravity="end"

<EditText
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:gravity="end"
     android:hint="type here" />

You can use

android:textDirection="rtl" // Works if you set MIN API level 17

Question:

I have one edittext and for example I put in12345. I want to check if the first two numbers' sum is >0 then do something. I don't know how to check first two elements' sum.

if(pirinfouserid.getText().toString().indexOf(2)>0)
        Toast.makeText(getApplicationContext(), "ok",
                Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(getApplicationContext(), "wrong",
                Toast.LENGTH_SHORT).show();

If anyone knows a solution please help me

Thanks


Answer:

int num1=Integer.parseInt(pirinfouserid.getText().toString().charAt(0));
int num2=Integer.parseInt(pirinfouserid.getText().toString().charAt(1));
int sum=num1+num2;
if(sum>0)
    Toast.makeText(getApplicationContext(), "ok",
            Toast.LENGTH_SHORT).show();
else
    Toast.makeText(getApplicationContext(), "wrong",
            Toast.LENGTH_SHORT).show();

Question:

I have one edittext and for example I put in12345. I want to check if the first two numbers' sum is >0 then do something. I don't know how to check first two elements' sum.

if(pirinfouserid.getText().toString().indexOf(2)>0)
        Toast.makeText(getApplicationContext(), "ok",
                Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(getApplicationContext(), "wrong",
                Toast.LENGTH_SHORT).show();

If anyone knows a solution please help me

Thanks


Answer:

int num1=Integer.parseInt(pirinfouserid.getText().toString().charAt(0));
int num2=Integer.parseInt(pirinfouserid.getText().toString().charAt(1));
int sum=num1+num2;
if(sum>0)
    Toast.makeText(getApplicationContext(), "ok",
            Toast.LENGTH_SHORT).show();
else
    Toast.makeText(getApplicationContext(), "wrong",
            Toast.LENGTH_SHORT).show();

Question:

I'm new to OOP, but I've had experience with C previously. I'm learning Java and working on building an app slowly. I find I learn more when I apply what I've read and learned from other sources to projects.

The problem I've been facing for a while now is in regard to returning values users have inputted into EditText fields and using those values to run some calculations. Here is my code:

public class Linmotion extends Activity {
// Creating the variables
EditText time, acc, dis, ivel, fvel;
Button solve;
int count = 0;
double time1,acc1,dis1,ivel1,fvel1;


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

    time = (EditText) findViewById(R.id.EditText01);
    acc = (EditText) findViewById(R.id.EditText02);
    dis = (EditText) findViewById(R.id.EditText03);
    ivel = (EditText) findViewById(R.id.EditText04);
    fvel = (EditText) findViewById(R.id.EditText05);
    solve = (Button) findViewById(R.id.buttonSolve);

    //Trying to return inputted values
    /*
    if (!(time.getText() == null)) {
        time1=Double.parseDouble(time.getText().toString());
    }
    if(!(acc.getText()==null)){
        acc1=Double.parseDouble(acc.getText().toString());
    }
    if(!(ivel.getText()==null)){
        ivel1=Double.parseDouble(ivel.getText().toString());
    }
    if(!(fvel.getText()==null)){
        fvel1=Double.parseDouble(fvel.getText().toString());
    }s
    if(!(dis.getText()==null)){
        dis1=Double.parseDouble(dis.getText().toString());
    }
    /*
     * Double.parseDouble(time.getText().toString());
     * Double.parseDouble(acc.getText().toString());
     * Double.parseDouble(ivel.getText().toString());
     * Double.parseDouble(fvel.getText().toString());
     * Double.parseDouble(dis.getText().toString());
     */



    // add button listener
    solve.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (time1 < 0) {
                count++;
                if (acc1 < 0) {
                    count++;
                }
                if (ivel1 < 0) {
                    count++;
                }
                if (fvel1 < 0) {
                    count++;
                }
                if (dis1 < 0) {
                    count++;
                }
                if (count > 2) {
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                            Linmotion.this);
                    final AlertDialog alert = alertDialog.create();
                    alert.show();
                    alertDialog.setTitle("Error");
                    alertDialog
                            .setMessage("Please input values into at least 3 fields");
                    alertDialog.setPositiveButton("OK",new DialogInterface.OnClickListener() {

                                // function of dialog button

                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    alert.cancel();
                                }
                            });

                }

            }

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.linmotion, menu);
    getActionBar().setDisplayShowTitleEnabled(false);
    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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

The if statements and the other Double.parseDouble lines have been commented out because every time I try to debug the code the app crashes the instant Linmotion is created. I suspect its from the fact that onCreate runs the Double.parseDouble code and the values in the field are null. I tried to fix this with the if statements and it still crashes. I'm not sure where to go from here.

Again, if I wasn't clear I just want the values inputted into the EditText to return a double and then use that double in the Java code to run some equations and an alert dialog if not enough fields have been filled in.

EDIT/UPDATE: I finally figured out what was wrong with my code. I took in advice from everyone and revised accordingly, so here it is:

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

    time = (EditText) findViewById(R.id.eTexttime);
    acc = (EditText) findViewById(R.id.eTextacc);
    dis = (EditText) findViewById(R.id.eTextdis);
    ivel = (EditText) findViewById(R.id.eTextivel);
    fvel = (EditText) findViewById(R.id.eTextfvel);
    solve = (Button) findViewById(R.id.buttonSolve);    
    solve.setOnClickListener(new OnClickListener() {

        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {
            count=0;
            if (time.getText().toString().equals("")){
                count++;
            }
                    if(dis.getText().toString().equals("")){
                        count++;
                    }
                        if(fvel.getText().toString().equals("")){
                            count++;
                        }
                            if(ivel.getText().toString().equals("")){
                                count++;
                            }
                                if(acc.getText().toString().equals("")){
                                    count++;
                                }

            if (count>2){
            // TODO Auto-generated method stub
            final AlertDialog alert= new AlertDialog.Builder(Linmotion.this).create();
            alert.setTitle("Oops");
            alert.setMessage("Please input values in at least 3 fields.");
            alert.setButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                    alert.cancel();
                }
            });
            alert.show();
            count=0;
        }
            if(!(time.getText().toString().equals(""))){
                time1=Double.parseDouble(time.getText().toString());

            }
            if(!(acc.getText().toString().equals(""))){
                acc1=Double.parseDouble(acc.getText().toString());

            }
            if(!(dis.getText().toString().equals(""))){
                dis1=Double.parseDouble(dis.getText().toString());

            }
            if(!(ivel.getText().toString().equals(""))){
                ivel1=Double.parseDouble(ivel.getText().toString());

            }
            if(!(fvel.getText().toString().equals(""))){
                fvel1=Double.parseDouble(fvel.getText().toString());

            }


        }       });



} 

In regard to the issues I had with the alertdialog I realized that my count integer would continue to increase every time the solve button was clicked. To fix this I simply equaled the integer to 0 at the beginning of the onclicklistener and at the end of the if statement regarding the dialog. Thanks everyone.


Answer:

It looks to me like you're doing it right. I think the problem might be that it's in your OnCreate method.

Try making the Button Solve's OnClick method run your commented code before doing the logic!

Question:

I have 2 groups of radio buttons. And I want to make when btn1stDigitBrown1 of 1st group is pressed it shows on display "1" just as it is in code below and when btn2ndDigitBlack0 from 2nd group is pressed it should also show one number next to the number that was just written on EditText, for example, "10". And when the button of the 2nd group is pressed (for example btn2ndDigitBlack0) before button from 1st group is pressed, it should automatically show on EditText "10". For now, when RadioButton from the 2nd group is pressed it rewrites number written already on EditText. This is my code:

    View.OnClickListener listener1stDigit = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn1stDigitBrown1:
                    ((EditText)findViewById(R.id.resistText)).setText("1");
                    break;
                case R.id.btn1stDigitRed2:
                    ((EditText)findViewById(R.id.resistText)).setText("2");
                    break;
                case R.id.btn1stDigitOrange3:
                    ((EditText)findViewById(R.id.resistText)).setText("3");
                    break;
                case R.id.btn1stDigitYellow4:
                    ((EditText)findViewById(R.id.resistText)).setText("4");
                    break;
                case R.id.btn1stDigitGreen5:
                    ((EditText)findViewById(R.id.resistText)).setText("5");
                    break;
                case R.id.btn1stDigitBlue6:
                    ((EditText)findViewById(R.id.resistText)).setText("6");
                    break;
                case R.id.btn1stDigitViolet7:
                    ((EditText)findViewById(R.id.resistText)).setText("7");
                    break;
                case R.id.btn1stDigitGrey8:
                    ((EditText)findViewById(R.id.resistText)).setText("8");
                    break;
                case R.id.btn1stDigitWhite9:
                    ((EditText)findViewById(R.id.resistText)).setText("9");
                    break;
                default:
            }
        }
    };

    btn1stDigitBrown1.setOnClickListener(listener1stDigit);
    btn1stDigitRed2.setOnClickListener(listener1stDigit);
    btn1stDigitOrange3.setOnClickListener(listener1stDigit);
    btn1stDigitYellow4.setOnClickListener(listener1stDigit);
    btn1stDigitGreen5.setOnClickListener(listener1stDigit);
    btn1stDigitBlue6.setOnClickListener(listener1stDigit);
    btn1stDigitViolet7.setOnClickListener(listener1stDigit);
    btn1stDigitGrey8.setOnClickListener(listener1stDigit);
    btn1stDigitWhite9.setOnClickListener(listener1stDigit);

    View.OnClickListener listener2ndDigit = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn2ndDigitBlack0:
                    ((EditText)findViewById(R.id.resistText)).setText("0");
                    break;
                case R.id.btn2ndDigitBrown1:
                    ((EditText)findViewById(R.id.resistText)).setText("1");
                    break;
                case R.id.btn2ndDigitRed2:
                    ((EditText)findViewById(R.id.resistText)).setText("2");
                    break;
                case R.id.btn2ndDigitOrange3:
                    ((EditText)findViewById(R.id.resistText)).setText("3");
                    break;
                case R.id.btn2ndDigitYellow4:
                    ((EditText)findViewById(R.id.resistText)).setText("4");
                    break;
                case R.id.btn2ndDigitGreen5:
                    ((EditText)findViewById(R.id.resistText)).setText("5");
                    break;
                case R.id.btn2ndDigitBlue6:
                    ((EditText)findViewById(R.id.resistText)).setText("6");
                    break;
                case R.id.btn2ndDigitViolet7:
                    ((EditText)findViewById(R.id.resistText)).setText("7");
                    break;
                case R.id.btn2ndDigitGrey8:
                    ((EditText)findViewById(R.id.resistText)).setText("8");
                    break;
                case R.id.btn2ndDigitWhite9:
                    ((EditText)findViewById(R.id.resistText)).setText("9");
                    break;
                default:
            }
        }
    };

    btn2ndDigitBlack0.setOnClickListener(listener2ndDigit);
    btn2ndtDigitBrown1.setOnClickListener(listener2ndDigit);
    btn2ndDigitRed2.setOnClickListener(listener2ndDigit);
    btn2ndDigitOrange3.setOnClickListener(listener2ndDigit);
    btn2ndDigitYellow4.setOnClickListener(listener2ndDigit);
    btn2ndDigitGreen5.setOnClickListener(listener2ndDigit);
    btn2ndDigitBlue6.setOnClickListener(listener2ndDigit);
    btn2ndDigitViolet7.setOnClickListener(listener2ndDigit);
    btn2ndDigitGrey8.setOnClickListener(listener2ndDigit);
    btn2ndDigitWhite9.setOnClickListener(listener2ndDigit);

Answer:

I think what you need to do is to learn how to manipulate strings You should read this

What you should do in the 2nd listener is concatenate the new number

switch (view.getId()) {
     case R.id.btn2ndDigitBlack0: {
         EditText editText = ((EditText)findViewById(R.id.resistText))
         String oldString = editText.getText()
         if (oldString.length <= 1) {
            editText.setText(oldString + "0")
         } else {
             editText.setText(oldString.substring(0, 1) + "0")
         }
         }
     ...

Question:

I want to manually (i.e. from the numeric keyboard) input date in dd-mm-yyyy format in an edittext field. Also to assign three integer variables, day, month, year for another calculation in such a way that the first two characters (i.e. index 0, 1) be the day variable then automatically add a separator ("-' or "/") then next two digit should be month variable then an automated separator like before and finally year. The day and month should display as two digit with leading zero (if necessary). Also if the user enter 4-9 in day field at index zero(0) it automatically convert it into two digit and move to month field, also for month 2-9 make that two digit and move to year. Finally when the input process completes move the cursor to next edittext field. I apologize for my poor English. Any kind of help will be appreciated. Thanks in advance.


Answer:

You can use this. Certain edge cases are not handled. Do those.

 private static final char SEPERATOR = '-';

    private void automateDateEntry() {
        dateEditText.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 10) {
                    charSequence = charSequence.subSequence(0, 10);
                    dateEditText.removeTextChangedListener(this);
                    dateEditText.setText(charSequence);
                    dateEditText.addTextChangedListener(this);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String currText = editable.toString();
                if(currText.isEmpty())
                    return;
                int separatorCount = getOcurrence(currText, SEPERATOR);

                if (currText.charAt(currText.length() - 1) == SEPERATOR) {
                    return;
                }
                int lastSeperatorPos = currText.lastIndexOf(SEPERATOR);
                String previousTxt = null;
                if (lastSeperatorPos > -1) {
                    previousTxt = currText.substring(0, lastSeperatorPos + 1);
                    Log.d("curr text", currText);
                    currText = currText.substring(lastSeperatorPos + 1);
                }

                if (!currText.isEmpty()) {
                    switch (separatorCount) {
                        case 0:
                            int date = Integer.parseInt(currText);
                            if (date < 0 || date > 31) {
                                dateEditText.setError("Enter proper date");
                                return;
                            }
                            if (currText.length() == 2 || date >= 4) {
                                currText = String.format(Locale.getDefault(), "%02d", date);
                                currText += SEPERATOR;
                            }
                            break;
                        case 1: int month = Integer.parseInt(currText);
                            if (month < 0 || month > 31) {
                                dateEditText.setError("Enter proper month");
                                return;
                            }
                            if (currText.length() == 2 || month >= 2) {
                                currText = String.format(Locale.getDefault(), "%02d", month);
                                currText += SEPERATOR;
                            }
                            break;
                        case 2: int year = Integer.parseInt(currText);
                            if (year < 0 ) {
                                dateEditText.setError("Enter proper year");
                                return;
                            }
                            break;
                    }
                }
                if(previousTxt != null){
                    currText = previousTxt + currText;
                }
                dateEditText.removeTextChangedListener(this);
                dateEditText.setText(currText);
                int textLength = currText.length();
                dateEditText.setSelection(textLength, textLength);
                dateEditText.addTextChangedListener(this);
            }
        });
    }

    private int getOcurrence(String string, char ch) {
        int count = 0;
        int len = string.length();
        for (int i = 0; i < len; i++) {
            if (string.charAt(i) == ch)
                ++count;
        }
        return count;
    }

Question:

I'm just starting to learn android app development as well as java, and I'm a bit confused how to get this to work. I created user input fields in the UI with the following tablelayout:

    public void inputRow( TableLayout tl, String label, int inputSize, int inputID )
    {
        TableRow inputRow = new TableRow(this);
        TextView tv = new TextView(this);
        EditText edit = new EditText(this);

        // some margin
        inputRow.setPadding( 20,10,20,0);
        tv.setText(label);
        edit.setMaxWidth( inputSize*7)  ;
        edit.setMinimumWidth(inputSize*7);
        edit.setId( inputID );
        edit.setGravity(Gravity.RIGHT);
        inputRow.addView(tv);
        inputRow.addView(edit);

        tl.addView(inputRow);
    }

I then filled out the inputRows with the following:

inputRow( myTableLayout, "Name", 30, 10000);
inputRow( myTableLayout, "Last Name", 20, 10001);
inputRow( myTableLayout, "Age", 3, 10002);
inputRow( myTableLayout, "Street Address", 20, 10003);
inputRow( myTableLayout, "State", 15, 10004);

Created the button

 Button btAccept = new Button(this);
        btAccept.setText( "Save");
        btAccept.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v)
            {

                alertDialog.show();

            }
        });

And the alert dialogue:

final AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Save");
alertDialog.setMessage("Saved..");

Rather than just displaying "Saved.." in the alert dialogue, how do I get it to display the actual info the user submitted once they click the button? While I have the id's set for each input row, I'm unsure how to actually retrieve them. Would it make the most sense for me to also place all the input within an aray to then display?

EDIT I've been searching online for possible solutions and thought maybe I need to look at each TableRow from myTableLayout.

TableRow row1 = (TableRow)myTableLayout.getChildAt(0);
TextView tv1 = (TextView) row1.getChildAt(0);
String input = tv1.getText().toString(); 

I figured that maybe I would be able to access the first row from my table to retrieve the textview output. However it still doesn't work. I really thought I could perhaps access each line with the id I've set with each editText, but nothing I'm trying works.


Answer:

Create an ArrayList of EditText in your class and put editText objects in it while creating row.

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

inside inputRow(.....) method

//your code
EditText edit = new EditText(this);
editTextList.add(edit);

Get Text of every input from arrayList and display it in alert dialog:

String message = "Saved: ";
for(EditText edit:editTextList) {
   message+=edit..getText().toString()+" ";
}
alertDialog.setMessage(message);

Question:

I have two editText boxes. In the editText boxes I have by default 0.0 and behind a hint and I have a OnFocusChangeListener.

Every time I tap the editText box to put a value in, the 0.0 disappear and the hint is visible and the box wait for input, which is OK.

But if I change my mind and change to the second editText box(without input to editText box 1) there is just the hint visible in box 1 but i want the value 0.0 to come back if there was no input.

final EditText text_box2;
text_box2 = (EditText) findViewById(R.id.fillingPressure);
text_box2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (text_box2.getText().toString().compareTo("0.0") == 0) {
                text_box2.setText("");
            }
        }
    }
});

final EditText text_box1;
text_box1 = (EditText) findViewById(R.id.tankVolume);
text_box1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (text_box1.getText().toString().compareTo("0.0") == 0) {
                text_box1.setText("");
            }
        }
    }
});
//

Answer:

Your Code:

    final EditText text_box2;
    text_box2 = (EditText) findViewById(R.id.fillingPressure);
    text_box2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (text_box2.getText().toString().compareTo("0.0") == 0) {
                text_box2.setText("");
            }
        }
    }
});

final EditText text_box1;
text_box1 = (EditText) findViewById(R.id.tankVolume);
text_box1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (text_box1.getText().toString().compareTo("0.0") == 0) {
                text_box1.setText("");
            }
        }
    }
});

Try this:

        text_box2 = (EditText) findViewById(R.id.fillingPressure);
        input2 = String.valueOf(text_box2.getText());
        text_box2.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if ((hasFocus)&&(input2.equals("0.0") || input2.equals(""))) {
                        text_box2.setText("");
                }
                input2 = (String.valueOf(text_box2.getText()));
                if ((!hasFocus) && (input2.equals(""))){
                    text_box2.setText("0.0");
                }
            }
        });

        text_box1 = (EditText) findViewById(R.id.tankVolume);
        input1 = String.valueOf(text_box1.getText());
        text_box1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if ((hasFocus)&&(input1.equals("0.0") || input1.equals(""))) {
                    text_box1.setText("");
                }
                input1 = (String.valueOf(text_box1.getText()));
                if ((!hasFocus) && (input1.equals(""))){
                    text_box1.setText("0.0");
                }

            }
        });

Now you need to declare your variables outside of the onCreate method like this:

public class YourClass extends Activity {
    String input1, input2;
    EditText text_box1, text_box2;
    // onCreate method here

Finally, make sure both your EditText values are set in your .xml to "0.0"

The reason you want to declare the variables outside of the onCreate() method is to avoid making them final. If the variables are final, the value would never change from "0.0".

Let me know if you have any more questions.