Hot questions for Using Android EditText in string

Question:

I have an EditText, a TextView and a Button. I want to check whether the string from EditText is too big or not to fit the TextView, if not I want to append "..." to the string, so if I write "That's a nice coat" and that's too big to fit in the TextView it shows "That's a ni...". I can't add more lines to the TextView to make it fit.


Answer:

Just use maxLines=1 and ellipsize=end in your TextView

if in code, use mText.setEllipsize(TextUtils.TruncateAt.END)

Question:

I'm trying to format the input value of an EditText in Android, I want to format the input in currency value, I' ve tried the following:

EditText minimo = (EditText) view.findViewById(R.id.minimo);

Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

 Locale locale = new Locale("en", "UK");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

    minimo.setText("", TextView.BufferType.valueOf(String.valueOf(fmt.format(TextView.BufferType.EDITABLE))));

Log:

java.lang.IllegalArgumentException: Bad class: class android.widget.TextView$BufferType

Answer:

try this :

set TextChangedListner as :

minimo.addTextChangedListener(new NumberTextWatcher(minimo));

create custom TextWatcher as:

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";

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

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

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

Question:

I have a ٍstring of math numbers and I just want to put a comma in the numbers only for example:

String s="(1000+2000000-5000.8÷90000+√5×80000)";

I want to send it to a method to convert it to

String s="(1,000+2,000,000-5,000.8÷90,000+√5×80,000)";

i am using :

DecimalFormat myFormatter = new DecimalFormat("$###,###.###");
String output = myFormatter.format(s);
System.out.println(output);

But get it error because there are operator '+-..'


Answer:

Isn't a simple approach using Matcher.appendReplacement enough?

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

....

static String formatMyString(String input){
    DecimalFormat myFormatter = new DecimalFormat("###,###.###");
    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile("(\\d+\\.*\\d+)");
    Matcher m = p.matcher(input);
    while(m.find()){
        String rep = myFormatter.format(Double.parseDouble(m.group()));
        m.appendReplacement(sb,rep);            
    }
    m.appendTail(sb);
    return sb.toString();
}

Question:

I have all my strings for my project stores in the string.xml file. I have no problem using them in most cases but for some reason it outputs an integer value to the editText when I mix Strings with an integer for example if I do:

editText.setText(R.string.x_plays + j)

which I want to display "X Plays: 3" to the GUI however it displays a large integer to the GUI. If I do this without j (which is an integer) it is fine.

editText.setText(R.string.x_plays)

This just displays the string "X Plays: ".

So the problem is obviously trying to concatenate an integer with an R.string but I don't know how to work around this. I have tried using stringBuilder and adding in empty strings ("") around the R.string and integer but similar results are returned. How can I fix this?


Answer:

The reason why this happens is because R.string.x_plays is actually an integer resource ID that certain methods are able to convert into a string that can be displayed. One of these is setText. However, if you add a number to this ID, it may no longer be valid.

The easiest solution is to just write getString(R.string.x_plays) + j.

You could also change the string to a format string, such as X plays: %1$d and instead write getString(R.string.x_plays, j)

See: String Resources

Question:

I have an EditText in my app which users can enter a youtube url.

Example url is like following:

https://www.youtube.com/watch?v=gXrWv6zlg8s

When i grab the text and make it to a string, i only need the last chars like gXrWv6zlg8s

How can i shorten the string value to only this charset?

final EditText url = findViewById(R.id.url);
b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String a;
            a = url.getText().toString().trim();}
}

Thanks for advice.


Answer:

String url= "https://www.youtube.com/watch?v=gXrWv6zlg8s";
System.out.println(url.substring(url.lastIndexOf("=") + 1));

Question:

Is it possible to hide part of a string in the editText with a method like

editText.hide(int start, int finish);

so that in the display I can't read the hidden part of the string, but if I use a method like editText.getText() in the code, it will include the hidden string?


Answer:

You can do something like:

String wholeString = editText.getText().toString();
editText.setText(editText.getText().toString().substring(int start, int end));

where start and end are integers that you want your string to begin and end at the positions you set.

So now you have the whole string before it was hidden. Additionally, if you want to hide a certain part in the middle of your editText, you can do something like this:

editText.setText(editText.getText().toString().substring(0, 20) + editText.getText().toString().substring(25, 30));

where you set your editText text with many strings. This will hide the string from position 21 till 25. You have to modify it according to your needs.

You may also need to know a method for a string called lastIndexOf("Some Text")

Example:

