更新 SQLite Android 列的所有行

Pet*_*ans 1 java sqlite android sql-update android-sqlite

我是 sqlite 的新手,但我确实尝试自己解决这个问题:我在 stackoverflow 上尝试了各种教程和答案,但没有成功。您可能认识该代码。我找不到我理解或可以用于我的案例的代码示例。

我有一个应用程序,用户可以通过输入以下内容来创建角色:他们的名字、姓氏、年龄。

用户可以按 + 1 年,在这种情况下,我希望年龄列中的所有整数都增加 1 并向用户显示。所有角色显然都应该老一岁。这是我无法在我的应用程序中完成的。

您能否告诉我应该如何修改代码来完成我想要的事情,您能否解释一下您的代码是如何工作的?

MainActivity.java:

public class MainActivity extends Activity {

ListView lv;
EditText firstnameTxt,familynameTxt,ageTxt;
Button savebtn,retrieveBtn,yearBtn;
ArrayList<String> characters=new ArrayList<String>();

ArrayAdapter<String> adapter;

String updatedAge;

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

    firstnameTxt=(EditText) findViewById(R.id.firstnameTxt);
    familynameTxt=(EditText) findViewById(R.id.familynameTxt);
    ageTxt=(EditText) findViewById(R.id.ageTxt);

    savebtn=(Button) findViewById(R.id.saveBtn);
    retrieveBtn=(Button) findViewById(R.id.retrievebtn);
    yearBtn=(Button) findViewById(R.id.yearBtn);

    lv=(ListView) findViewById(R.id.listView1);
    lv.setBackgroundColor(Color.LTGRAY);

    adapter=new ArrayAdapter<String>(this,android.R.layout.simple_selectable_list_item,characters);

    final DatabaseHelper db=new DatabaseHelper(this);

    //EVENTS
    savebtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            //OPEN
            db.openDB();

            //INSERT
            long result=db.add(firstnameTxt.getText().toString(),familynameTxt.getText().toString(),ageTxt.getText().toString());

            if(result > 0)
            {
                firstnameTxt.setText("");
                familynameTxt.setText("");
                ageTxt.setText("");
            }else
            {
                Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
            }


            //CLOSE DB
            db.close();
        }
    });

    yearBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            characters.clear();

            db.openDB();

            Cursor c=db.getAllNames();

            c.moveToFirst();

            while(!c.isAfterLast()) {
            //while(c.moveToFirst()) {
                int age = c.getInt(3);
                updatedAge = String.valueOf(age);
                boolean isUpdate = db.updateAgeInDatabase(updatedAge);
                if (isUpdate == true)
                    Toast.makeText(MainActivity.this, "Data successfully updated", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(MainActivity.this, "Data updated FAILED", Toast.LENGTH_LONG).show();
                c.moveToNext();
            }


            lv.setAdapter(adapter);

            db.close();
        }
    });

    //RETRIEVE
    retrieveBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            characters.clear();

            //OPEN
            db.openDB();

            //RETRIEVE
            Cursor c=db.getAllNames();

            while(c.moveToNext())
            {
                String firstname=c.getString(1);
                String familyname=c.getString(2);
                int age=c.getInt(3);
                characters.add(firstname + " " + familyname + ": " + age);
            }

            lv.setAdapter(adapter);

            db.close();

        }
    });

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int age,
                                long id) {
            // TODO Auto-generated method stub

            Toast.makeText(getApplicationContext(), characters.get(age), Toast.LENGTH_SHORT).show();

        }
    });
}
}
Run Code Online (Sandbox Code Playgroud)

数据库助手.java:

public class DatabaseHelper {

//COLUMNS
static final String ROWID="id";
static final String FIRSTNAME = "firstname";
static final String FAMILYNAME = "familyname";
static final String AGE = "age";

//DB PROPERTIES
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';

static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
        + "firstname TEXT NOT NULL,familyname TEXT NOT NULL,age INTEGER NOT NULL);";

final Context c;
SQLiteDatabase db;
DBHelper helper;

public DatabaseHelper(Context ctx) {
    // TODO Auto-generated constructor stub

    this.c=ctx;
    helper=new DBHelper(c);
}

// INNER HELPER DB CLASS
private static class DBHelper extends SQLiteOpenHelper
{

