2017-01-06 108 views
0

我是新来的sqlite,但我尝试自己解决这个问题:我尝试了各种教程和答案在这里在stackoverflow,但没有成功。您可能会认出代码。我无法找到我理解或可用于我的案例的代码示例。更新列sqlite的所有行Android

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

用户可以按加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> 

回答

1

假设你的问题是与updateAgeInDatabase方法。

我相信你的问题是"ID = ?"。基本上它是说改变ID列的行数等于where参数字符串数组中相应的值(这是什么?)。然后,您将通过可能符合或不符合身份证明的年龄。

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

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

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

谢谢你,MikeT。我确实希望为所有年龄添加1。您的建议似乎可行,但“execsql”似乎是“execSQL”(首都)。我认为我仍然在使用yearBtn.setOnClickListener方法时遇到问题,因为该应用现在将1添加到最后一个条目并将该值应用于所有条目。你有什么主意吗? –

+0

oops是execSQL,回答相应改变。 – MikeT

+0

这听起来像你可能正在调用'db.update'以及上面给出的'db.execSQL'。我想你只是想使用给定的db.execSQL。也许你应该更新你的问题,以包含更新的代码。 – MikeT

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; 
}