//You have a string called example.
String example = "Android development is fun and nice."
String cutExample = example.substring(example.lastIndexOf("is") +3, example.lastIndexOf(".");

The result will be: "fun and nice".

So lastIndexOf() will return the position of the defined string.

Test with what I wrote. Hope that helps.

Question:

I want the user to put in characters into an edit text and upon a keyUp() would change a textview to match a certain char from a string.

If a user put in 4 characters in the edittext string, then the index of 3 of the string would be set for the textview.

The problem is that the program crashes when checking the 0th index of the string. This log command gives me the proper output,

            String thedefaultstring = "Hello Android";
            //e_question is the edit text
            int stringsum = e_question.getText().toString().length();
            System.out.println(thedefaultstring.charAt(stringsum));

But when I set the textview with the char, it crashes.

// t_debug3.setText(thedefaultstring.charAt(0)); //crashes

Answer:

Try:

setText(new String(thedefaultstring.charAt(stringSum));

setText takes a String as an argument. Build a new String of only one char to trick it.

Question:

So, I have an EditText view and my idea is on a, lets say for now, touch event to select and copy the touched word into clipboard memory. So far I can set Selection through offset, but it is only "", because getSelectionStart() = getSelectionEnd() = offset. How can I extend it until the next encountered whitespace or end/start of text.

How could I extend one such selection in the above described manner?

Code so far:

@Override
public boolean onTouch(View v, MotionEvent event)
{
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        float x = event.getX() + getScrollX();
        int offset = getOffset(event);
        if(offset != Integer.MIN_VALUE){
                setSelection(offset);
                String selectedText = getText().toString()
                            .substring(getSelectionStart(), getSelectionEnd());

                   //TODO: extend selection otherwise copies ""

                putInClipMemory(selectedText);
        }
    return true;
} 

Thanks.


Answer:

You should be able to calculate the index of the next space after your start selection index and use that (endIndex below in my example) instead of getSelectionEnd() when calling substring when you're setting your selectedText.

For example:

String substringFromStartSelection = getText().toString().substring (getSelectionStart());
int nextSpaceIndex = substringFromStartSelection.indexOf(" "); 
int selectionEnd = getSelectionStart() + nextSpaceIndex; 

Question:

I'm writing an Android app that syntax highlights code. Currently, the app works by taking a string, turning it into a new SpannableStringBuilder, then coloring it via setSpan(new ForegroundColorSpan(...)) based on the file extension. When all that is done, EditText.setText is called with the builder. The problem with this approach is with large files, all of the setSpan calls take a pretty long time, and the UI freezes for 10s of seconds before setText() is called and the text is displayed.

I want to overhaul the approach here. I would like to call setText() on the entire string first, so the text is displayed immediately (but is uncolored). Then I want to color the text in batches of 500 lines, flushing to the display after each batch. The user probably won't notice any difference (aside from the perf) because I can process + flush 500 lines much faster than the user can scroll down 500 lines.

I'm not sure how to implement my idea efficiently, however. The only way to 'flush' the changes by updating the display is to call setText() on the SpannableStringBuilder again after appending more spans to it. setText(), in turn, re-reads through the entire string and all its spans, when it only needs to look at the new spans. Is it possible to tell the EditText to only redraw the new spans? Thanks.


Answer:

I was being dumb. I made this test app (using Xamarin / C#) before asking this question:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    SetContentView(Resource.Layout.Main);

    var editText = FindViewById<EditText>(Resource.Id.EditText);
    var ssb = new SpannableStringBuilder(new string('E', 250));
    editText.SetText(ssb, TextView.BufferType.Editable);
    ssb.SetSpan(new ForegroundColorSpan(Color.Blue), 0, ssb.Length(), SpanTypes.InclusiveExclusive);
}

When you run the app all of the text is white. I thought this was because the EditText disregards any changes you made after SetText, and you need to call SetText again for the changes to take effect. However, I remembered that EditText by default copies your Editable when you call SetText, so you have to add this beforehand:

editText.SetEditableFactory(new NoCopyEditableFactory());

private class NoCopyEditableFactory : EditableFactory // Editable.Factory in Java
{
    public override IEditable NewEditable(ICharSequence source) => (IEditable)source;
}

Now all of the text is blue even though I called SetSpan after SetText.

Question:

I am having a editText and inputType as phone number. I would like add specific area code immediately after I enter first digit. Say for example

I enter 6 the EditText should show up +1 6.

I am trying achieve this using textWatcher but not sure how to put the number that I type after "+1"

   public void afterTextChanged(Editable s) 
            {               
                if(s.length() == 1)
                {
                    numberText.settext("+1");
                    numberText.setSelection(numberText.getText().length());
                }
            }

But the problem here is that when I enter first number the +1 is populated but the number which type through keyboard is not getting shown. I am not sure what is wrong here?

Also when I backspace and remove 1 from the text this happens but I am not able to remove + (this populates automatically). I don't want to remove +1 when I back space after +1 is populated.

Is this possible, if so how?

Thanks!


Answer:

Replace

numberText.settext("+1");

with

numberText.settext("+1" + s.toString());

You are not updating the existing text properly.

Question:

I wanted to make a little app. What this app is supposed to do is have a running "bank account" total and there are two options: deposit money or withdraw money. I attached the main activity class as well as the class I made for the "bank account" (I haven't implemented the history function yet as I have not figure out this part!). Basically, this line:

bankAccount.withdrawal(Double.parseDouble(findViewById(R.id.inputWithdrawal).toString()))

and it's deposit counterpart is throwing a NumberFormatException saying it's an "Invalid Double". I have no Idea what I've look on other threads but ihavent been able to find anything that works.

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


public class MainActivity extends AppCompatActivity {

    private EditText withdrawal, deposit;
    private Button withdrawalButton, depositButton;
    private BankAccount bankAccount;
    private String total;
    private TextView textViewTotal;

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

        withdrawal = (EditText) findViewById(R.id.inputWithdrawal);
        deposit = (EditText) findViewById(R.id.inputDeposit);

        withdrawalButton = (Button) findViewById(R.id.withdrawalButton);
        depositButton = (Button) findViewById(R.id.depositButton);
        withdrawalButton.setOnClickListener(onClickListener);
        depositButton.setOnClickListener(onClickListener);

        bankAccount = new BankAccount();
        textViewTotal = (TextView) findViewById(R.id.Total);
        updateTotal();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener(){
        @Override
        public void onClick(View view){
            try {
                switch (view.getId()) {
                    case R.id.withdrawalButton:
                        if (!withdrawal.getText().toString().equals("")) {
                            bankAccount.withdrawal(Double.parseDouble(findViewById(R.id.inputWithdrawal).toString()));
                            updateTotal();
                        }
                        break;

                    case R.id.depositButton:
                        if (!deposit.getText().toString().equals("")) {
                            bankAccount.deposit(Double.parseDouble(findViewById(R.id.inputDeposit).toString()));
                            updateTotal();
                        }
                        break;
                }
            } catch (NumberFormatException e){
                e.printStackTrace();
            }
        }};

    public void updateTotal(){
        total = "$" + bankAccount.getCheckingTotal();
        textViewTotal.setText(total);
    }  
}

public class BankAccount {
    private double checkingTotal;
    private ArrayList<String> history;

    public BankAccount(){
        checkingTotal = 0;
        history = new ArrayList<String>();
    }

    public void withdrawal(double amount){
        checkingTotal -= amount;
        history.add("-$" + amount);

        if(history.size() > 5)
            history.remove(0);
    }

    public void deposit(double amount){
        checkingTotal += amount;
        history.add("$" + amount);

        if(history.size() > 5)
            history.remove(0);
    }

    public double getCheckingTotal(){
        return checkingTotal;
    }
}

Answer:

findViewById(R.id.inputWithdrawal) returns a View

View.toString() gives you some garbage value (not the content of the EditText).

You already have withdrawal = (EditText) findViewById(R.id.inputWithdrawal);, so use it to get the String (like you already did with getText().toString() to see if the string was empty).

String w = withdrawal.getText().toString();
if (!TextUtils.isEmpty(w)) {
    bankAccount.withdrawal(Double.parseDouble(w));
    updateTotal();
}

Tip: always avoid extra findViewById calls.

Question:

EDIT2: Using

fragTransaction.add(fragment, tag);

instead of

fragTransaction.add(id, fragment);

OR

Removing all Fragments code in MainActivity makes the app works again, for some odd reason.


Getting the text via .getText().toString() returns null/empty when button is pressed.

Tried to manually .setText("something"), it works when .getText().toString() is called but,

when the text is modified, calling .getText().toString() will still return "something".

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragTransaction = fragmentManager.beginTransaction();

        Fragment loginFrag = new LoginFragment();

        fragTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
        fragTransaction.add(R.id.mainFrag, loginFrag);
        fragTransaction.commit();
    }

LoginFragment.java

public class LoginFragment extends Fragment{
    EditText fieldID;
    EditText fieldPassword;
    Button logButton;
    private FirebaseAuth mAuth;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login_menu, container, false);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        mAuth = FirebaseAuth.getInstance();
        view = v;

        fieldID = v.findViewById(R.id.fieldID);
        fieldPassword = v.findViewById(R.id.fieldPassword);
        logButton = v.findViewById(R.id.button_login);



        logButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn(fieldID.getText().toString(), fieldPassword.getText().toString());
            }
        });
    }

    private void signIn(String email, String password) {
        System.out.println("Email: " + email);
        System.out.println("Pass: " + password);

        if(!email.isEmpty() && !password.isEmpty()) {
            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                Log.d("Auth", "signInWithEmail:success");
                                FirebaseUser user = mAuth.getCurrentUser();
                                //updateUI(user);

                                view.findViewById(R.id.logoMain).setVisibility(View.GONE);
                            } else {
                                // If sign in fails, display a message to the user.
                                Log.w("Auth", "signInWithEmail:failure", task.getException());
                                //updateUI(null);
                            }
                        }
                    });
        }
    }
}