    public DBHelper(Context context ) {
        super(context, DBNAME, null, DBVERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        try
        {
            db.execSQL(CREATE_TB);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        Log.w("DBAdapter","Upgrading DB");

        db.execSQL("DROP TABLE IF EXISTS m_TB");

        onCreate(db);
    }

}

// OPEN THE DB
public DatabaseHelper openDB()
{
    try
    {
        db=helper.getWritableDatabase();

    }catch(SQLException e)
    {
        Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
    }

    return this;
}


//CLOSE THE DB
public void close()
{
    helper.close();
}

//INSERT INTO TABLE
public long add(String firstname,String familyname,String age)
{
    try
    {
        ContentValues cv=new ContentValues();
        cv.put(FIRSTNAME, firstname);
        cv.put(FAMILYNAME, familyname);
        cv.put(AGE, age);

        return db.insert(TBNAME, ROWID, cv);

    }catch(SQLException e)
    {
        e.printStackTrace();
    }

    return 0;
}

public boolean updateAgeInDatabase(String age) {   //or the problem is here
    //SQLiteDatabase db = this.getWritableDatabase(); //"getWritableDatabase" stays red
    ContentValues cv = new ContentValues();
    cv.put(AGE, age);
    //db.update(TBNAME, cv, "ID = ?", new String[] { age });   this is the line I replaced with MikeT's code right down here
    db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " = 1 + ? ", new String[] { age } );
    return true;
}

//GET ALL VALUES

public Cursor getAllNames()
{
    String[] columns={ROWID,FIRSTNAME,FAMILYNAME,AGE};

    return db.query(TBNAME, columns, null, null, null, null, null);
    //return db.rawQuery("select * from "+TBNAME,null);
}
}
Run Code Online (Sandbox Code Playgroud)

活动_main.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: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=".MainActivity" >

<Button
    android:id="@+id/saveBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/ageTxt"
    android:layout_marginTop="34dp"
    android:text="Save" />

<EditText
    android:id="@+id/firstnameTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:layout_toRightOf="@+id/saveBtn"
    android:ems="10" />

<EditText
    android:id="@+id/familynameTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/firstnameTxt"
    android:layout_below="@+id/firstnameTxt"
    android:ems="10" />

<EditText
    android:id="@+id/ageTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/firstnameTxt"
    android:layout_below="@+id/familynameTxt"
    android:ems="10" >
</EditText>

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/familynameTxt"
    android:layout_alignParentLeft="true"
    android:text="Firstname"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/ageTxt"
    android:layout_alignParentLeft="true"
    android:text="Familyname"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/ageTxt"
    android:layout_alignParentLeft="true"
    android:text="Age"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/saveBtn"
    android:layout_marginRight="16dp"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

    </ListView>

</LinearLayout>

<Button
    android:text="+1 year"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/retrievebtn"
    android:layout_centerHorizontal="true"
    android:id="@+id/yearBtn" />

<Button
    android:id="@+id/retrievebtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Retrieve"
    android:layout_above="@+id/linearLayout1"
    android:layout_alignParentEnd="true" />


</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

Mik*_*keT 5

假设您的问题与 updateAgeInDatabase方法有关。

我相信你的问题与"ID = ?". 基本上,它是说更改 ID 列等于 where 参数字符串数组中相应值的行(这就是 ? 的作用)。您就已经过了年龄,该年龄可能与身份证件匹配,也可能不匹配。

如果您想使用单个值更新所有年龄,请使用db.update(TBNAME,cv,null,null)

我的猜测是,您想要将所有年龄添加 1,而不是将年龄设置为特定值。SET如果是这样,那么您可以使用例如运行查询

db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " =  " + AGE + " + 1", null);
Run Code Online (Sandbox Code Playgroud)