Hot questions for Using Android EditText in crash

Question:

I have a problem when change the text in EditText, my expected result is clear old text then set the new text that user input. After that, every working with editText is normal.

Exp: old text: 'abcdef',
     user press key 'k',
     expected text in editText is: 'k'

Here is my code:

editText.addTextChangedListener(new TextWatcher() {
private boolean firstRun = true;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if(firstRun) {
        editText.removeTextChangedListener(this);
        firstRun = false;
        if(count == 0) {
        // Delete key or other special key
            editText.setText("");
            return;
        } else {
            if(s.length() > start) {
                editText.setText(String.valueOf(s.charAt(start)));
                editText.setSelection(etp.getEditText().getText().length());
            } else {
                editText.setText("");
            }
        }
   }

}

My code is crashed in case user paste a new text inside old text (it's not crashed if user paste from begin or end of old text).

Exp: Old text: abcdef
     User action: abcd(paste here)ef

The logcat is below

08-14 06:18:55.977: E/AndroidRuntime(4187): FATAL EXCEPTION: main
08-14 06:18:55.977: E/AndroidRuntime(4187): java.lang.IndexOutOfBoundsException: replace (-1 ... -1) starts before 0
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1021)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:441)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:435)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:30)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.widget.TextView.replaceText_internal(TextView.java:8442)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.widget.TextView.prepareSpacesAroundPaste(TextView.java:8250)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.widget.TextView.paste(TextView.java:8271)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.widget.TextView.onTextContextMenuItem(TextView.java:8036)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.widget.Editor$ActionPopupWindow.onClick(Editor.java:2862)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.view.View.performClick(View.java:4204)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.view.View$PerformClick.run(View.java:17355)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.os.Handler.handleCallback(Handler.java:725)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.os.Looper.loop(Looper.java:137)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.app.ActivityThread.main(ActivityThread.java:5041)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at java.lang.reflect.Method.invoke(Method.java:511)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-14 06:18:55.977: E/AndroidRuntime(4187):     at dalvik.system.NativeStart.main(Native Method)

What is causing this error?


Answer:

This is an unintended side-effect of a feature that adds spaces before and after the text that was pasted. The big clue here is in the stack-trace:

08-14 06:18:55.977: E/AndroidRuntime(4187):     at android.widget.TextView.prepareSpacesAroundPaste(TextView.java:8250)

You've written code in the TextWatcher that sets the text to an empty string (editText.setText("")), but the code in prepareSpacesAroundPaste is expecting the original text. Hence the index out of range exception.

Solution: try doing your text replacement in the afterTextChanged event instead; you might need to have a flag set in onTextChanged that is referenced in afterTextChanged before updating your text value.

Question:

I have an app with a register fragment where users can register themselves.

When I start typing on any EditText, the app just crashes unusually.

Error Log

01-20 22:52:40.942 6164-6164/in.snotes.snotes E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.snotes.snotes, PID: 6164
java.lang.IndexOutOfBoundsException
    at android.graphics.Canvas.drawText(Canvas.java:1707)
    at android.text.Layout.drawText(Layout.java:396)
    at android.widget.Editor.drawHardwareAccelerated(Editor.java:1735)
    at android.widget.Editor.onDraw(Editor.java:1657)
    at android.widget.TextView.onDraw(TextView.java:5888)
    at android.view.View.draw(View.java:17086)
    at android.view.View.updateDisplayListIfDirty(View.java:16068)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3752)
    at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3732)
    at android.view.View.updateDisplayListIfDirty(View.java:16031)
    at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:657)
    at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:663)
    at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:771)
    at android.view.ViewRootImpl.draw(ViewRootImpl.java:2808)
    at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2616)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2223)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1258)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6348)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
    at android.view.Choreographer.doCallbacks(Choreographer.java:683)
    at android.view.Choreographer.doFrame(Choreographer.java:619)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6123)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

This is my register fragment xml

<LinearLayout 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:orientation="vertical"
tools:context="in.snotes.snotes.ui.RegisterFragment">

<android.support.v7.widget.Toolbar
    android:id="@+id/register_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="?attr/actionBarTheme" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="30dp"
    android:gravity="center"
    android:text="@string/register_snotes"
    android:textSize="24sp"
    android:textStyle="bold" />