Main Activity

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".presenter.Activity.MainActivity">

    <fragment
        android:id="@+id/mainFrag"
        android:name="com.raze.mfa.presenter.Fragment.LoginFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Fragment Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="110dp"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logoMain"
        app:layout_constraintVertical_bias="1.0"
        app:srcCompat="@drawable/bak"
        tools:srcCompat="@drawable/bak" />

    <ImageView
        android:id="@+id/iconlock"
        android:layout_width="43dp"
        android:layout_height="43dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toStartOf="@+id/fieldPassword"
        app:layout_constraintHorizontal_bias="0.523"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/iconuser"
        app:srcCompat="@mipmap/lockicon" />

    <ImageView
        android:id="@+id/iconuser"
        android:layout_width="43dp"
        android:layout_height="43dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="320dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toStartOf="@+id/fieldID"
        app:layout_constraintHorizontal_bias="0.522"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/usericon" />

    <Button
        android:id="@+id/button_login"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/loginText"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fieldPassword"
        app:layout_constraintVertical_bias="0.188" />

    <EditText
        android:id="@+id/fieldPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="72dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/password"
        android:inputType="textPassword"
        android:singleLine="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fieldID" />

    <EditText
        android:id="@+id/fieldID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="320dp"
        android:layout_marginEnd="72dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/email"
        android:inputType="textEmailAddress"
        android:singleLine="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/logoMain"
        android:layout_width="128dp"
        android:layout_height="128dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="108dp"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        app:layout_constraintBottom_toTopOf="@+id/fieldID"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:srcCompat="@drawable/logoimg" />

    <Button
        android:id="@+id/button_register"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/register"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_login"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

