2013-05-09 43 views
0

我想將網站詳細信息添加到數據庫,然後在插入一行後,將結果輸出到TextView。記錄被插入到數據庫中,因爲它被顯示在TextView中,但是我只能插入一條記錄,我不知道爲什麼。我一直在使用教程here並修改它以滿足我的需求。不能添加多條記錄,ID不能自動識別

這是我將對DBAdapter:

public class DBAdapter { 

    // /////////////////////////////////////////////////////////////////// 
    // Constants & Data 
    // /////////////////////////////////////////////////////////////////// 
    // For logging: 
    private static final String TAG = "DBAdapter"; 

    // DB Fields 
    public static final String KEY_ROWID = "_id"; 
    public static final int COL_ROWID = 0; 
    /* 
    * CHANGE 1: 
    */ 
    // TODO: Setup your fields here: 
    public static final String KEY_NAME = "name"; 
    public static final String KEY_ADDRESS = "address"; 
    public static final String KEY_USERNAME = "username"; 
    public static final String KEY_PASSWORD = "password"; 
    public static final String KEY_PORT = "port"; 

    // TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...) 
    public static final int COL_NAME = 1; 
    public static final int COL_ADDRESS = 2; 
    public static final int COL_USERNAME = 3; 
    public static final int COL_PASSWORD = 4; 
    public static final int COL_PORT = 5; 

    public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME, 
      KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT }; 

    // DB info: it's name, and the table we are using (just one). 
    public static final String DATABASE_NAME = "Sites"; 
    public static final String DATABASE_TABLE = "SiteTable"; 
    // Track DB version if a new version of your app changes the format. 
    public static final int DATABASE_VERSION = 2; 

    private static final String DATABASE_CREATE_SQL = "create table " 
      + DATABASE_TABLE 
      + " (" 
      + KEY_ROWID 
      + " integer primary key autoincrement, " 

      /* 
      * CHANGE 2: 
      */ 
      // TODO: Place your fields here! 
      // + KEY_{...} + " {type} not null" 
      // - Key is the column name you created above. 
      // - {type} is one of: text, integer, real, blob 
      // (http://www.sqlite.org/datatype3.html) 
      // - "not null" means it is a required field (must be given a 
      // value). 
      // NOTE: All must be comma separated (end of line!) Last one must 
      // have NO comma!! 
      + KEY_NAME + " string not null, " + KEY_ADDRESS 
      + " string not null, " + KEY_USERNAME + " string not null, " 
      + KEY_PASSWORD + " string not null, " + KEY_PORT 
      + " integer not null" 

      // Rest of creation: 
      + ");"; 

    // Context of application who uses us. 
    private final Context context; 

    private DatabaseHelper myDBHelper; 
    private SQLiteDatabase db; 

    // /////////////////////////////////////////////////////////////////// 
    // Public methods: 
    // /////////////////////////////////////////////////////////////////// 

    public DBAdapter(Context ctx) { 
     this.context = ctx; 
     myDBHelper = new DatabaseHelper(context); 
    } 

    // Open the database connection. 
    public DBAdapter open() { 
     db = myDBHelper.getWritableDatabase(); 
     return this; 
    } 

    // Close the database connection. 
    public void close() { 
     myDBHelper.close(); 
    } 

    // Add a new set of values to the database. 
    public long insertRow(String name, String address, String username, 
      String password, int port) { 
     /* 
     * CHANGE 3: 
     */ 
     // TODO: Update data in the row with new fields. 
     // TODO: Also change the function's arguments to be what you need! 
     // Create row's data: 
     ContentValues initialValues = new ContentValues(); 
     initialValues.put(KEY_NAME, name); 
     initialValues.put(KEY_ADDRESS, address); 
     initialValues.put(KEY_USERNAME, username); 
     initialValues.put(KEY_PASSWORD, password); 
     initialValues.put(KEY_PORT, port); 
     // Insert it into the database. 
     return db.insert(DATABASE_TABLE, null, initialValues); 
    } 

    // Delete a row from the database, by rowId (primary key) 
    public boolean deleteRow(long rowId) { 
     String where = KEY_ROWID + "=" + rowId; 
     return db.delete(DATABASE_TABLE, where, null) != 0; 
    } 

    public void deleteAll() { 
     Cursor c = getAllRows(); 
     long rowId = c.getColumnIndexOrThrow(KEY_ROWID); 
     if (c.moveToFirst()) { 
      do { 
       deleteRow(c.getLong((int) rowId)); 
      } while (c.moveToNext()); 
     } 
     c.close(); 
    } 

    // Return all data in the database. 
    public Cursor getAllRows() { 
     String where = null; 
     Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, 
       null, null, null); 
     if (c != null) { 
      c.moveToFirst(); 
     } 
     return c; 
    } 

    // Get a specific row (by rowId) 
    public Cursor getRow(long rowId) { 
     String where = KEY_ROWID + "=" + rowId; 
     Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, 
       null, null, null); 
     if (c != null) { 
      c.moveToFirst(); 
     } 
     return c; 
    } 

    // Change an existing row to be equal to new data. 
    public boolean updateRow(long rowId, String name, String address, 
      String username, String password, String port) { 
     String where = KEY_ROWID + "=" + rowId; 

     /* 
     * CHANGE 4: 
     */ 
     // TODO: Update data in the row with new fields. 
     // TODO: Also change the function's arguments to be what you need! 
     // Create row's data: 
     ContentValues newValues = new ContentValues(); 
     newValues.put(KEY_NAME, name); 
     newValues.put(KEY_ADDRESS, address); 
     newValues.put(KEY_USERNAME, username); 
     // newValues.put(KEY_PASSWORD, password); 
     // newValues.put(KEY_PORT, port); 

     // Insert it into the database. 
     return db.update(DATABASE_TABLE, newValues, where, null) != 0; 
    } 

    // /////////////////////////////////////////////////////////////////// 
    // Private Helper Classes: 
    // /////////////////////////////////////////////////////////////////// 

    /** 
    * Private class which handles database creation and upgrading. Used to 
    * handle low-level database access. 
    */ 
    private static class DatabaseHelper extends SQLiteOpenHelper { 
     DatabaseHelper(Context context) { 
      super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 

     @Override 
     public void onCreate(SQLiteDatabase _db) { 
      _db.execSQL(DATABASE_CREATE_SQL); 
     } 

     @Override 
     public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) { 
      Log.w(TAG, "Upgrading application's database from version " 
        + oldVersion + " to " + newVersion 
        + ", which will destroy all old data!"); 

      // Destroy old database: 
      _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 

      // Recreate new database: 
      onCreate(_db); 
     } 
    } 
} 