<android.support.design.widget.TextInputLayout
    android:id="@+id/name_input_layout"
    style="@style/InputStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edt_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/name"
        android:textAllCaps="true" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/email_input_layout"
    style="@style/InputStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edt_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/email"
        android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/password_input_layout"
    style="@style/InputStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true">

    <EditText
        android:id="@+id/edt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/password"
        android:inputType="textPassword" />

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/confirm_password_input_label"
    style="@style/InputStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true">

    <EditText
        android:id="@+id/edt_confirm_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/confirm_password"
        android:inputType="textPassword" />

</android.support.design.widget.TextInputLayout>

<Button
    android:id="@+id/btn_register"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="20dp"
    android:background="@color/colorAccent"
    android:text="@string/register" />

And here is my java class

public class RegisterFragment extends Fragment {

@BindView(R.id.register_toolbar)
Toolbar registerToolbar;
@BindView(R.id.edt_name)
EditText edtName;
@BindView(R.id.name_input_layout)
TextInputLayout nameInputLayout;
@BindView(R.id.edt_email)
EditText edtEmail;
@BindView(R.id.email_input_layout)
TextInputLayout emailInputLayout;
@BindView(R.id.edt_password)
EditText edtPassword;
@BindView(R.id.password_input_layout)
TextInputLayout passwordInputLayout;
@BindView(R.id.edt_confirm_password)
EditText edtConfirmPassword;
@BindView(R.id.confirm_password_input_label)
TextInputLayout confirmPasswordInputLabel;
@BindView(R.id.btn_register)
Button btnRegister;
Unbinder unbinder;
private RegisterFragmentListener mListener;

public RegisterFragment() {
    // Required empty public constructor
}

// TODO: Rename and change types and number of parameters
public static RegisterFragment newInstance() {
    return new RegisterFragment();
}

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

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_register, container, false);
    unbinder = ButterKnife.bind(this, view);
    return view;
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof RegisterFragmentListener) {
        mListener = (RegisterFragmentListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement RegisterFragmentListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
}

@OnClick(R.id.btn_register)
public void registerClicked() {

    invalidateErrorMessages();

    String name = edtName.getText().toString().trim();
    if (name.isEmpty() || TextUtils.isEmpty(name)){
        nameInputLayout.setError("Name cannot be empty");
        return;
    }

    String email = edtEmail.getText().toString().trim();
    if (email.isEmpty() || TextUtils.isEmpty(email)){
        emailInputLayout.setError("Email cannot be empty");
        return;
    }
    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
        emailInputLayout.setError("Enter a valid email");
        return;
    }

    String password = edtPassword.getText().toString().trim();
    String confirmPassword = edtConfirmPassword.getText().toString().trim();

    if (password.isEmpty() || TextUtils.isEmpty(password)){
        passwordInputLayout.setError("Password cannot be empty");
        return;
    }

    if (confirmPassword.isEmpty() || TextUtils.isEmpty(confirmPassword)){
        confirmPasswordInputLabel.setError("Confirm Password cannot be empty");
        return;
    }

    if (!Objects.equals(password,confirmPassword)){
        passwordInputLayout.setError("Passwords should match");
        confirmPasswordInputLabel.setError("Passwords should match");
        return;
    }

    mListener.register(name,email,password);

}

private void invalidateErrorMessages() {
    nameInputLayout.setError(null);
    emailInputLayout.setError(null);
    passwordInputLayout.setError(null);
    confirmPasswordInputLabel.setError(null);
}

public interface RegisterFragmentListener {
    void register(String name, String email, String password);
}}

I have no idea why the app crashes when I start typing that too with an Index Out Of Bounds exception.

Whats wrong? How do I fix it?


Answer:

Remove android:textAllCaps="true" property from EditText

textAllCaps property is for TextView only. You can not use this property for EditText.

For EditText caps use this code

editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});

Question:

I am trying to display a toast when EditText is empty and the button is clicked.

The app crashes when button is clicked.

