package
com.example.sqlite;
import
java.util.ArrayList;
import
java.util.HashMap;
import
android.os.Bundle;
import
android.app.Activity;
import
android.app.ListActivity;
import
android.content.ContentValues;
import
android.database.Cursor;
import
android.database.sqlite.SQLiteDatabase;
import
android.view.Menu;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.SimpleAdapter;
public
class
MainActivity
extends
ListActivity {
private
SQLiteDatabase mDb;
Cursor mCursor;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
mDb = openOrCreateDatabase(
"mydb1.db"
,MODE_PRIVATE,
null
);
mDb.execSQL(
"drop table if exists my_table"
);
mDb.execSQL(
"create table my_table(_id integer primary key autoincrement, "
+
"studentId int not null, score int not null)"
);
mDb.execSQL(
"insert into my_table(studentId,score) values (60092418, 100);"
);
mDb.execSQL(
"insert into my_table(studentId,score) values (60092419, 90);"
);
mDb.execSQL(
"insert into my_table(studentId,score) values (60092420, 80);"
);
mCursor = mDb.query(
"my_table"
,
new
String[] {
"studentId"
,
"score"
},
null
,
null
,
null
,
null
,
"_id"
,
"5"
);
ArrayList<HashMap<String,String>> mList =
new
ArrayList<HashMap<String,String>>();
if
(mCursor !=
null
){
if
(mCursor.moveToFirst()){
do
{
HashMap<String,String> item =
new
HashMap<String,String>();
for
(
int
j=
0
; j<mCursor.getColumnCount(); j++){
item.put(mCursor.getColumnName(j), mCursor.getString(j));
}
mList.add(item);
}
while
(mCursor.moveToNext());
}
}
SimpleAdapter adapter =
new
SimpleAdapter(
this
,mList,android.R.layout.simple_list_item_2,
new
String[] {
"studentId"
,
"score"
},
new
int
[]{android.R.id.text1, android.R.id.text2});
setListAdapter(adapter);
setContentView(R.layout.activity_main);
Button insert = (Button)findViewById(R.id.insert);
Button delete = (Button)findViewById(R.id.delete);
insert.setOnClickListener(
new
OnClickListener(){
public
void
onClick(View v){
if
(v.getId()==R.id.insert){
mDb.execSQL(
"insert into my_table(studentId,score) values (0, 0);"
);
}
}
});
delete.setOnClickListener(
new
OnClickListener(){
public
void
onClick(View v){
if
(v.getId()==R.id.delete){
mDb.execSQL(
"delete from my_table where _id=1;"
);
}
}
});
}
@Override
public
boolean
onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return
true
;
}
}