import
android.content.ContentValues;
public class
MainActivity
extends
AppCompatActivity
implements
View.OnClickListener{
Button
btnAdd
,
btnRead
,
btnClear
; EditText
etName
,
etNumb
;
DBWork
dbWork
; @Override
protected
void
onCreate(Bundle
savedInstanceState)
{
super
.onCreate(savedInstanceState); setContentView(R.layout.
activity_main
);
btnAdd
= (Button) findViewById(R.id.
btnRecord
);
btnAdd
.setOnClickListener(
this
);
btnRead
= (Button) findViewById(R.id.
btnReading
);
btnRead
.setOnClickListener(
this
);
btnClear
= (Button) findViewById(R.id.
btnRemoval
);
btnClear
.setOnClickListener(
this
);
etName
=
(EditText) findViewById(R.id.
etName
);
etNumb
=
(EditText)
findViewById(R.id.
etNumb
);
dbWork
=
new
DBWork(
this
);
}
@Override
public void
onClick(View v) {
String
name
=
etName
.getText().toString();
String
numb
=
etNumb
.getText().toString();
SQLiteDatabase database =
dbWork
.getWritableDatabase();
85
ContentValues contentValues =
new
ContentValues();
switch
(v.getId()) {
case
R.id.
btnRecord
:
contentValues.put(DBWork.
KEY_NAME
,
name);
contentValues.put(DBWork.
KEY_NUMBER
,
numb);
database.insert(DBWork.
TABLE_CONTACTS
,
null
,
contentValues);
break
;
case
R.id.
btnReading
: Cursor cursor =
database.query(DBWork.
TABLE_CONTACTS
,
null
,
null
,
null
,
null
,
null
,
null
);
if
(cursor.moveToFirst()) {
int
idIndex = cursor.getColumnIndex(DBWork.
KEY_ID
);
int
nameIndex = cursor.getColumnIndex(DBWork.
KEY_NAME
);
int
numbIndex = cursor.getColumnIndex(DBWork.
KEY_NUMBER
);
do
{
Log.
d
(
"mLog"
,
"ID = "
+ cursor.getInt(idIndex) +
", name = "
+
cursor.getString(nameIndex) +
", numb = "
+ cursor.getString(numbIndex));
}
while
(cursor.moveToNext()); }
else
Log.
d
(
"mLog"
,
"0 rows"
); cursor.close();
break
;
case
R.id.
btnRemoval
: database.delete(DBWork.
TABLE_CONTACTS
,
null
,
null
);
break
;
}
dbWork
.close();
}
}
86
Листинг DBWork.java
package
ru.omgtu.myapplication;
import
android.content.Context;
import
android.database.sqlite.SQLiteDatabase;
import
android.database.sqlite.SQLiteOpenHelper;
public
class
DBWork
extends
SQLiteOpenHelper {
public static final int
DATABASE_VERSION
= 1;
public static final
String
DATABASE_NAME
=
"phoneDb"
;
public static final
String
TABLE_CONTACTS
=
"contacts"
;
public static final
String
KEY_ID
=
"_id"
;
public static final
String
KEY_NAME
=
"name"
;
public static final
String
KEY_NUMBER
=
"number"
;
public
DBWork(Context context) {
super
(context,
DATABASE_NAME
,
null
,
DATABASE_VERSION
);
}
@Override
public void
onCreate(SQLiteDatabase db) { db.execSQL(
"create table "
+
TABLE_CONTACTS
+
"("
+
KEY_ID
+
" integer primary key,"
+
KEY_NAME
+
" text,"
+
KEY_NUMBER
+
" text"
+
")"
);
}
@Override
public void
onUpgrade(SQLiteDatabase db,
int
oldVersion,
int
newVersion) {
db.execSQL(
"drop table if exists "
+
TABLE_CONTACTS
); onCreate(db);
}
}
87
Достарыңызбен бөлісу: |