Unrelated: I've Googled mostly everything but it seems that I haven't understand the basics of using Fragments, Activites, context, Views, and etc.


Answer:

Ok I see, you are using a <fragment/> tag already in your MainActivity layout, and then you add with the FragmentTransaction a fragment to it.

The transaction is for FrameLayout containers that are empty and take a fragment. When you add the fragment statically through the <fragment/> tag the fragment is already loaded into the screen.

Something weird was happening when you added a new fragment to a fragment tag, maybe it duplicated the fragment and it was reading the one that is behind the actual fragment and it wasn't getting the input from the user.

Read here for the proper use of FragmentTransaction: https://developer.android.com/training/basics/fragments/fragment-ui

Taken from the docs above, see how they use a FrameLayout as the container.

XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Java:

public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState?) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check that the activity is using the layout version with
    // the fragment_container FrameLayout
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create a new Fragment to be placed in the activity layout
        HeadlinesFragment firstFragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an
        // Intent, pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    }
}
}

Question:

I am trying to make an app where you get the input trough the editText component and put it in the string like below:

number = findViewById(R.id.editText2); newNumber = number.getText().toString();

Now what I want is to replace the string start if a certain condition is met like this:

                if (number.getText().toString().substring(0, 1).equals("0")) {

                    newNumber = newNumber.replaceFirst("06", "3876");

                        Log.d("TAG", newNumber);
}

I get an error saying that the StringIndexIsOutOfBounds index=2 length=0

I also tried it like this:

 if (newNumber.startsWith("06")) {
                    newNumber = newNumber.replaceFirst("06", "3876");

                        Log.d("TAG", newNumber);
                        //Toast.makeText(MainActivity.this, newNumber, Toast.LENGTH_SHORT).show();
                    }
    else {
...
}

I get the else statement when I run this query.

Since I tried this in many combinations, a similar one produces an empty toast. (Can't remember what exactly did it, but it doesn't even matter as it is also not right)

What is wrong in my code? The string is all numbers, but I found it easiest to do the replacements on a string, if you know of a better implementation, be my guest. The input should be 9 numbers, and output should be 11 numbers (I am replacing 06 with 3876 so I get the 2 extra numbers there).