What possibly am I doing wrong? Kindly help me with this as I am new to Mobile App Development. Where do I need to make changes or what to rectified in order to get this done? Any help is appreciated.

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class EmployeeActivity extends AppCompatActivity {

    EditText hourlyWage, totalRegularHours, totalOvertimeHours;
    Button btnCalculate;
    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.employee_activity);
        hourlyWage = findViewById(R.id.et_hourlyWage);
        totalRegularHours = findViewById(R.id.et_totalRegularHours);
        totalOvertimeHours = findViewById(R.id.et_totalOvertimeHours);
        btnCalculate = findViewById(R.id.btnCalculate);
        result = (TextView) findViewById(R.id.tv_Result);
    }

    // method to be called on onClick
    public void calculateResult(View view) {
        double regularHours = Integer.parseInt(totalRegularHours.getText().toString());
        double overtimeHours;
        overtimeHours = Integer.parseInt(totalOvertimeHours.getText().toString());
        // check if EditText is empty
        if (hourlyWage.getText().toString().trim().equals("")) {
            Toast.makeText(this, "Please Enter The Value.", Toast.LENGTH_LONG).show();
        }
        // check if EditText is empty
        else if (totalRegularHours.getText().toString().trim().equals("")) {
            Toast.makeText(this, "Please Enter The Value.", Toast.LENGTH_LONG).show();
        }
        // check if EditText is out of range
        else if (regularHours <= 0 && regularHours >= 40) {
            Toast.makeText(this, "Please Enter The Value of Hours Between 0 to 40.", Toast.LENGTH_LONG).show();
        }
        // check if EditText is out of range
        else if (overtimeHours <= 0 && overtimeHours >= 30) {
            Toast.makeText(this, "Please Enter The Value of Hours Between 0 to 30.", Toast.LENGTH_LONG).show();
        }
        // calculates the answer
        else if (regularHours >= 0 && regularHours <= 40) {
            // formula for calculation
            double regularWage;
            regularWage = (Integer.parseInt(hourlyWage.getText().toString()) * Integer.parseInt(totalRegularHours.getText().toString())) + (Integer.parseInt(totalOvertimeHours.getText().toString()) * Integer.parseInt(hourlyWage.getText().toString()) * (1.5));
            //displays the result in a TextView
            result.setText(String.valueOf(regularWage));
        }
    }
}

Answer:

You are parsing with Integer.parseInt with an empty string. Also, you are storing an integer in a different type - double. Here's your fix:

// method to be called on onClick
    public void calculateResult(View view) {

// check if EditText is empty
        if (hourlyWage.getText().toString().isEmpty()){
            Toast.makeText(this, "Please Enter The Value.", Toast.LENGTH_LONG).show();
            return;
        }
// check if EditText is empty
        if(totalRegularHours.getText().toString().isEmpty())
        {
           Toast.makeText(this, "Please Enter The Value.", Toast.LENGTH_LONG).show();
           return;
        }

        int regularHours = Integer.parseInt(totalRegularHours.getText().toString());

        int overtimeHours;
        overtimeHours = Integer.parseInt(totalOvertimeHours.getText().toString());

// check if EditText is out of range
        if (regularHours <= 0 && regularHours >= 40) {

            Toast.makeText(this, "Please Enter The Value of Hours Between 0 to 40.", Toast.LENGTH_LONG).show();

        }
// check if EditText is out of range
        else if (overtimeHours <= 0 && overtimeHours >= 30) {

            Toast.makeText(this, "Please Enter The Value of Hours Between 0 to 30.", Toast.LENGTH_LONG).show();

        }
// calculates the answer
        else if(regularHours >= 0 && regularHours <= 40) {
// formula for calculation
          double regularWage;
          regularWage = (Integer.parseInt(hourlyWage.getText().toString()) * Integer.parseInt(totalRegularHours.getText().toString())) + (Integer.parseInt(totalOvertimeHours.getText().toString()) * Integer.parseInt(hourlyWage.getText().toString()) * (1.5));
//displays the result in a TextView
          result.setText(String.valueOf(regularWage));
        }


    }

Question:

I am having this issue with Edittext in android studio.The app works fine but app crashes with no input

Here is the java code

public void onButtonClick (View v)
{
    int num1,num2,sum;

    EditText e1 = (EditText)findViewById(R.id.num1);
    EditText e2 = (EditText)findViewById(R.id.num2);

    TextView t1 = (TextView)findViewById(R.id.sum);

    num1 = Integer.parseInt(e1.getText().toString());

    num2 = Integer.parseInt(e2.getText().toString());

    sum = num1 + num2;

    t1.setText(Integer.toString(sum));
}

