简体   繁体   English

更新列的所有行sqlite Android

[英]Update all rows of a column sqlite Android

I'm new to sqlite, but I did try to solve this problem on my own: I tried various tutorials and answers here at stackoverflow, but without success. 我是sqlite的新手,但我确实尝试自己解决此问题:我在stackoverflow尝试了各种教程和答案,但没有成功。 You may recognise the code. 您可能会识别代码。 I couldn't find an example of code that I understood or could use for my case. 我找不到我理解或可以用于我的案例的代码示例。

I have an app where users can create characters by entering: their first name, their last name, their age. 我有一个应用程序,用户可以通过输入以下内容来创建角色:他们的名字,姓氏,年龄。

The user can press plus 1 year in which case I want all integers in the column age to increment by 1 and show this to the user. 用户可以按加1年,在这种情况下,我希望列年龄中的所有整数都增加1并显示给用户。 All the characters should obviously age by one year. 所有角色显然都应该老化一年。 This I can't accomplish in my app. 我无法在我的应用中完成此操作。

Could you please tell me how I should modify the code to accomplish what I want and could you maybe please explain how your code works? 您能告诉我如何修改代码以完成我想要的吗?您能否解释一下代码的工作原理?

MainActivity.java: 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();

        }
    });
}
}

DatabaseHelper.java: DatabaseHelper.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);
}
}

activity_main.xml: activity_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>

Assuming your issues are with the updateAgeInDatabase method. 假设问题出在updateAgeInDatabase方法上。

I believe your issue is with "ID = ?" 我相信您的问题是"ID = ?" . basically it is saying change the rows that have the ID column that equals the respective value in the where arguments string array (that's what the ? does). 基本上是说更改具有ID列的行,其中ID列等于where参数字符串数组中的相应值(这是?的作用)。 You are then passing the age, which may or may not match an ID. 然后,您要通过年龄,该年龄可能与ID匹配,也可能不匹配。

If you want to update ALL ages with a single value then use db.update(TBNAME,cv,null,null) . 如果要使用单个值更新所有年龄,请使用db.update(TBNAME,cv,null,null)

My guess is that you want to ADD 1 to ALL ages rather than set ages to a specific value. 我的猜测是,您想对所有年龄添加1,而不是将年龄设置为特定值。 If so then you could run a query using SET eg 如果是这样,那么您可以使用SET运行查询,例如

db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " =  " + AGE + " + 1", null);

MainActivity.java: MainActivity.java:

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


            characters.clear();

            db.openDB();

            Cursor c=db.getAllNames();

            c.moveToFirst();

            while(!c.isAfterLast()) {
                c.moveToLast();
                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();
        }
    });

DatabaseHelper.java: DatabaseHelper.java:

public boolean updateAgeInDatabase(String age) {
    db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " =  " + AGE + " + 1");
    return true;
}

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

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