MyDBClass.java
// Database Name
private static final String DATABASE_NAME = "Listyu";
// Table Name
private static final String TABLE_COUNTRY = "paylist";
public static final String[] ALL_KEYS = new String[] {"ID","Name","Amount"};
public myDBClass(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create Table Name
db.execSQL("CREATE TABLE " + TABLE_COUNTRY +
"(ID INTEGER PRIMARY KEY," +
" Amount INTEGER,"+
" Name TEXT(100));");
Log.d("CREATE TABLE","Create Table Successfully.");
}
// Insert Data
public long InsertData(String name, int amnt) {
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("Name", name);
Val.put("Amount", amnt);
long rows = db.insert(TABLE_COUNTRY, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
// Select Data
public Cursor SelectData() {
try {
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_COUNTRY, new String[] { "ID AS _id, *" },null, null, null, null, null);
if(cursor != null) {
return cursor;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
Create.java
在这个类中,我按如下方式插入了name(string)和amount(int),
String note = et.getText().toString();
String amount = ett.getText().toString();
int converted = Integer.parseInt(amount);
myDb.InsertData(note,converted);
List.java
在这个类中,我调用列表视图中插入的所有金额,如下所示,当打开list.java时程序不起作用。
myDb = new myDBClass(this);
ListView lisView1 = (ListView)findViewById(R.id.listView1);
final Cursor c = myDb.SelectData();
lisView1.setAdapter(new CountryAdapter(this, c ));
registerForContextMenu(lisView1);
public class CountryAdapter extends CursorAdapter
{
private Cursor cursor;
public CountryAdapter(Context context, Cursor cur) {
super(context, cur , 0);
this.cursor = cur;
}
@Override
public void bindView(View view, Context context, final Cursor cursor) {
// ColID
TextView txtID = (TextView) view.findViewById(R.id.textsv);
txtID.setText(cursor.getString(cursor.getColumnIndex("Amount")));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_layout, parent, false);
bindView(view, context, cursor);
return view;
}