在 Android 开发中,我们通常使用 SQLite 数据库进行本地数据库操作。首先,我们需要在 AndroidManifest.xml 中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
然后,我们需要创建一个数据库帮助类,例如 DatabaseHelper.java:
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "user_db"; private static final int DB_VERSION = 1; private static final String TABLE_NAME = "user_table"; private static final String COLUMN_ID = "id"; private static final String COLUMN_USERNAME = "username"; private static final String COLUMN_PASSWORD = "password"; public DatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createTableQuery = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_USERNAME + " TEXT, " + COLUMN_PASSWORD + " TEXT" + ");"; db.execSQL(createTableQuery); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } }
接着,我们创建一个用户类,例如 User.java:
public class User { private int id; private String username; private String password; public User(int id, String username, String password) { this.id = id; this.username = username; this.password = password; } public int getId() { return id; } public String getUsername() { return username; } public String getPassword() { return password; } }
接下来,我们需要实现从本地数据库获取用户列表的代码,例如 getLocalUserList(). 首先,我们需要从数据库中获取所有用户数据,并将其存储在一个 ArrayList<User> 中,然后将其返回。如果数据库中没有用户数据,则返回一个空的 ArrayList<User>。这个方法应该放在 DatabaseHelper.java 中:
public ArrayList<User> getLocalUserList() { ArrayList<User> userList = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM " + TABLE_NAME; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID)); String username = cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)); String password = cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)); userList.add(new User(id, username, password)); } while (cursor.moveToNext()); } cursor.close(); db.close(); return userList; }
联系电话:0763-84538663
联 系 QQ:540383622
工作时间:周一至周五8:00~18:00