Answer:

Integer.parseInt() fails when no input is given, calculate only if there is an input.

public void onButtonClick (View v)
{
    int num1 = 0,num2 = 0,sum = 0;
    EditText e1 = (EditText)findViewById(R.id.num1);
    EditText e2 = (EditText)findViewById(R.id.num2);

    TextView t1 = (TextView)findViewById(R.id.sum);
    if(!(e1.getText().toString()).equals(""))
       num1 = Integer.parseInt(e1.getText().toString());
    if(!(e2.getText().toString()).equals(""))
       num2 = Integer.parseInt(e2.getText().toString());

    sum = num1 + num2 ;

    t1.setText(sum.toString());
}

Your application will crash if the given input is not a number.

To make an EditText only accept numbers

In the xml file use this

<EditText
    android:inputType="number"
    android:digits="0123456789."
/>

Question:

I have this error:

The specified child already has a parent. You must call removeView() on the child's parent first.

When I clicked buildNot.setPosiviteButton. Help me please, thanks guys! This is my Java source code:

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

        Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);

        list = (ListView) findViewById(R.id.listView1);
        adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
        etDers = new EditText(MainActivity.this);
        etNot = new EditText(MainActivity.this);
        //Dialog
        AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
        build.setTitle("Ders Ekle");
        build.setView(etDers);
        //Dialog Not
        final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
        buildNot.setTitle("Not Ekle");
        buildNot.setView(etNot);

        build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                adapter.add(etDers.getText().toString());
                dialog.cancel();
            }
        });
        final AlertDialog alertDers = build.create();

        buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                 adapter = (ArrayAdapter ) list.getAdapter();
                  String item = (String) list.getSelectedItem();
                  int position = list.getSelectedItemPosition();
                  item += "YourText";
                  adapter.insert(item, position);
                  dialog.cancel();
            }
        });
        final AlertDialog alertNot = buildNot.create();
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                alertNot.show();
            }
        });
        list.setAdapter(adapter);

        btnDersEkle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                alertDers.show();

            }
        });


    }

Answer:

That is because nothing is selected.

list.getSelectedItemPosition() will always return -1.

"Click" and "select" are separate things. "Select" in a ListView is done via the pointing device (D-pad, trackball, arrow keys, etc.).

list.getSelectedItemPosition() will always return -1 if you are not using D-pad, trackball or arrow keys.

You should store the position in onItemClick(AdapterView<?> parent, View view, int position, long id) as a class member and access it in buildNot.setPositiveButton onClick.

Coding below, where mPosition is a class member of your class.

buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        adapter = (ArrayAdapter ) list.getAdapter();
        String item = (String) adapter.getItem(mPosition);
        item += "YourText";
        adapter.insert(item, mPosition);
        dialog.cancel();
    }
});

list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        mPosition = position;
        alertNot.show();
    }
});

Question:

Clicking on register makes the app crash when the email and password fields are empty, but when the name field is empty it works properly what seems to be the problem?

xml file:

 <LinearLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.zachmarcelo.softcash.LoginActivity"
android:background="#fff"
>

<!-- Login progress -->
<ImageView
    android:layout_width="match_parent"
    android:layout_height="47dp"
    android:layout_marginBottom="20dp"
    android:visibility="visible"
    app:srcCompat="@drawable/icon_ewallet_" />

<ProgressBar
    android:id="@+id/login_progress"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:visibility="gone" />

<ScrollView
    android:id="@+id/login_form"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <LinearLayout
        android:id="@+id/email_login_form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textColorHint="@color/colorHint" >

            <EditText
                android:id="@+id/reg_username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Name"
                android:inputType="text"
                android:textSize="20sp"
                android:textColor="@android:color/background_dark"
                />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/TextLabel"
            android:textColorHint="@color/colorHint">

            <EditText
                android:id="@+id/reg_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@android:color/darker_gray"
                android:hint="Email"
                android:maxLines="1"
                android:singleLine="true"
                android:textColor="@android:color/background_dark"
                android:inputType="textEmailAddress"
                />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/TextLabel"
            android:textColorHint="@color/colorHint">

            <EditText
                android:id="@+id/reg_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@android:color/background_dark"
                android:hint="Password"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true"
                android:textColor="@android:color/background_dark" />

        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/register"
            style="?android:textAppearanceSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorAccent"
            android:gravity="center"
            android:paddingLeft="20sp"
            android:paddingRight="20sp"
            android:text="Register"
            android:textStyle="bold"
            android:layout_marginBottom="20dp"/>

        <TextView
            android:id="@+id/signin"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Already have an account?"
            android:textAlignment="center"
            android:textColor="@color/colorPrimary"
            android:textSize="12dp" />

    </LinearLayout>
