public class DBExample extends Activity implements View.OnClickListener {
private TextView textArea1;
private EditText field1;
private EditText field2;
public static String newline = System.getProperty("line.separator");
private SQLiteDatabase db;
private static final String TAG = "DBExample";
private static final String DBNAME = "sample1";
private static final String TABLE1NAME = "table1";
private static final String CREATE_TABLE1 = "create table if not exists "
+ " table1 (id integer primary key autoincrement, "
+ " text1 text not null, text2 text not null);";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
field1 = (EditText) findViewById(R.id.field1);
field2 = (EditText) findViewById(R.id.field2);
Button saveButton = (Button) findViewById(R.id.button1);
saveButton.setOnClickListener(this);
Button deleteButton = (Button) findViewById(R.id.delbutton);
deleteButton.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
deleteAllRows();
}
});
Button showAllButton = (Button) findViewById(R.id.showallbutton);
showAllButton.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
showAllValues();
}
});
textArea1 = (TextView) findViewById(R.id.textarea1);
openDatabase();
//insertRow("hello1", "db1");
}
private void openDatabase() {
try {
db = openOrCreateDatabase(DBNAME, MODE_WORLD_WRITEABLE, null);
db.execSQL(CREATE_TABLE1);
}
catch (Exception e){
Log.i(TAG, "Error opening DB or creating new DB. " + e);
}
}
private boolean insertRow(String value1, String value2) {
ContentValues values = new ContentValues();
values.put("text1", value1);
values.put("text2", value2);
return (db.insert(TABLE1NAME, null, values) > 0);
}
private boolean deleteAllRows() {
textArea1.setText("Deleted All Values in Table: "+TABLE1NAME);
return (db.delete(TABLE1NAME, "id>=0", null) > 0);
}
public List
ArrayList
try {
Cursor c = db.query(TABLE1NAME, new String[] { "id", "text1", "text2" }, null,
null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Table1Items item = new Table1Items();
item.id = c.getLong(0);
item.text1 = c.getString(1);
item.text2 = c.getString(2);
dbRows.add(item);
c.moveToNext();
}
} catch (Exception e) {
Log.e(TAG, "Error in getting items from db: " + e);
}
return dbRows;
}
/*
*
* clicked on button "Insert Values"
*
*/
public void onClick(View arg0) {
textArea1.setText("");
insertRow(field1.getText().toString(), field2.getText().toString());
textArea1.append("inserted: "+field1.getText() + ", " + field2.getText().toString());
field1.setText("");
field2.setText("");
}
private void showAllValues() {
textArea1.setText("");
ArrayList
for (Iterator
Table1Items item = it.next();
textArea1.append(item.toString() + newline);
}
}
}
What is your setup to run this program?
回覆刪除Ray
Raykong@bloomsbi.com