(I have searched SO for similar problems and some attempts were recreations, but none successful)


Answer:

Ok, first of all, are u sure, you've the right string f.ex. 06xxxxxx in your var and is not empty?

Check your string

!number.getText().toString().isEmpty()

than try this:

EditText number = (EditText) findViewById(R.id.editText2);
String newNumber = number.getText().toString();

f(!number.getText().toString().isEmpty()){
        Log.d("TAG", newNumber);
        newNumber = newNumber.replaceFirst("06", "3876");
        Log.d("TAG", newNumber);
}

Question:

I'am doing a login that has a code of the user and a password. Then, when the fields will be completed, there's a button "log in" that was set.Enabled(false) and it will be set.Enabled(true) allowing the acces ( I did this for to avoid test of consistency).

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText codigo;
    final TextView nome;
    final EditText senha;

    codigo = (EditText) findViewById(R.id.cod_edit_text);
    senha = (EditText)findViewById(R.id.senha_edit_text);

    String cod = codigo.getEditableText().toString();
    String password = senha.getEditableText().toString();

    final Button botaologar = (Button) findViewById(R.id.button_logar);
    if(!cod.isEmpty() || !password.isEmpty())
    {
        botaologar.setClickable(true);
        botaologar.setEnabled(true);
    }
    else
    {
        botaologar.setEnabled(false);
        botaologar.setClickable(false);
    }

However, when I catch a string of the EditText it is empty by some reason and the button still set.Enabled(false).

I noticed, then, when i named on XML of the activity_main.xml with a string on string.XML with some value, the button stays set.Enabled(true), but the value appears on EditText with the values of the string.xml. Look:

File activity_main.xml:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"

    android:text="@string/cod_edit_text"

    android:id="@+id/cod_edit_text"
    android:layout_below="@+id/codigo_text_view"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:ems="10"
    android:id="@+id/senha_edit_text"

    android:text="@string/senha_edit_text"

    style="@style/AppTheme"
    android:password="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/senha_text_view"
    android:layout_alignParentLeft="true" />

File string.xml:

<string name="cod_edit_text"> test </string>
<string name="senha_edit_text"> test  </string>

So, the problem is that I can't the button stays .setEnabled(true) because I can't to take the value of the EditText correctly. Any idea to solve the problem?


Answer:

Use TextWatcher :

Example

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
private EditText passwordEditText;
private TextView textView;

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

    /* Initializing views */
    passwordEditText = (EditText) findViewById(R.id.password);
    textView = (TextView) findViewById(R.id.passwordHint);
    textView.setVisibility(View.GONE);

    /* Set Text Watcher listener */
    passwordEditText.addTextChangedListener(passwordWatcher);
 }

 private final TextWatcher passwordWatcher = new TextWatcher() {
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        textView.setVisibility(View.VISIBLE);
    }

    public void afterTextChanged(Editable s) {
        if (s.length() == 0) {
            textView.setVisibility(View.GONE);
        } else{
            textView.setText("You have entered : " + passwordEditText.getText());
        }
    }
 };
}

You can always enable or disable the button in TextWatcher's beforeTextChanged or afterTextChanged. Based on your requirements.

Question:

As title says, when i execute this app, WebView connects to "https://null/" insted of the string i put on the EditText, i cant figure out the problem

MainActivity activity

public class MainActivity extends AppCompatActivity {
EditText web;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    web = (EditText) findViewById(R.id.web);
    String webstr = web.getText().toString();
    Intent int2 = new Intent(MainActivity.this, WebView.class);
    int2.putExtra("123", webstr);
    Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Intent intent = new Intent(getApplicationContext(), WebView.class);
            v.getContext().startActivity(intent);
        }
    });

  }
}

WebView Activity

public class WebView extends AppCompatActivity {
private android.webkit.WebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);
    Intent intent = getIntent();
    String web1 = intent.getStringExtra("123");
    webView = findViewById(R.id.webview);
    webView.getSettings().setDomStorageEnabled(true);
    webView.setWebViewClient(new WebViewClient());
    webView.loadUrl("https://" + web1);
    Toast.makeText(WebView.this, "Connected", Toast.LENGTH_SHORT).show();

 } 
}

Answer:

You need to get the value from your EditText when you click the button, not within onCreate.

Also you're not using the same Intent, so you're not actually passing that value.

Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), WebView.class);
        String webstr = web.getText().toString();
        intent.putExtra("123", webstr);
        v.getContext().startActivity(intent);
    }
});

