我是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();
}
});
}
}
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中:
<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>
答案 0 :(得分:2)
假设您的问题采用distinct
方法。
我相信您的问题是updateAgeInDatabase
。基本上它是说改变具有ID列的行等于where参数字符串数组中的相应值(&具有什么?)。您正在传递年龄,该年龄可能与ID匹配,也可能不匹配。
如果您想使用单个值更新所有年龄段,请使用"ID = ?"
。
我的猜测是你希望将1添加到所有年龄而不是将年龄设置为特定值。如果是,那么您可以使用 db.update(TBNAME,cv,null,null)
例如
SET
答案 1 :(得分:1)
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:
public boolean updateAgeInDatabase(String age) {
db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " = " + AGE + " + 1");
return true;
}