</ScrollView>
<ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

code:

package com.example.zachmarcelo.softcash;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity implements 
View.OnClickListener {
 private EditText reg_password,
  reg_username,
  reg_email;
 private FirebaseAuth mAuth;
 private ProgressBar progressBar;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    progressBar = new ProgressBar(getApplicationContext());
    reg_password = findViewById(R.id.reg_password);
    reg_email    = findViewById(R.id.reg_email);
    reg_username = findViewById(R.id.reg_username);
    progressBar = findViewById(R.id.progressBar);
    progressBar.setVisibility(View.GONE);
    mAuth = FirebaseAuth.getInstance();
    findViewById(R.id.register).setOnClickListener(this);
    findViewById(R.id.signin).setOnClickListener(this);
}

@Override
protected void onStart() {
    super.onStart();

    if (mAuth.getCurrentUser() != null) {
        Intent i = new Intent(RegisterActivity.this, HomeActivity.class);
        startActivity(i);
        finish();
    }
}

private void registerUser() {
    final String username = reg_username.getText().toString().trim();
    final String email = reg_email.getText().toString().trim();
    String password = reg_password.getText().toString().trim();


    if (username.equals("")) {
        reg_username.setError(getString(R.string.input_error_name));
        reg_username.requestFocus();
        return;
    }
    if (email.equals("")) {
        reg_email.setError(getString(R.string.input_error_email));
        reg_email.requestFocus();
        return;
    }else{
        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            reg_email.setError(getString(R.string.input_error_email_invalid));
            reg_email.requestFocus();
            return;
        }
    }

    if (password.equals("")) {
        reg_password.setError(getString(R.string.input_error_password));
        reg_password.requestFocus();
        return;
    }else{
    if (password.length() < 8) {
            reg_password.setError(getString(R.string.input_error_password_length));
            reg_password.requestFocus();
            return;
        }
    }

        progressBar.setVisibility(View.VISIBLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if (task.isSuccessful()) {

                            User user = new User(
                                    username,
                                    email
                            );

                            FirebaseDatabase.getInstance().getReference("Users")
                                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                    .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    progressBar.setVisibility(View.GONE);
                                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                    if (task.isSuccessful()) {
                                        Toast.makeText(RegisterActivity.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show();
                                        Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
                                        startActivity(i);
                                        finish();
                                    } else {
                                        Toast.makeText(RegisterActivity.this, getString(R.string.registration_failed), Toast.LENGTH_LONG).show();
                                    }
                                }
                            });

                        } else {
                            Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                });


}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.register:
                registerUser();
            break;
        case R.id.signin:
                Intent i = new Intent(this, LoginActivity.class);
                startActivity(i);
                finish();
            break;
        }

    }
}

error log:

09-03 13:25:24.942 15875-15875/com.example.zachmarcelo.softcash E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zachmarcelo.softcash, PID: 15875
android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class TextView
Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class TextView
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 4: TypedValue{t=0x2/d=0x1010099 a=1}
at android.content.res.TypedArray.getColor(TypedArray.java:492)
at android.widget.TextView.<init>(TextView.java:955)
at android.widget.TextView.<init>(TextView.java:872)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:75)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:71)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:783)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.widget.Editor.showError(Editor.java:505)
at android.widget.Editor.onFocusChanged(Editor.java:1237)
at android.widget.TextView.onFocusChanged(TextView.java:9821)
at android.view.View.handleFocusGainInternal(View.java:6631)
at android.view.View.requestFocusNoSearch(View.java:10890)
at android.view.View.requestFocus(View.java:10869)
at android.view.View.requestFocus(View.java:10836)
at android.view.View.requestFocus(View.java:10778)
at com.example.zachmarcelo.softcash.RegisterActivity.registerUser(RegisterActivity.java:74)
at com.example.zachmarcelo.softcash.RegisterActivity.onClick(RegisterActivity.java:143)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

and this is what is supposed to be happening: (works perfectly in name text but not in other edittexts)

screenshot of mobile app

any help will be appreciated :D


Answer:

My guess is that it has something to do with what you put into @style/TextLabel.

When you have an error with password or email you request focus programmatically. Which is fine, however when that happens something in your style is looking for a color resource which doesn't exist. That's what's causing the error.

Question:

I have to convert some numeric editText in double and after text changed do a simple math operation. Everything works fine except On Text Changed: it crash whatever I do (also to change TextView with "hello world").

Here's my code:

hEditText.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)
        {
            Double hDouble = Double.parseDouble(hEditText.toString());
            Double bDouble = Double.parseDouble(bEditText.toString());
            Double mDouble = Double.parseDouble(mEditText.getText().toString());
            Double miDouble = Double.parseDouble(miEditText.getText().toString());

            lResult.setText("" + Math.sqrt((hDouble * hDouble) + (bDouble * bDouble)));
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

LOG

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.cosmo.fisicapp, PID: 21198
              java.lang.NumberFormatException: empty String
                  at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1071)
                  at java.lang.Double.parseDouble(Double.java:547)
                  at com.example.cosmo.fisicapp.Equilibrio$1.afterTextChanged(Equilibrio.java:47)
                  at android.widget.TextView.sendAfterTextChanged(TextView.java:8525)
                  at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:10788)
                  at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1222)
                  at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:583)
                  at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:509)
                  at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:508)
                  at android.text.method.NumberKeyListener.onKeyDown(NumberKeyListener.java:121)
                  at android.widget.TextView.doKeyDown(TextView.java:6533)
                  at android.widget.TextView.onKeyDown(TextView.java:6323)
                  at android.view.KeyEvent.dispatch(KeyEvent.java:2742)
                  at android.view.View.dispatchKeyEvent(View.java:9949)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.widget.ScrollView.dispatchKeyEvent(ScrollView.java:391)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                  at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:439)
                  at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1861)
                  at android.app.Activity.dispatchKeyEvent(Activity.java:3141)
                  at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:535)
                  at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
                  at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2530)
                  at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:353)
                  at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4742)
                  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4713)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4249)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4302)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4268)
                  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4395)
                  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4276)
                  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4452)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4249)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4302)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4268)
                  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4276)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4249)
                  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6676)
                  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6650)
                  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6611)
                  at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3917)
                  at android.os.Handler.dispatchMessage(Handler.java:105)
                  at android.os.Looper.loop(Looper.java:156)
                  at android.app.ActivityThread.main(ActivityThread.java:6523)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)

E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)


Answer:

hEditText.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.equals("")){
            Double hDouble = Double.parseDouble(charSequence.toString());
            Double bDouble = Double.parseDouble(charSequence.toString());
            Double mDouble = Double.parseDouble(charSequence.getText().toString());
            Double miDouble = Double.parseDouble(charSequence.getText().toString());

            lResult.setText("" + Math.sqrt((hDouble * hDouble) + (bDouble * bDouble)));
           }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

Question:

I am trying to limit the edit text value to be less than or equal to 130. In the onCreate method, I did the following:

final EditText expectedYears = (EditText)findViewById(R.id.lifespan);
expectedYears.addTextChangedListener(new TextWatcher() {
      public void afterTextChanged(Editable s) {}
      public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
      }
      public void onTextChanged(CharSequence s, int start,
                                      int before, int count){
          if(Integer.parseInt(s.toString())>130){
                expectedYears.setText(String.valueOf(130));
          }

      }
});

I am not really sure why the app crashes after this. By testing, I figured out that the expectedYears.setText line is causing this. I feel like once I set the text, the onTextChanged function gets called again. How can I fix this?

Stack Trace

 at android.widget.EditText.setText(EditText.java:113)
 at android.widget.TextView.setText(TextView.java:5209
 at net.msolonko.motivation_app.MainActivity$1.onTextChanged(MainActivity.java:49) 
 at android.widget.TextView.sendOnTextChanged(TextView.java:9364)
 at android.widget.TextView.setText(TextView.java:5397)
 at android.widget.TextView.setText(TextView.java:5250)

Answer:

According to this question, you should not change the text of the EditText being watched in onTextChanged(). My guess is that it results in an infinite recursion loop.

Instead, try putting your logic setting the text in afterTextChanged().

Question:

The edittext have only one character limit, a delete button delete the character in edittext but the problem is when I pressed the delete btn in empty edittext. App becomes crash.

I have used below code but when I click on del btn in empty edittext , App crash.

del.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String text = et1.getText().toString();
                        et1.setText(text.substring(0, text.length() - 1));
                    }
                });

