2017-01-06 8 views
0

私はsqliteを初めて使っていますが、私はこの問題を自分で解決しようとしました:ここではさまざまなチュートリアルと答えをstackoverflowで試しましたが、あなたはコードを認識するかもしれません。私は、私が理解している、または私の場合に使用できるコードの例を見つけることができませんでした。カラムsqliteのすべての行を更新します。

私はユーザーが自分の名字、姓、年齢などを入力して文字を作成できるアプリを持っています。

ユーザーはプラス1年を押すことができます。この場合、列の年齢のすべての整数に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列を持つ行を変更することです(これは?)。 IDと一致する場合とそうでない場合がある年齢を渡しています。

すべての年齢を1つの値で更新する場合は、db.update(TBNAME,cv,null,null)を使用します。

私の推測では、年齢を特定の値に設定するのではなく、1歳からすべての年齢を追加するとします。その場合は、SETなどを使用してクエリを実行できます。

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

は、MikeT、ありがとうございました。私は本当にすべての年齢に1を追加したいと思います。 "execsql"は "execSQL"(首都)のようですが、あなたの提案はうまくいくように見えます。私はまだアプリケーションが最後のエントリに1を追加し、その値をすべてのエントリに適用するため、yearBtn.setOnClickListenerメソッドに問題があると思います。あなたは何か考えていますか? –

+0

oops yes execSQL、それに応じて回答が変更されました。 – MikeT

+0

上記の 'db.execSQL'だけでなく' db.update'も呼び出すようです。私はあなたがちょうど与えられた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; 
} 
関連する問題