我在這裏查詢數據庫:

public class FTPConnector extends Activity { 
DBAdapter myDb; 
    public void onCreate(Bundle icicle) { 
      super.onCreate(icicle); 
      setContentView(R.layout.ftp); 

      status = (TextView) findViewById(R.id.status); 
      editAddress = (EditText) findViewById(R.id.editAddress); 
      editUser = (EditText) findViewById(R.id.editUsername); 
      editPassword = (EditText) findViewById(R.id.editPassword); 
      addsiteBtn = (Button) findViewById(R.id.addsiteBtn); 
      addsiteBtn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        siteManager(); 

       } 
      }); 
      openDb(); 
     } 

     private void openDb() { 
      myDb = new DBAdapter(this); 
      myDb.open(); 

     } 

     @Override 
     protected void onDestroy() { 
      // TODO Auto-generated method stub 
      super.onDestroy(); 
      closeDb(); 
     } 

     private void closeDb() { 
      myDb.close(); 
     } 

     //Where the insertRecord() happens 
      public void siteManager() { 
        final AlertDialog customDialog = new AlertDialog.Builder(this).create(); 
        LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext() 
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
        View view = layoutInflater.inflate(R.layout.site_manager, null); 
        final EditText tmpname = (EditText) view 
          .findViewById(R.id.dialogsitename); 
        final EditText tmpaddress = (EditText) view 
          .findViewById(R.id.dialogaddress); 
        final EditText tmpuser = (EditText) view 
          .findViewById(R.id.dialogusername); 
        final EditText tmppass = (EditText) view 
          .findViewById(R.id.dialogpassword); 
        final EditText tmpport = (EditText) view.findViewById(R.id.dialogport); 
        final TextView tmpsites = (TextView) view.findViewById(R.id.textView6); 
        final CheckBox tmppassive = (CheckBox) view 
          .findViewById(R.id.dialogpassive); 
        final Button tmpclose = (Button) view.findViewById(R.id.closeBtn); 
        final Button tmptestBtn = (Button) view.findViewById(R.id.testBtn); 
        final Button tmpsavetsite = (Button) view.findViewById(R.id.saveSite); 

        customDialog.setView(tmpclose); 
        customDialog.setView(tmptestBtn); 
        customDialog.setView(tmpname); 
        customDialog.setView(tmpaddress); 
        customDialog.setView(tmpuser); 
        customDialog.setView(tmppass); 
        customDialog.setView(tmpport); 
        customDialog.setView(tmppassive); 
        customDialog.setView(tmpsavetsite); 
        customDialog.setView(tmpsites); 

        tmpclose.setOnClickListener(new OnClickListener() { 

         @Override 
         public void onClick(View v) { 
          customDialog.dismiss(); 
         } 
        }); 

        tmptestBtn.setOnClickListener(new OnClickListener() { 

         @Override 
         public void onClick(View v) { 
          _name = tmpname.getText().toString(); 
          _address = tmpaddress.getText().toString(); 
          _user = tmpuser.getText().toString(); 
          _pass = tmppass.getText().toString(); 
          _port = Integer.parseInt(tmpport.getText().toString()); 

          _passive = false; 
          if (tmppassive.isChecked()) { 
           _passive = true; 
          } 

          boolean status = ftpConnect(_address, _user, _pass, _port); 

          if (status == true) { 
           Toast.makeText(FTPConnector.this, "Connection Succesful", 
             Toast.LENGTH_LONG).show(); 
          } else { 
           Toast.makeText(FTPConnector.this, 
             "Connection Failed:" + status, Toast.LENGTH_LONG) 
             .show(); 

          } 
         } 
        }); 

        tmpsavetsite.setOnClickListener(new OnClickListener() { 

         @Override 
         public void onClick(View v) { 
          tmpsites.setText(""); 
          String msg = "!"; 
          _name = tmpname.getText().toString(); 
          _address = tmpaddress.getText().toString(); 
          _user = tmpuser.getText().toString(); 
          _pass = tmppass.getText().toString(); 
          _port = Integer.parseInt(tmpport.getText().toString()); 

          long newId = myDb.insertRow(_name, _address, _user, _pass, 21); 

          Cursor c = myDb.getAllRows(); 

          if (c.moveToFirst()) { 
           int id = c.getInt(0); 
           String _name = c.getString(1); 
           String _address = c.getString(2); 
           String _user = c.getString(3); 
           String _pass = c.getString(4); 
           int _port = c.getInt(5); 

           msg += "id=" + id + "\n"; 
           msg += ", name=" + _name + "\n"; 
           msg += ", address=" + _address + "\n"; 
           msg += ", username=" + _user + "\n"; 
           msg += ", password=" + _pass + "\n"; 
           msg += ", port=" + _port + "\n"; 

           while (c.moveToNext()); 
          } 
          c.close(); 
          // displayText(msg); 
          tmpsites.setText(msg); 
         } 
        }); 
        customDialog.setView(view); 
        customDialog.show(); 
       } 

爲什麼我不能添加多個記錄嗎?

回答

2

在這裏:

while (c.moveToNext()); //<<< 
目前沒有使用像 do-while任何環路通過光標迭代( 你忘了加與不同時塊)

。得到光標的所有數據,使用循環:

//more to the first row 
c.moveToFirst(); 

//iterate over rows 
for (int i = 0; i < c.getCount(); i++) { 

    // get all data here from current row.. 

    //move to the next row 
    c.moveToNext(); 
} 
//close the cursor 
c.close(); 

,並使用do-while你可以從當前行獲取所有值:

c.moveToFirst(); //more to the first row 
    do { 
     // get all data here from current row.. 
    } while (c.moveToNext());