This error is display in logcat.

IInputConnectionWrapper: endBatchEdit on inactive InputConnection

Plz help me. Thanks in advance


Answer:

but the problem is when I pressed the delete btn in empty edittext. App becomes crash.

Yes, because you are trying to do a substring of a null, that's why it crashes, to avoid it, just add an if condition before doing the action as follows :

del.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      String text = et1.getText().toString();
      if(!text.isEmpty()) et1.setText(text.substring(0, text.length() - 1));
   }
});

Question:

I'm relatively new with Java and Android programming, and I'm working on a simple Android app where you put something into EdiTexts, have one Spinner and two buttons. The first button (buttonspremi) shows the Toast message, and that works okay. The second button (buttonponisti) should clear all the EditTexts, but it always crashes my app. Can you please tell me what am I doing wrong? Thanks!

public class Glavni extends ActionBarActivity {

private Button buttonspremi;
private Button buttonponisti;


public EditText editTextIme, editTextPrezime, editTextAdresa, editTextOib, editTextTelefon;
private RadioButton radioButtonMusko, radioButtonZensko;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_glavni);
    Spinner s = (Spinner) findViewById(R.id.spinnerGradovi);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(
            this, R.array.gradovi, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(
            android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(adapter);

    buttonspremi = (Button) findViewById(R.id.btnspremipodatke);

    buttonspremi.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Toast.makeText(getApplicationContext(), "Podaci su spremljeni", Toast.LENGTH_LONG).show();

        }
    });

    buttonponisti = (Button) findViewById(R.id.btnponisti);
    buttonponisti.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editTextIme.setText(" ");
            editTextPrezime.setText(" ");
            editTextAdresa.setText(" ");
            editTextOib.setText(" ");
            editTextTelefon.setText(" ");
        }

    });

}

Answer:

You have not initialized your references to the EditTexts you are trying to clear. You'll need to add lines like

editTextIme = (EditText) findViewById(R.id.editTextIme_id); editTextPrezime = ...

etc. for all the EditTexts inside your Activity's onCreate.

Question:

I need help please! Leaving the EditText empty causes my app to crash. I have gone through all the solutions on stackflow and google and nothing seems to solve it. The two errors in Logcat are:

java.lang.reflect.InvocationTargetException

and

java.lang.NumberFormatException: Invalid double: ""
package com.example.curencyconverter;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    @SuppressLint("DefaultLocale")
    public void convert(View view) {
        EditText inputEditText = (EditText) findViewById(R.id.inputEditText);
        double inputAmount = Double.parseDouble(inputEditText.getText().toString());
        try {
            inputAmount = Double.parseDouble(inputEditText.getText().toString());
        } catch (NumberFormatException e) {
            inputAmount = Double.parseDouble(null);
        }

        Double poundAmount = inputAmount * 0.75;
        Toast.makeText(MainActivity.this, "£" + String.format("%.2f", poundAmount), Toast.LENGTH_LONG).show();
        Log.i("Amount", inputEditText.getText().toString());
    }



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

XML File:

<?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=".MainActivity">

    <EditText
        android:id="@+id/inputEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/enter_amount"
        android:importantForAutofill="no"
        android:inputType="text"
        android:textAllCaps="false"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#F10606"
        android:textColorHint="#006064"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.07" />

    <Button
        android:id="@+id/converter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="convert"
        android:text="@string/converter"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputEditText"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>


Answer:

try-catch is not doing anything, as you have already invoked parseDouble unsafely (without try-catch) when initializing the variable. Just initialize it to something like 0 or any default value you want.

double inputAmount = 0;

Also, parseDouble(null) generates a NullPointerException. Set inputAmount to your default value in catch.

Question:

I don't even understand what's is this and why it doesn't work ok. I have button, which starts new activity. But before it, I check some values, and after clicking on the button - it's crashing .-. I don't know what to do, it doesn't work properly anyway. I'm writing on Code:

