java - Android 数据库 EditText NumberSigned

标签 java android database android-sqlite

我制作了一个带有两个编辑文本的 Android SQLDatabase。一个保存姓名,另一个保存一些号码。这是我的 Activity

 public class AccountActivity extends ActionBarActivity {

        int from_Where_I_Am_Coming = 0;
        private DBHelper mydb ;
        TextView name ;
        TextView amount;
        int id_To_Update = 0;

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

    name = (TextView) findViewById(R.id.input_name);
    amount = (TextView) findViewById(R.id.input_amount);

    mydb = new DBHelper(this);

    Bundle extras = getIntent().getExtras();
    if(extras !=null) {
        int Value = extras.getInt("id");
        if (Value > 0) {
            //means this is the view part not the add contact part.
            Cursor rs = mydb.getData(Value);
            id_To_Update = Value;
            rs.moveToFirst();
            String nam = rs.getString(rs.getColumnIndex(DBHelper.ACCOUNT_COLUMN_NAME));
            String amo = rs.getString(rs.getColumnIndex(DBHelper.ACCOUNT_COLUMN_AMOUNT));
            if (!rs.isClosed()) {
                rs.close();
            }
            Button b = (Button) findViewById(R.id.btn_save);
            b.setVisibility(View.INVISIBLE);

            name.setText((CharSequence) nam);
            name.setFocusable(false);
            name.setClickable(false);

            amount.setText((CharSequence) amo);
            amount.setFocusable(false);
            amount.setClickable(false);
        }
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    Bundle extras = getIntent().getExtras();
    if(extras !=null)
    {
        int Value = extras.getInt("id");
        if(Value>0){
            getMenuInflater().inflate(R.menu.menu_account, menu);
        }
        else{
            getMenuInflater().inflate(R.menu.menu_main, 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.action_settings) {
            return true;
        }

        switch(item.getItemId())
        {
            case R.id.Edit_Contact:
                Button b = (Button)findViewById(R.id.btn_save);
                b.setVisibility(View.VISIBLE);
                name.setEnabled(true);
                name.setFocusableInTouchMode(true);
                name.setClickable(true);

                amount.setEnabled(true);
                amount.setFocusableInTouchMode(true);
                amount.setClickable(true);

                return true;
            case R.id.Delete_Contact:

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage(R.string.deleteAccount)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                mydb.deleteAccount(id_To_Update);
                                Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User cancelled the dialog
                            }
                        });
                AlertDialog d = builder.create();
                d.setTitle("Are you sure");
                d.show();

                return true;

            default:
        return super.onOptionsItemSelected(item);
    }
}
    public void run(View view)
    {
        Bundle extras = getIntent().getExtras();
        if(extras !=null)
        {
            int Value = extras.getInt("id");
            if(Value>0){
                if(mydb.updateAccount(id_To_Update, name.getText().toString(), amount.getText().length())){
                    Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
                    startActivity(intent);
                }
                else{
                    Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
                }
            }
            else{
                if(mydb.insertAccount(name.getText().toString(), amount.getText().length())){
                }
                else{
                }
                Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
                startActivity(intent);
            }
        }
    }
}

这是我的 xml。

<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:background="#E0EEEE"
    tools:context="com.tubapps.accountdb.AccountActivity">

            <EditText
                android:id="@+id/input_name"
                android:layout_width="fill_parent"
                android:inputType="text"
                android:layout_height="wrap_content"
                android:hint="@string/account_name"
                android:layout_marginLeft="8dip"
                android:layout_marginRight="8dip" />

            <EditText
                android:id="@+id/input_amount"
                android:layout_width="fill_parent"
                android:inputType="numberSigned"
                android:layout_height="wrap_content"
                android:hint="@string/initial_value"
                android:layout_below="@+id/input_name"
                android:layout_marginLeft="8dip"
                android:layout_marginRight="8dip" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:adjustViewBounds="true"
        android:orientation="horizontal"
        android:showDividers="middle">

        <Button
            android:id="@+id/btn_cnc"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#FFFFFF"
            android:clickable="true"
            android:focusable="true"
            android:text="@string/cancel" />

        <Button
            android:id="@+id/btn_save"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="run"
            android:background="#FFFFFF"
            android:text="@string/save_income" />
    </LinearLayout>

</RelativeLayout>

这是我的 DBHelper。

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String ACCOUNT_TABLE_NAME = "accounts";
    public static final String ACCOUNT_COLUMN_ID = "id";
    public static final String ACCOUNT_COLUMN_NAME = "name";
    public static final String ACCOUNT_COLUMN_AMOUNT = "amount";

    private HashMap hp;

    public DBHelper(Context context)
    {
        super(context, DATABASE_NAME , null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table accounts " +
                        "(id integer primary key, name text,amount integer)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS accounts");
        onCreate(db);
    }

    public boolean insertAccount  (String name, Integer amount)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("name", name);
        contentValues.put("amount", amount);

        db.insert("accounts", null, contentValues);
        return true;
    }
    public Cursor getData(int id){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from accounts where id="+id+"", null );
        return res;
    }
    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, ACCOUNT_TABLE_NAME);
        return numRows;
    }
    public boolean updateAccount (Integer id, String name, Integer amount)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("amount", amount);
        db.update("accounts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteAccount (Integer id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("accounts",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }
    public ArrayList getAllAccounts()
    {
        ArrayList array_list = new ArrayList();
        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from accounts", null );
        res.moveToFirst();
        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(ACCOUNT_COLUMN_NAME)));
            res.moveToNext();
        }
        return array_list;
    }
}

当我插入数字时,它只保存数字 3。我不知道问题出在哪里。

最佳答案

您得到的是数字的“长度”,而不是这些行上的值:

amount.getText().length()

我怀疑你应该这样做:

Integer.valueOf(amount.getText())

关于java - Android 数据库 EditText NumberSigned,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28344718/

相关文章:

java - 允许用户在Java中搜索和删除ArrayList中的对象

android - arraylist返回错误的索引android

android - 我如何从 SQLITE 数据库获取数据到 android 中的数组?

mysql - 哪一种是更好的方法?

java - 如何获取类的 View ,该类扩展了扩展 fragment/Activity 等的类

java - 尽管有脚手架,Grails 应用程序仍不允许值修改

java - 如何从PDF中读取条件文本?

Java Swing : best way to set background image clickable

java - GCM : How to send heartbeat to GCM server

java - 获取随机按钮并设置特定值