Как указать ошибку, если пользователь вводит буквы в текст редактирования для возраста?(Android Studio) - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь создать приложение, которое учитывает данные студентов.Часть этой детали - возраст учеников, который должен быть только числовым.Если буквы вводятся в поле для редактирования текста, приложение должно указывать на ошибку.

У меня есть код ниже, однако, похоже, что нет никаких изменений в приложении, так как оно все еще падает, когда я вводю букву длявозраст.

// XML-контент

 <LinearLayout  
 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="40dp"
android:background="#F0F8FF"
>

<TableLayout
    android:id="@+id/add_table"
    android:layout_width="match_parent"
    android:layout_height="606dp"
    android:paddingTop="40dp">

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Student ID:" />

        <EditText
            android:id="@+id/sid"
            android:layout_width="190dp"
            android:layout_height="wrap_content" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="First Name:" />

        <EditText
            android:id="@+id/fn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Last Name:" />

        <EditText
            android:id="@+id/ln"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:layout_marginTop="5dp"
            android:text="Gender:" />


        <RadioGroup
            android:id="@+id/ge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleX="0.9"
                android:scaleY="0.9"
                android:text="Male" />

            <RadioButton
                android:id="@+id/female"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:scaleX="0.9"
                android:scaleY="0.9"
                android:text="Female" />

        </RadioGroup>



    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Course Study:" />

        <EditText
            android:id="@+id/cs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:inputType="number"
            android:digits="0123456789"
            android:padding="3dip"
            android:text="Age:" />

        <EditText
            android:id="@+id/ag"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Address:" />

        <EditText
            android:id="@+id/ad"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />


    </TableRow>

    <Button
        android:id="@+id/add_button"
        android:layout_width="207dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="118dp"
        android:layout_marginRight="52dp"
        android:layout_marginTop="14dp"
        android:padding="6dip"
        android:text="Add Student" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        app:srcCompat="@mipmap/man" />

</TableLayout>

// Java

  package com.user.project3;

 import android.content.Intent;
 import android.os.Bundle;
 import android.support.annotation.IdRes;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.RadioButton;
 import android.widget.RadioGroup;
 import android.widget.Toast;

 public class Addrecord extends AppCompatActivity {

DatabaseManager myDb;
EditText sid, fn, ln, cs, ag, ad;
RadioGroup radioGenderGroup;
RadioButton radioGenderButton;

Button btnAddStudent;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(null);
    myDb = new DatabaseManager(this);

    sid = (EditText)findViewById(R.id.sid);
    fn = (EditText)findViewById(R.id.fn);
    ln = (EditText)findViewById(R.id.ln);
    cs = (EditText)findViewById(R.id.cs);
    ag = (EditText)findViewById(R.id.ag);
    ad = (EditText)findViewById(R.id.ad);
    btnAddStudent = (Button)findViewById(R.id.add_button);

    AddStudentRecord();

}



public  void AddStudentRecord() {
    btnAddStudent.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
                    int selectedid = radioGenderGroup.getCheckedRadioButtonId();
                    radioGenderButton = (RadioButton) findViewById(selectedid);

                    boolean isInserted = myDb.insertDataStudent(
                            Integer.parseInt(sid.getText().toString()),
                            fn.getText().toString(),
                            ln.getText().toString(),
                            radioGenderButton.getText().toString(),
                            cs.getText().toString(),
                            Integer.parseInt(ag.getText().toString()),
                            ad.getText().toString()


                    );


                    String strNumber=ag.getText().toString().trim();
                    if(TextUtils.isEmpty(strNumber) || Integer.parseInt(strNumber)>100){
                        Toast.makeText(Addrecord.this,"Please input a number",Toast.LENGTH_LONG).show();
                    }


                    if(isInserted == true)
                        Toast.makeText(Addrecord.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(Addrecord.this,"Data not Inserted",Toast.LENGTH_LONG).show();

                }
            }
    );
}


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

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

    //noinspection SimplifiableIfStatement

    if (id == R.id.home2) {
        Intent intent = new Intent(Addrecord.this, Home.class);
        startActivity(intent);
        return true;

    }

    if (id == R.id.viewarecord) {
        Intent intent = new Intent(Addrecord.this, Viewstudent.class);
        startActivity(intent);
        return true;

    }
    return super.onOptionsItemSelected(item);
}




 }

// журнал сбоев

         E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.supriya.project3, PID: 2274
              java.lang.NumberFormatException: For input string: "j"
                  at java.lang.Integer.parseInt(Integer.java:608)
                  at java.lang.Integer.parseInt(Integer.java:643)
                  at   
        com.supriya.project3.Addrecord$1.onClick(Addrecord.java:72)
                  at android.view.View.performClick(View.java:6891)
                  at   
        android.widget.TextView.performClick(TextView.java:12651)
                  at 
        android.view.View$PerformClick.run(View.java:26083)
                  at 
        android.os.Handler.handleCallback(Handler.java:789)
                  at 
        android.os.Handler.dispatchMessage(Handler.java:98)
                  at android.os.Looper.loop(Looper.java:164)
                  at 
        android.app.ActivityThread.main(ActivityThread.java:6938)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at 

com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
                  at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Application terminated.

Ответы [ 4 ]

0 голосов
/ 27 сентября 2018

Используйте это регулярное выражение, чтобы найти, содержит ли строка числа:

 Pattern pattern = Pattern.compile(".*[^0-9].*");  
 pattern.matcher(you input in edittext).matches());
0 голосов
/ 26 сентября 2018

Вы можете использовать android: inputType = "number".Если вы также хотите отфильтровать число, введенное пользователем, вы можете добавить TextChangeListener.

0 голосов
/ 26 сентября 2018
String strNumber = ag.getText().toString().trim();

if(TextUtils.isEmpty(strNumber)){
                 Toast.makeText(Addrecord.this,"Please input a number",Toast.LENGTH_LONG).show();
                }else{
 String regexStr = "^[0-9]*$";

if(your_editText.getText().toString().trim().matches(regexStr))
{
    //write code here for success
    your_editText.setError(null) // to clear any errors
}
else{
    your_editText.setError(“please insert numbers only”);
}
    }
 }
0 голосов
/ 26 сентября 2018

Попробуйте это

youredittext.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void afterTextChanged(Editable mEdit) 
        {
            String regexStr = "^[0-9]*$";

    if(your_editText.getText().toString().trim().matches(regexStr))
    {
        //write code here for success
    }
    else{
        // write code here on failure
    }
        }

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

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

дайте мне знать, если это работает или нет

...