Android Studio中Zxing扫码器集成Firebase及扫码数据处理问询
Hey there! Let's work through your requirements step by step—from modifying the ZXing scan flow to integrating Firebase and handling duplicate barcodes.
First, we'll replace the popup display with a navigation to a dedicated product edit screen, passing the scanned barcode ID along:
Step 1: Update the Scan Success Callback
In your ZXing scan activity/fragment, replace the popup code with an intent to start the new edit activity:
// Example ZXing scan result callback @Override public void onScanResult(Result result) { String barcodeId = result.getText(); // Launch product edit activity with barcode ID Intent editIntent = new Intent(this, ProductEditActivity.class); editIntent.putExtra("BARCODE_ID", barcodeId); startActivity(editIntent); }
Step 2: Build the Product Edit Screen
Create a new ProductEditActivity with:
- A
TextViewto display the scanned barcode ID EditTextfields for product name, date, and category- A save button to trigger Firebase storage
Here's a simplified implementation:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_edit); // Retrieve the passed barcode ID String barcodeId = getIntent().getStringExtra("BARCODE_ID"); TextView barcodeDisplay = findViewById(R.id.tv_barcode); barcodeDisplay.setText("Barcode ID: " + barcodeId); // Set up save button click listener Button saveBtn = findViewById(R.id.btn_save); saveBtn.setOnClickListener(v -> saveProductToFirebase(barcodeId)); }
Let's cover the end-to-end integration for Firebase (we'll use Firestore here, but the process is similar for Realtime Database):
Step 1: Add Firebase to Your Project
- Open Android Studio, go to
Tools > Firebase - Select
Firestore Database(orRealtime Database) and follow the wizard to connect your app to Firebase - Download the
google-services.jsonfile and place it in your app module directory
Step 2: Add Firebase Dependencies
Add these lines to your module-level build.gradle file:
// Firestore dependency (use Realtime Database dependency if preferred) implementation 'com.google.firebase:firebase-firestore:24.10.0' // Optional: Firebase Auth (if you need user-based access control) implementation 'com.google.firebase:firebase-auth:22.3.1'
Step 3: Implement Firebase Save Logic
Add this method to your ProductEditActivity to store data using the barcode ID as the document ID:
private void saveProductToFirebase(String barcodeId) { // Get input values from EditTexts EditText nameEt = findViewById(R.id.et_product_name); EditText dateEt = findViewById(R.id.et_date); EditText categoryEt = findViewById(R.id.et_category); String productName = nameEt.getText().toString().trim(); String productDate = dateEt.getText().toString().trim(); String productCategory = categoryEt.getText().toString().trim(); // Create a Product model class (required for Firebase serialization) Product product = new Product(productName, productDate, productCategory); // Initialize Firestore instance FirebaseFirestore db = FirebaseFirestore.getInstance(); // Save data with barcode ID as document ID db.collection("products") .document(barcodeId) .set(product) .addOnSuccessListener(aVoid -> { Toast.makeText(this, "Product saved successfully!", Toast.LENGTH_SHORT).show(); finish(); // Return to scan screen after save }) .addOnFailureListener(e -> Toast.makeText(this, "Save failed: " + e.getMessage(), Toast.LENGTH_SHORT).show() ); } // Product model class (must have empty constructor for Firebase) public class Product { public String name; public String date; public String category; public Product() {} // Required for Firebase public Product(String name, String date, String category) { this.name = name; this.date = date; this.category = category; } }
When the same barcode is scanned again, you have two common options—choose based on your app's needs:
Option 1: Auto-navigate to Edit Existing Data
Check if the barcode already exists in Firebase, then pre-fill the edit screen with existing data:
// Update the ZXing scan callback to check for existing data first @Override public void onScanResult(Result result) { String barcodeId = result.getText(); FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("products") .document(barcodeId) .get() .addOnSuccessListener(docSnapshot -> { Intent editIntent = new Intent(this, ProductEditActivity.class); editIntent.putExtra("BARCODE_ID", barcodeId); if (docSnapshot.exists()) { // Pass existing product data to pre-fill fields Product existingProduct = docSnapshot.toObject(Product.class); editIntent.putExtra("PRODUCT_NAME", existingProduct.name); editIntent.putExtra("PRODUCT_DATE", existingProduct.date); editIntent.putExtra("PRODUCT_CATEGORY", existingProduct.category); } startActivity(editIntent); }) .addOnFailureListener(e -> Toast.makeText(this, "Failed to check existing data: " + e.getMessage(), Toast.LENGTH_SHORT).show() ); }
Then update ProductEditActivity's onCreate to pre-fill the fields if data exists.
Option 2: Prompt User for Action
Show a dialog asking the user to edit, view, or cancel when a duplicate barcode is detected:
@Override public void onScanResult(Result result) { String barcodeId = result.getText(); FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("products") .document(barcodeId) .get() .addOnSuccessListener(docSnapshot -> { if (docSnapshot.exists()) { new AlertDialog.Builder(this) .setTitle("Barcode Already Exists") .setMessage("A product with this barcode is already saved. What would you like to do?") .setPositiveButton("Edit", (dialog, which) -> { // Navigate to edit screen with existing data Intent editIntent = new Intent(this, ProductEditActivity.class); editIntent.putExtra("BARCODE_ID", barcodeId); Product existingProduct = docSnapshot.toObject(Product.class); editIntent.putExtra("PRODUCT_NAME", existingProduct.name); startActivity(editIntent); }) .setNegativeButton("View Details", (dialog, which) -> { // Navigate to a read-only detail screen Intent detailIntent = new Intent(this, ProductDetailActivity.class); detailIntent.putExtra("BARCODE_ID", barcodeId); startActivity(detailIntent); }) .setNeutralButton("Cancel", null) .show(); } else { // Navigate to new product screen Intent editIntent = new Intent(this, ProductEditActivity.class); editIntent.putExtra("BARCODE_ID", barcodeId); startActivity(editIntent); } }); }
内容的提问来源于stack exchange,提问作者fhsks

