简体   繁体   English

如何停止 function 允许字符串或字符? (安卓)

[英]How to stop function allowing Strings or Characters? (Android)

I'm creating an inventory app that allows users to enter enter items with three different information fields.我正在创建一个库存应用程序,允许用户输入具有三个不同信息字段的输入项目。 These fields are item name, item owner and item number.这些字段是项目名称、项目所有者和项目编号。

However, when I input a string or character into the item number field, the app crashes.但是,当我在项目编号字段中输入字符串或字符时,应用程序会崩溃。 I want to prevent this crashing by not allowing for characters to be entered in this field only.我想通过不允许仅在此字段中输入字符来防止这种崩溃。 I've tried a several fixes, but none seem to have worked so far.我已经尝试了几个修复,但到目前为止似乎没有一个有效。

Is there anyway to specifically check for string types and prevent using them?有没有专门检查字符串类型并防止使用它们?

Here is my addItem function:这是我的 addItem function:

public class AddItem extends AppCompatActivity {

    // Setting up variable names for XML object items
    EditText mItemName;
    EditText mOwnerName;
    EditText mItemNum;
    Button mAddButton;

    @Override
    //Initializing object variables and the addButton setOnClickListener
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_item);
        mItemName = findViewById(R.id.itemName_input);
        mOwnerName = findViewById(R.id.owner_input);
        mItemNum = findViewById(R.id.num_input);
        mAddButton = findViewById(R.id.add_button);

        //This click listener sets up functionality for the add item button. The addItem method is called from the MyDBHelper class.
        mAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //TESTING
                String itemName = mItemName.getText().toString().trim();
                String itemOwner = mOwnerName.getText().toString().trim();
                String itemNum = mItemNum.getText().toString().trim();

                //This IF/ELSE branch checks to see if any fields in AddItem are empty. If so, an error message displays. Else, it is entered into the database.
                if(itemName.equals("")||itemOwner.equals("")||itemNum.equals("")) {
                    Toast.makeText(AddItem.this, "Please enter data to all fields!", Toast.LENGTH_SHORT).show();
                }
                else {
                    MyDBHelper myDatabase = new MyDBHelper(AddItem.this);
                    myDatabase.addItem(mItemName.getText().toString().trim(), mOwnerName.getText().toString().trim(), Integer.valueOf(mItemNum.getText().toString().trim()));

                    //This will add functionality to return to the DisplayInventory Screen after pressing button.
                    Intent intent = new Intent(AddItem.this, DisplayInventory.class);
                    startActivity(intent);
                    finish();
                }
            }
        });


    }
}

Here is the database the function is using:这是 function 正在使用的数据库:

public class MyDBHelper extends SQLiteOpenHelper {

    // Setting up all variables that make up the columns in the database.
    private Context context;
    private static final String DATABASE_NAME = "InventoryList.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "my_list";
    private static final String COLUMN_ID = "_id";
    private static final String COLUMN_TITLE = "item_name";
    private static final String COLUMN_OWNER = "item_owner";
    private static final String COLUMN_NUM = "item_num";


    MyDBHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    //Initializing the Database
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String query =
                "CREATE TABLE " + TABLE_NAME +
                        " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        COLUMN_TITLE + " TEXT, " +
                        COLUMN_OWNER + " TEXT, " +
                        COLUMN_NUM + " INTEGER);";
        sqLiteDatabase.execSQL(query);



    }

    @Override
    //This will make sure to erase the table if one already exists.
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(sqLiteDatabase);

    }

    //This method is adding functionality to add the item name, owner and number of items.
    void addItem(String itemName, String itemOwner, int numItem) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_TITLE, itemName);
        cv.put(COLUMN_OWNER, itemOwner);
        cv.put(COLUMN_NUM, numItem);
        long result = db.insert(TABLE_NAME, null, cv);

        if (result == -1) {
            Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(context, "Item Added to Inventory!", Toast.LENGTH_SHORT).show();
        }
    }

    //This method sets up the functionality to search the entire database and read the data.
    Cursor readAllData() {
        String query = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;

        if (db != null) {
           cursor = db.rawQuery(query, null);
        }
        return cursor;
    }

    //This method allows the user to update the item's data. Values that will be updated are item name, owner and number of items.
    void updateData(String row_id, String item_name, String item_owner, String item_num) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_TITLE, item_name);
        cv.put(COLUMN_OWNER, item_owner);
        cv.put(COLUMN_NUM, item_num);
        long result = db.update(TABLE_NAME, cv, "_id=?", new String[]{row_id});
    }

    void deleteItem(String row_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        long result = db.delete(TABLE_NAME, "_id=?", new String[]{row_id});

    }

    void destroyInventory() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_NAME);
    }

}

You need to use android:inputType="number" property in your xml for EditText for itemNumber .您需要在您的 xml android:inputType="number"属性用于itemNumberEditText That way user won't be able to enter any character to that input field.这样用户将无法在该输入字段中输入任何字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM