공통 레이아웃 및 기본 컨트롤 사용 마스터하기
인터페이스 이미지 디스플레이 사용 마스터하기
SQLite 데이터베이스 생성 및 기본 작동 마스터하기
선형 레이아웃과 상대 레이아웃을 통해 활동 인터페이스를 구축하고, MainActivity에 논리 코드를 작성하고, 프로그램을 실행하고, 두 개의 연락처 정보를 입력하고 각각 "추가", "조회", "수정" 및 "삭제" 버튼을 클릭합니다. 연락처 정보 추가, 쿼리, 수정 및 삭제 기능을 실현합니다. 작업이 성공하면 팝업 메시지 내용을 통해 해당 작업이 표시됩니다. 다음 인터페이스는 참조용이며 기능에 따라 다른 인터페이스를 설계할 수 있습니다.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:id="@+id/ll1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:"
android:layout_marginLeft="10dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et1"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ll1"
android:id="@+id/ll2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="电话:"
android:layout_marginLeft="10dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et2"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ll2"
android:layout_marginTop="10dp"
android:id="@+id/ll3">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#5522"
android:layout_weight="1"
android:layout_marginLeft="10dp"
android:text="添加"
android:textColor="#000"
android:id="@+id/addBtn"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#5522"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:text="查询"
android:textColor="#000"
android:id="@+id/selectBtn"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#5522"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:text="修改"
android:textColor="#000"
android:id="@+id/updateBtn"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#5522"
android:layout_weight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="5dp"
android:text="删除"
android:textColor="#000"
android:id="@+id/deleteBtn"/>
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et3"
android:layout_below="@+id/ll3"
android:hint="请输入要查询或修改或删除的姓名:"
android:layout_marginLeft="10dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#5522"
android:layout_centerHorizontal="true"
android:layout_below="@+id/et3"
android:layout_marginTop="5dp"
android:textColor="#000"
android:text="条件查询"
android:id="@+id/conditional_query_btn"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/conditional_query_btn"
android:id="@+id/showInfo"
android:layout_marginLeft="10dp" />
</RelativeLayout>
원래 인터페이스에 조건 입력란을 추가하여 조건 조회, 수정, 삭제 시 사용자 이름으로 작업을 수행할 수 있도록 했습니다.
MainActivity.java
package com.example.shiyan5;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button add, select, update, delete, conditionalQueryBtn;
private EditText name, telNumber, conditionalQueryEt;
private TextView showInfo;
private SQLiteDatabase db;
private MyDbHelper myDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVeiw();
add.setOnClickListener(this);
select.setOnClickListener(this);
update.setOnClickListener(this);
delete.setOnClickListener(this);
conditionalQueryBtn.setOnClickListener(this);
conditionalQueryEt.setOnClickListener(this);
myDbHelper = new MyDbHelper(this, "MyDatabase.db", null, 669);
}
private void initVeiw() {
add = findViewById(R.id.addBtn);
select = findViewById(R.id.selectBtn);
update = findViewById(R.id.updateBtn);
delete = findViewById(R.id.deleteBtn);
name = findViewById(R.id.et1);
telNumber = findViewById(R.id.et2);
showInfo = findViewById(R.id.showInfo);
conditionalQueryEt = findViewById(R.id.et3);
conditionalQueryBtn = findViewById(R.id.conditional_query_btn);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.addBtn:
db = myDbHelper.getWritableDatabase();
String userName = name.getText().toString();
String telephoneNumber = telNumber.getText().toString();
//SQLiteDatabase的insert方法来添加
/* ContentValues contentValues = new ContentValues();
contentValues.put("userName", userName);
contentValues.put("telephoneNumber", telephoneNumber);
db.insert("user", null, contentValues);*///返回的是插入记录的索引号,也就是第多少条。
db.execSQL("insert into user(username,telephoneNumber) values(?,?)", new Object[]{userName, telephoneNumber});
db.close();
break;
case R.id.selectBtn:
db = myDbHelper.getReadableDatabase();
//Cursor: 结果集,有一个游标,游标会指向结果集中的某一条记录。
Cursor cursor = db.query("user", new String[]{"userName", "telephoneNumber"}, null, null, null, null, null, null);
showInfo.setText("查询结果:\n");
if (cursor.getCount()>0) {
Toast.makeText(this, "查询成功!!", Toast.LENGTH_SHORT).show();
while (cursor.moveToNext()) {
showInfo.append("姓名:" + cursor.getString(0) + "电话号码:" + cursor.getString(1) + "\n");
}
} else {
Toast.makeText(this, "一条数据都没有呢~~", Toast.LENGTH_SHORT).show();
}
cursor.close();
db.close();
break;
case R.id.conditional_query_btn:
db=myDbHelper.getReadableDatabase();
String conditionalQuery=conditionalQueryEt.getText().toString();
Cursor cursor1=db.query("user",new String[]{"userName", "telephoneNumber"},"userName=?",new String[]{conditionalQuery},null,null,null,null);
//Cursor cursor1 =db.rawQuery("select userName,telephoneNumber from user where userName=?",new String[]{conditionalQuery});
showInfo.setText("查询结果:\n");
if (cursor1.getCount()>0) {
Toast.makeText(this, "查询成功!!", Toast.LENGTH_SHORT).show();
while (cursor1.moveToNext()){
showInfo.append("姓名:" + cursor1.getString(0) + "电话号码:" + cursor1.getString(1) + "\n");
}
}else{
Toast.makeText(this, "没找到呢~~", Toast.LENGTH_SHORT).show();
}
cursor1.close();
db.close();
break;
case R.id.updateBtn:
db=myDbHelper.getWritableDatabase();
ContentValues contentValues1=new ContentValues();
String userName1 = name.getText().toString();
String telephoneNumber1= telNumber.getText().toString();
String conditionalQuery2=conditionalQueryEt.getText().toString();
contentValues1.put("userName", userName1);
contentValues1.put("telephoneNumber", telephoneNumber1);
int a=db.update("user",contentValues1,"userName=?",new String[]{conditionalQuery2});
if (a>0) {
Toast.makeText(this, "更改成功,共更改了"+a+"条数据", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "更改失败", Toast.LENGTH_SHORT).show();
}
//db.execSQL("update user set userName=?,telephoneNumber=? where userName=?",new Object[]{userName1,telephoneNumber1,conditionalQuery2});
db.close();
break;
case R.id.deleteBtn:
db=myDbHelper.getWritableDatabase();
String conditionalQuery1=conditionalQueryEt.getText().toString();
//db.execSQL("delete from user where userName=?",new Object[]{conditionalQuery1});
int i=db.delete("user","userName=?",new String[]{conditionalQuery1});//返回删除的条数。
if(i>0)
{
Toast.makeText(this, "删除成功,共删除了"+i+"条数据", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
}
db.close();
break;
}
}
class MyDbHelper extends SQLiteOpenHelper {
public MyDbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table user(user_id integer primary key autoincrement,userName varchar(10),telephoneNumber varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
}
추가, 삭제, 수정, 확인 두 가지 방법을 작성했는데, 첫 번째는 SQL 문을 직접 사용하여 동작하는 db.execSQL()이고, 두 번째는 SQLiteDatabase에서 제공하는 추가, 삭제, 수정, 확인 방법을 사용하는 방법입니다. : db.insert() db.query( ) db.update() db.delete().
ㅋ
하하하
조수에 대해 생각하고 있는데 정적 제동이란 무엇입니까?
산과 숲의 안개
, 은폐로 사용할 수 있습니까?
달과 별의 궤적은 군대의 궤적과 같습니다.
Fenglin은 Volcano 가장 중요하게 쓰는건
결국 전략을 짜는 건 나겠지 넌
결국 저항을 포기해
노을을 바라보고 넌 고개를 숙이고
슬프게 떠나가
군대의 나는 딱 맞으니까
걱정 안 해도 돼