Question:

Im working on hebrew logo quiz app and i need to use an edittext that the user type what he see and then compare it to the preset value. The current code is

        Check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String word = String.valueOf(test.getText());
            String word2 = String.valueOf("טקסט בעברית");
            if (word==word2){
                tv.setText("True");
            }
            else tv.setText("False");
        }

    });

and the output is always False as well as the correct answer.. I really need help here


Answer:

you are comparing two object by their references and because they are not same, returned value is always false. you should compare their values not their reference. read more here

String class in java has a method for comparison. you should use equals method. read more here

Question:

Initializing the EditTexts on onCreate is returning a "" which cannot be cast into valid double hence this error. Using an explicit value might help but then I will lose the android:hint text. How can I resolve this issue without losing the android:hint text ?

Code

public class MainActivity extends Activity {

private double quant, problem, verbal;

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




    EditText quantScore = (EditText) findViewById(R.id.quant);
    EditText problemScore = (EditText) findViewById(R.id.problem);
    EditText verbalScore = (EditText) findViewById(R.id.verbal);
    Button calculate = (Button) findViewById(R.id.button);



    quant = Double.valueOf(quantScore.getText().toString());
    problem = Double.valueOf(problemScore.getText().toString());
    verbal = Double.valueOf(verbalScore.getText().toString());

    final double total = quant + problem + verbal;




    calculate.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "The total is " +total, Toast.LENGTH_LONG).show();
        }
    });




}

Layout

<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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Score To Percentile"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:ems="10"
    android:id="@+id/quant"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="70dp"
    android:hint="Quantitative Ability"
    android:gravity="center"
    android:textStyle="italic" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:ems="10"
    android:id="@+id/problem"
    android:layout_marginTop="50dp"
    android:layout_below="@+id/quant"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:hint="Problem Solving"
    android:gravity="center"
    android:textColorLink="#ffffdbeb"
    android:textStyle="italic" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:ems="10"
    android:id="@+id/verbal"
    android:layout_marginTop="50dp"
    android:hint="Verbal Ability"
    android:gravity="center"
    android:textColorLink="#ff48f3ff"
    android:layout_below="@+id/problem"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:textStyle="italic" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Calculate"
    android:id="@+id/button"
    android:layout_below="@+id/verbal"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="60dp"
    android:textStyle="italic"
    android:typeface="monospace" />


Answer:

You should catch the NumberFormatException and provide the desired default value.

try {
   quant = Double.valueOf(quantScore.getText().toString());
} catch(NumberFormatException e) {
   quant = 0;
}

This will work for any text that can't be parsed to Double not only when the EditText is empty.

Question:

I met a interest issue about getting the String from another activity to main activity.

The procedures: 1. User click the editText to trigger the calendar shows with DatePickerDialog

  1. Once the date that user picked is valid, it return to be a String and set on editText, then click submit button will send to activity_confirm.

  2. When users clicked "Edit" button, the activity_confirm will return all values and go through with dataHolder to send those data to Main activity's fragment and setText on those editText.

I can get all the values correctly except DOB, I wonder why it will return null on activity_confirm while setText() on the TextView of it, is the error existed on fragment's method? But I was confused.

Thanks for any assistance or suggestion.

Main activity:

 btn_Click.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            ......
            //Get from fragment and intent to activity_confirm
            extras.putString("confirmDOB", strDOB);
            ......
        }
 }

Fragment:

......
TextInputLayout DOBpicker;
EditText DOB;
Calendar myCalendar = Calendar.getInstance();
......

    final DatePickerDialog.OnDateSetListener date = (new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar checkValid = new GregorianCalendar(year, monthOfYear, dayOfMonth);
                Calendar minAdultAge = new GregorianCalendar();
                minAdultAge.add(Calendar.YEAR, -18);
                if (minAdultAge.before(checkValid)) {
                    //Snackbar.make(correspondence, "Applicant's Date of birth cannot be 18 or below.", Snackbar.LENGTH_LONG).show();
                    DOBpicker.setErrorEnabled(true);
                    DOBpicker.setError("Applicant's Date of birth cannot be 18 or below.");
                    strDOB = "";
                    DOB.setText(strDOB);
                    insureApplicant2.put(1, strDOB);
                    DOBpicker.clearFocus();
                } else {
                    DOBpicker.setErrorEnabled(false);
                    myCalendar.set(Calendar.YEAR, year);
                    myCalendar.set(Calendar.MONTH, monthOfYear);
                    myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateLabel();
                }
            }
        });

        DOB.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @Override
            public void onFocusChange(View view, boolean isFocus){
                if(isFocus){
                    new DatePickerDialog(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, date, myCalendar
                            .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                            myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                }
            }
        });
    private void updateLabel(){
        String myFormat = "dd/MM/yyyy"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
        DOB.setText(sdf.format(myCalendar.getTime()));
        strDOB = DOB.getText().toString().trim();
        insureApplicant2.put(1, strDOB);
        passToActivity2("DOB", DOB.getText().toString().trim());
    }

