如何在Android应用程序中使用SQLite数据库?


此示例演示了如何在Android应用程序中使用SQLite数据库。

步骤1 - 在Android Studio中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。

步骤2 - 将以下代码添加到res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
   <ListView
      android:id="@+id/listView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:dividerHeight="1dp"
      android:padding="10dp" >
   </ListView>
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="" />
</RelativeLayout>

步骤3 - 创建一个新的Java类(DataBaseManager)并添加以下代码 -

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DataBaseManager {
private DatabaseHelper databaseHelper;
private Context context;
private SQLiteDatabase database;
DataBaseManager(Context c) {
   context = c;
   }
   DataBaseManager open() throws SQLException {
      databaseHelper = new DatabaseHelper(context);
      database = databaseHelper.getWritableDatabase();
      return this;
   }
   public void close() {
      databaseHelper.close();
   }
   void insert(String name, String desc) {
      ContentValues contentValue = new ContentValues();
      contentValue.put(DatabaseHelper.SUBJECT, name);
      contentValue.put(DatabaseHelper.DESCRIPTION, desc);
      database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
   }
   Cursor fetch() {
      String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESCRIPTION };
      Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
   if (cursor != null) {
      cursor.moveToFirst();
   }
   return cursor;
}
public int update(long _id, String name, String desc) {
   ContentValues contentValues = new ContentValues();
   contentValues.put(DatabaseHelper.SUBJECT, name);
   contentValues.put(DatabaseHelper.DESCRIPTION, desc);
   return database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
}
public void delete(long _id) {
   database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}

步骤4 - 创建一个新的Java类(DataBaseHelper)并添加以下代码

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
class DatabaseHelper extends SQLiteOpenHelper {
   static final String TABLE_NAME = "FOOTBALLPLAYERS";
   static final String _ID = "_id";
   static final String SUBJECT = "subject";
   static final String DESCRIPTION = "description";
   private static final String DB_NAME = "PLAYER_COUNTRIES.DB";
   private static final int DB_VERSION = 1;
   private static final String CREATE_TABLE = "create table " + TABLE_NAME + "("
      + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
      + SUBJECT + " TEXT NOT NULL, " + DESCRIPTION + " TEXT);";
   DatabaseHelper(Context context) {
      super(context, DB_NAME, null, DB_VERSION);
   }
   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL(CREATE_TABLE);
   }
   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
      onCreate(db);
   }
}

步骤5 - 将以下代码添加到src/MainActivity.java

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   DataBaseManager dataBaseManager;
   ListView listView;
   SimpleCursorAdapter adapter;
   final String[] from = new String[]{DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESCRIPTION};
   final int[] to = new int[]{R.id.id, R.id.title, R.id.desc};
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      dataBaseManager = new DataBaseManager(this);
      dataBaseManager.open();
      Cursor cursor = dataBaseManager.fetch();
      listView = findViewById(R.id.listView);
      listView.setEmptyView(findViewById(R.id.textView));
      adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
      adapter.notifyDataSetChanged();
      listView.setAdapter(adapter);
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
            TextView idTextView = view.findViewById(R.id.id);
            TextView titleTextView = view.findViewById(R.id.title);
            TextView descTextView = view.findViewById(R.id.desc);
            String id = idTextView.getText().toString();
            String title = titleTextView.getText().toString();
            String desc = descTextView.getText().toString();
            Intent modifyIntent = new Intent(getApplicationContext(), ModifyPlayerActivity.class);
            modifyIntent.putExtra("title", title);
            modifyIntent.putExtra("desc", desc);
            modifyIntent.putExtra("id", id);
            startActivity(modifyIntent);
         }
      });
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      int id = item.getItemId();
      if (id == R.id.addRecord) {
         Intent addPlayer = new Intent(this, AddPlayerActivity.class);
         startActivity(addPlayer);
      }
      return super.onOptionsItemSelected(item);
   }
}

步骤6 - 创建两个活动(AddPlayerActivity & ModifyPlayerActivity)并添加以下代码 -

AddPlayerActivity.java -

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class AddPlayerActivity extends AppCompatActivity implements
View.OnClickListener {
   Button btnAdd;
   private EditText editSubject;
   private EditText editDescription;
   private DataBaseManager dataBaseManager;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setTitle("Add Record");
      setContentView(R.layout.activity_addplayer);
      editSubject = findViewById(R.id.editTextSubject);
      editDescription = findViewById(R.id.editTextDescription);
      btnAdd = findViewById(R.id.add_record);
      dataBaseManager = new DataBaseManager(this);
      dataBaseManager.open();
      btnAdd.setOnClickListener(this);
   }
   @Override
   public void onClick(View v) {
      if (v.getId() == R.id.add_record) {
         final String name = editSubject.getText().toString();
         final String desc = editDescription.getText().toString();
         dataBaseManager.insert(name, desc);
         Intent main = new Intent(AddPlayerActivity.this,
         MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         startActivity(main);
      }
   }
}

activity_addplayer.xml -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp">
   <EditText
      android:id="@+id/editTextSubject"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:ems="10"
      android:hint="Enter Name" >
      <requestFocus />
   </EditText>
   <EditText
      android:id="@+id/editTextDescription"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="Enter Country"
      android:inputType="textMultiLine">
   </EditText>
   <Button
      android:id="@+id/add_record"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="Add Record" />
</LinearLayout>

ModifyPlayerActivity -

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ModifyPlayerActivity extends AppCompatActivity implements
View.OnClickListener {
   EditText editTextSub;
   Button updateBtn, deleteBtn;
   EditText editTextDesc;
   private long _id;
   DataBaseManager dataBaseManager;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setTitle("Modify Record");
      setContentView(R.layout.activity_modify_player);
      dataBaseManager = new DataBaseManager(this);
      dataBaseManager.open();
      editTextSub = findViewById(R.id.editTextSub);
      editTextDesc = findViewById(R.id.editTextDesc);
      updateBtn = findViewById(R.id.btnUpdate);
      deleteBtn = findViewById(R.id.btnDelete);
      Intent intent = getIntent();
      String id = intent.getStringExtra("id");
      String name = intent.getStringExtra("title");
      String desc = intent.getStringExtra("desc");
      _id = Long.parseLong(id);
      editTextSub.setText(name);
      editTextDesc.setText(desc);
      updateBtn.setOnClickListener(this);
      deleteBtn.setOnClickListener(this);
   }
   @Override
   public void onClick(View v) {
      switch (v.getId()) {
         case R.id.btnUpdate:
         String title = editTextSub.getText().toString();
         String desc = editTextDesc.getText().toString();
         dataBaseManager.update(_id, title, desc);
         this.returnHome();
         break;
         case R.id.btnDelete:
         dataBaseManager.delete(_id);
         this.returnHome();
         break;
      }
   }
   public void returnHome() {
      Intent home_intent = new Intent(getApplicationContext(),
      MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(home_intent);
   }
}

activity_modify_player.xml -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="10dp" >
   <EditText
      android:id="@+id/editTextSub"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginBottom="10dp"
      android:ems="10"
      android:hint="Enter Name" />
   <EditText
      android:id="@+id/editTextDesc"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="Enter Country">
   </EditText>
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:weightSum="2"
      android:gravity="center_horizontal"
      android:orientation="horizontal">
   <Button
      android:id="@+id/btnUpdate"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:text="Update" />
   <Button
      android:id="@+id/btnDelete"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:text="Delete" />
   </LinearLayout>
</LinearLayout>

步骤7 - 创建一个布局资源文件(action_view_record.xml)并添加以下代码 -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp">
   <TextView
      android:id="@+id/id"
      android:layout_width="25dp"
      android:layout_height="wrap_content"
      android:layout_alignParentStart="true"
      android:layout_alignParentTop="true"
      android:layout_marginEnd="6dp"
      android:padding="3dp"
      android:visibility="visible" />
   <TextView
      android:id="@+id/title"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginStart="10dp"
      android:layout_toEndOf="@id/id"
      android:maxLines="1"
      android:padding="3dp"
      android:textSize="17sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/desc"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/title"
      android:layout_marginStart="10dp"
      android:layout_toEndOf="@id/id"
      android:ellipsize="end"
      android:maxLines="2"
      android:padding="3dp"
      android:visibility="visible" />
</RelativeLayout>

步骤8 - 将以下代码添加到androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".ModifyPlayerActivity"></activity>
         <activity android:name=".MainActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
      <activity android:name=".AddPlayerActivity" />
   </application>
</manifest>

让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的电脑。要从Android Studio运行应用程序,请打开您项目中的一个活动文件,然后点击运行 工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -

  

 

点击这里下载项目代码。

更新于: 2019年11月22日

734次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告