如何将基于Java与Android Studio开发的条码扫描移动应用连接至数据库
嘿,你已经把条码扫描的核心功能跑通了,接下来给你梳理两种常见的数据库连接方案,你可以根据自己的需求来选:
一、用本地SQLite数据库(适合离线存储扫描记录)
这种方案不需要联网,数据存在设备本地,适合只是想保存历史扫描记录的场景:
- 创建数据库帮助类
先写一个继承SQLiteOpenHelper的类,用来管理数据库的创建和版本升级:
public class BarcodeDbHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "barcode_db"; private static final int DATABASE_VERSION = 1; // 条码表的创建语句 private static final String CREATE_TABLE_BARCODES = "CREATE TABLE barcodes (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "barcode_text TEXT NOT NULL," + "scan_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"; public BarcodeDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_BARCODES); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 版本升级时的逻辑,比如删除旧表重建 db.execSQL("DROP TABLE IF EXISTS barcodes"); onCreate(db); } }
- 在MainActivity中插入扫描到的数据
当你从Google Mobile Vision API拿到条码数据后,就可以把它存入数据库了:
// 实例化数据库帮助类 BarcodeDbHelper dbHelper = new BarcodeDbHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase(); // 封装要插入的数据 ContentValues values = new ContentValues(); values.put("barcode_text", scannedBarcodeText); // scannedBarcodeText是你拿到的条码内容 // 插入数据 long newRowId = db.insert("barcodes", null, values); // 记得关闭数据库连接(或者用try-with-resources) db.close();
- 查询历史记录(可选)
如果需要展示之前扫描的记录,可以用查询语句:
SQLiteDatabase db = dbHelper.getReadableDatabase(); String[] projection = {"id", "barcode_text", "scan_time"}; Cursor cursor = db.query("barcodes", projection, null, null, null, null, "scan_time DESC"); // 遍历cursor获取数据 while (cursor.moveToNext()) { String barcode = cursor.getString(cursor.getColumnIndexOrThrow("barcode_text")); String time = cursor.getString(cursor.getColumnIndexOrThrow("scan_time")); // 把数据展示到UI上,比如ListView或者RecyclerView } cursor.close(); db.close();
二、连接远程数据库(适合多设备同步数据)
Android不能直接连接远程数据库(比如MySQL、PostgreSQL),必须通过后端API来中转,这里给你一个简单的实现思路:
- 先搭建后端API
用Java的Spring Boot或者其他后端框架写一个接口,接收Android发送的条码数据,然后存入远程数据库。举个Spring Boot的例子:
@RestController @RequestMapping("/api/barcodes") public class BarcodeController { @Autowired private BarcodeRepository barcodeRepository; // 这是操作数据库的Repository @PostMapping public ResponseEntity<String> saveBarcode(@RequestBody BarcodeDto barcodeDto) { Barcode barcode = new Barcode(); barcode.setBarcodeText(barcodeDto.getBarcodeText()); barcode.setScanTime(new Date()); barcodeRepository.save(barcode); return ResponseEntity.ok("数据保存成功"); } }
- Android端集成网络库
推荐用Retrofit来发送网络请求,先在app/build.gradle里添加依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
然后创建API接口:
public interface BarcodeApiService { @POST("/api/barcodes") Call<ResponseBody> saveBarcode(@Body BarcodeDto barcodeDto); } // 数据传输类 public class BarcodeDto { private String barcodeText; public BarcodeDto(String barcodeText) { this.barcodeText = barcodeText; } // Getter和Setter public String getBarcodeText() { return barcodeText; } public void setBarcodeText(String barcodeText) { this.barcodeText = barcodeText; } }
- 在MainActivity中调用API
注意网络请求不能在主线程,所以要用Coroutines或者AsyncTask,这里用Coroutines的例子:
// 初始化Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://你的后端域名/") // 替换成你的后端地址 .addConverterFactory(GsonConverterFactory.create()) .build(); BarcodeApiService apiService = retrofit.create(BarcodeApiService.class); // 在Coroutine中发送请求 lifecycleScope.launch(Dispatchers.IO) { try { Response<ResponseBody> response = apiService.saveBarcode(new BarcodeDto(scannedBarcodeText)).execute(); if (response.isSuccessful()) { // 数据发送成功,可以在主线程更新UI withContext(Dispatchers.Main) { Toast.makeText(MainActivity.this, "数据已同步到服务器", Toast.LENGTH_SHORT).show(); } } } catch (IOException e) { e.printStackTrace(); withContext(Dispatchers.Main) { Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show(); } } }
一些注意事项
- 权限:如果用远程数据库,记得在
AndroidManifest.xml中添加网络权限:<uses-permission android:name="android.permission.INTERNET" /> - 线程安全:无论是本地数据库操作还是网络请求,都不能在主线程执行,否则会触发ANR(应用无响应)
- 数据安全:远程传输一定要用HTTPS,避免数据被窃取;本地存储敏感条码数据的话,可以考虑加密存储
内容的提问来源于stack exchange,提问作者Outcast
相关产品推荐
相关产品推荐