activity_confirm:

//onCreate()
......
    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if(extras != null) {
            ......
            strDOB = extras.getString("ConfirmDOB");
            //Log.e("getStringDate", String.valueOf(extras.getString("confirmDOB"))); //can get value
            ......
            DOB.setText(strDOB);
            //DOB.setText(String.valueOf(extras.getString("ConfirmDOB")));  
            //DOB.setText(strDOB);
            //All return null ?!
            ......
        } else {
            ......
            DOB = null;
        }
    }
......
//End of onCreate()

......
btn_editInfo.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            ......
            dataHolder.setDob(strDOB);
            ......
            //intent to main activity
        }
    });
......

dataHolder (store those editText value for get/set):

public class fragment_data_holder {
    private static data_holder mInstance;
    ......
    private String dob;
    ......

    public static data_holder getmInstance(){
        if (mInstance == null) {
            return mInstance = new data_holder();
        } else {
            return mInstance;
        }
    }

    //Getter and Setter
    ......
    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }
}

Answer:

Your spelling is different. On MainActivity it is "confirmDOB" while on activity_confirm it is "ConfirmDOB"

Question:

Looking at this solution to an answer that was made for an EditText field in Android Studio, I am wondering what this string means and how I can break it down to understand and interpret the parts that I need.

I have referred this:Android Money Input with fixed decimal

I pulled this from Zds and Ninjasense's answer

if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))

What I'm trying to figure out is how to remove the $ sign that is attached to the EditText so that I can use the number and make some calculations to it.

The whole code I'm currently using in my project is:

@Override
public void onTextChanged(CharSequence s, int start,
        int before, int count) {
    if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
    {
        String userInput= ""+s.toString().replaceAll("[^\\d]", "");
        StringBuilder cashAmountBuilder = new StringBuilder(userInput);

        while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
            cashAmountBuilder.deleteCharAt(0);
        }
        while (cashAmountBuilder.length() < 3) {
            cashAmountBuilder.insert(0, '0');
        }
        cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
        cashAmountBuilder.insert(0, '$');

        cashAmountEdit.setText(cashAmountBuilder.toString());
        cashAmountEdit.setTextKeepState(cashAmountBuilder.toString());
        Selection.setSelection(cashAmountEdit.getText(), cashAmountBuilder.toString().length());
    }
}

Answer:

Check out this link for visualizing the regular expression in your string.