lateinit var string: String
var day: Int = 0
var month: Int = 0
var yearProp: Int = 0
var dayEnd: Int = 0
var monthEnd: Int = 0
var yearEndProp: Int = 0
var priceFrom: Int = 0
var priceTo: Int = 0
companion object {
    lateinit var props: Properties
}

override fun onDateSet(view: DatePickerDialog?, year: Int, monthOfYear: Int, dayOfMonth: Int, yearEnd: Int, monthOfYearEnd: Int, dayOfMonthEnd: Int) {
    day = dayOfMonth
    month = monthOfYear
    yearProp = year
    dayEnd = dayOfMonthEnd
    monthEnd = monthOfYearEnd
    yearEndProp = yearEnd
    button_whats_date.text = getString(R.string.title_from) + ": " + day + "/" + month + "/" + yearProp + " | " + getString(R.string.title_to) + ": " + dayEnd + "/" + monthEnd + "/" + yearEndProp
}    

param_done.setOnClickListener {
        if (input_price_from.getText().toString().matches("".toRegex()) || input_price_to.getText().toString().matches("".toRegex())) {
            priceFrom = 0; priceTo = 999999999
            Log.i("VALUES", "" + priceTo)
            if (Integer.parseInt(input_price_from.text.toString()) > Integer.parseInt(input_price_to.text.toString())) {
                Toast.makeText(this@MainActivity, getString(R.string.error_change_price), LENGTH_SHORT).show()
            } else {
                try {
                    props = Properties(string, int, int, int, int, int, int, priceFrom, priceTo)
                    val intent = Intent(this@MainActivity, SearchActivity::class.java)
                    startActivity(intent)
                } catch (e: Throwable) {
                    Toast.makeText(this@MainActivity, getString(R.string.props_error), LENGTH_SHORT).show()
                    Log.i("Hereissometex", "User cannot follow to next activity")
                }
            }
        }
    }


<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="12dp"
            android:layout_marginHorizontal="8dp"
            android:orientation="horizontal">
            <EditText
                android:id="@+id/input_price_from"
                android:inputType="number"
                android:layout_width="0dp"
                android:layout_height="60dp"
                android:layout_weight="2"
                android:textColor="#FFF"
                android:hint="@string/title_from"/>
            <EditText
                android:id="@+id/input_price_to"
                android:inputType="number"
                android:layout_width="0dp"
                android:layout_height="60dp"
                android:layout_weight="2"
                android:textColor="#FFF"
                android:hint="@string/title_to"/>
        </LinearLayout>
    </LinearLayout>
    <Button
        android:id="@+id/param_done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_marginBottom="10dp"
        android:background="@android:color/transparent"
        android:text="@string/done"
        android:textColor="@color/colorPrimary"/>
</FrameLayout>

And it's just crashing down. If you need something else - just give me a sign. There is how I do check input values:

input_price_from.addTextChangedListener(object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun afterTextChanged(s: Editable) {
            priceFrom = Integer.parseInt(input_price_from.text.toString())
        }
    })
    input_price_to.addTextChangedListener(object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun afterTextChanged(s: Editable) {
            priceTo = Integer.parseInt(input_price_to.text.toString())
            Log.i("[TravelMet::INFO]", "InputPrice value changed and parced")
        }
    })   

**EDIT**: Added log.


    E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: s.com.s, PID: 1979
                  java.lang.NumberFormatException: For input string: ""
                      at java.lang.Integer.parseInt(Integer.java:533)
                      at java.lang.Integer.parseInt(Integer.java:556)
                      at arsensaruhanyan.com.travelmet.MainActivity$onCreate$5.onClick(MainActivity.kt:110)
                      at android.view.View.performClick(View.java:6261)
                      at android.widget.TextView.performClick(TextView.java:11185)
                      at android.view.View$PerformClick.run(View.java:23752)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

101:
                    Toast.makeText(this@MainActivity, getString(R.string.error_change_price), LENGTH_SHORT).show()

Answer:

I guess the exception is pretty clear

java.lang.NumberFormatException: For input string: ""

change here and check the text is not empty and is of greater length

check if the text is not empty

try{
    if(input_price_from.text.toString().length()>0){
       //code goes here
     }
   }catch(e:NumberFormatException){
     e.printStackTrace()
   }