The check mainly relies on digits \d’ to be found a fixed{3}or ranged{1,3}or unlimited+number of times, allowing,and.` to be preseent at specific locations.

Question:

I have been recently having an error when compiling my android code onto an emulator. The game is that when you click a button, it gives you a math question displayed on a textView, and user types their answer (in numbers) and clicks the button 'check' When I click that button, it always returns false. Anyone knows how to fix this?

Java Class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);




    mathQuestion = findViewById(R.id.magic_textview);

    redCircle = findViewById(R.id.math_ball);

    yellowbox = findViewById(R.id.yellow_box);
    yellowboxY = 1550f - 130f;
    yellowbox.setY(yellowboxY);
    yellowboxX = 472f;
    yellowbox.setX(yellowboxX);


    type_answer = findViewById(R.id.type_answer);
    Button checkButton = findViewById(R.id.check_button);
    checkButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(redCircleX == yellowboxX && redCircleY == yellowboxY){
                mathQuestion.setText("What is "+math_int1+" + "+math_int2+" ?");
                math_int1 = r.nextInt(20);
                math_int2 = r.nextInt(20)+1;
                string_math_int1 = String.valueOf(math_int1);
                string_math_int2 = String.valueOf(math_int2);
                Button checkAnswer = findViewById(R.id.check_answer);
                 checkAnswer.setOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View view) {

                        //Error? Always returning false?

                         if (type_answer.getText().toString().contains (Integer.toString( math_int1 + math_int2))) {
                            Toast t =  Toast.makeText(GameActivity.this, "Success!", Toast.LENGTH_SHORT);
                            t.show();
                         } else {
                            Toast t2= Toast.makeText(GameActivity.this, type_answer.getText().toString(), Toast.LENGTH_SHORT);
                            t2.show();

                         }



                       }


                 });

            }else{
                Toast.makeText(GameActivity.this, "Incorrect Or Error", Toast.LENGTH_SHORT).show();
            }
        }

    });



    Button upButton = findViewById(R.id.up_button);
    upButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            moveUp();

        }
    });
    Button downButton = findViewById(R.id.down_button);
    downButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            moveDown();

        }
    });


    Button leftButton = findViewById(R.id.left_button);
    leftButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            moveLeft();

        }
    });
    Button rightButton = findViewById(R.id.right_button);
    rightButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            moveRight();

        }
    });
    Button resetCircleXY = findViewById(R.id.reset_button);
    resetCircleXY.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            initCircleXY();
            Toast.makeText(GameActivity.this, "Reset Ball's Position", Toast.LENGTH_SHORT).show();

        }
    });
    upButton.performClick();
    leftButton.performClick();
    redCircleY = 1550f;
    redCircle.setY(redCircleY);
    redCircleX = 472f;
    redCircle.setX(redCircleX);


}

private void moveUp(){
    redCircleY -= ballMoveDis;
    redCircle.setY(redCircleY);

}
private void moveDown(){
    redCircleY += ballMoveDis;
    redCircle.setY(redCircleY);

}

private void moveLeft(){
    redCircleX += ballMoveDis;
    redCircle.setX(redCircleX);

}
private void moveRight(){
    redCircleX -= ballMoveDis;
    redCircle.setX(redCircleX);

}
private void initCircleXY(){
    redCircleY = 1550f;
    redCircle.setY(redCircleY);
    redCircleX = 472f;
    redCircle.setX(redCircleX);
}

}

Help is greatly appreciated, Thanks


Answer:

First mistake

string_math_int1 = String.valueOf(math_int1);
string_math_int2 = String.valueOf(math_int1);  // this should be math_int2

BUT consider adding two strings

 string_math_int1 + string_math_int2)

 "10"             +  "20"

equals

 "1020" not "30"

Maybe

if (type_answer.getText().toString().equals(String.valueOf (math_int1 + math_int2) {

Question:

How can I check if set of random characters from String of EditText matches a certain word from file?

For example:

EditText input: TINARSE Can match word like NASTIER, STAINER. Suppose a word in file is denoted by i.

I know how read strings from file just cant figure out how to match it with the random character input using IF statements.

Note: Length of string should be same as length EditText


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    anagram=(EditText)findViewById(R.id.inputtext);
    submit=(Button)findViewById(R.id.submit);
    viewall=(TextView)findViewById(R.id.list);
    viewall.setMovementMethod(new ScrollingMovementMethod());
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String a =anagram.getText().toString();
            checkword("cswfifteen.txt",a);



        }
    });

}
private void checkword(String Filename,  String a) {

    StringBuilder builder = null;
    BufferedReader reader = null;
    ArrayList<String> words= new ArrayList<>();

    try {
        builder = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(
                getAssets().open(Filename)

        ));


        String Line;
            while ((Line = reader.readLine()) != null) {

                builder.append(Line).append("\n");

            }
            String[] dict = builder.toString().split("\n");


                for (String i : dict) {



                    char[] b = i.toString().toCharArray();
                    Arrays.sort(b);

                   char[] c=a.replace("?","").toCharArray();
                    Arrays.sort(c);
                    if (String.valueOf(b).contains(String.valueOf(c)) && b.length==a.length()){
                        words.add(i);}



            }

        Collections.sort(words);
        StringBuilder result = new StringBuilder();
            for (String i : words)
            {

                result.append(i + "\n");
            }
            viewall.setText(result.toString());


    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Answer:

Sort the text from EditText and word i from the file. Compare these two strings.

String textFromEditText= "zxbc";
String wordFromFile="cxbz";
char a[] = textFromEditText.toCharArray();
char c[] = wordFromFile.toCharArray();
Arrays.sort(a);
Arrays.sort(c);
System.out.println(String.valueOf(a).equalsIgnoreCase(String.valueOf(c)));

Question:

I have BMI calculator app that takes some input and puts it in "EditText". Here is what I am trying to do: If the input is 170, it will become 1.70. If the input is 1.70, it will not change.

This is the code I have:

String weight = editText.getText().toString();

Answer:

Cant you convert the string to an integer and take modulus 100 to the cms and divide by 100 to get in meters?

You can convert the String weight to int like this

int wgt = Integer.parseInt(weight); 

Then separating meters and centimetres.

int mtrs = wgt / 100; 
int cms = wgt % 100; 

Then combining both

String result = mtrs + "." + cms;