Android布局仅显示CheckBox,ImageView与TextView不显示问题求助
Let's break down what's happening here:
Your layout XML is perfectly fine—all the views are defined correctly. The problem lies in your database setup, which is preventing your code from populating the ImageView and TextViews with data. Here's the breakdown:
Missing
FAVORITEcolumn in theDRINKtable
In yourStarbuzzDatabaseHelper, the initial table creation (foroldVersion < 1) doesn't include aFAVORITEcolumn. And your upgrade logic (oldVersion >=2) has an empty branch—there's no code to add this column to existing databases.Query failure leads to unpopulated views
When yourDrinkActivitytries to query theDRINKtable for theFAVORITEcolumn, the database throws an implicit error (caught by yourSQLiteExceptionhandler). This causescursor.moveToFirst()to returnfalse, so all the code that sets text for your TextViews and the image for your ImageView never runs.The CheckBox still shows up because you've hardcoded its text in the XML (
android:text="@string/favorite"), so it doesn't rely on database data to be visible. The other views are present but empty, making them look like they're not there.
1. Update the Database Upgrade Logic
Modify the updateMyDatabase method in StarbuzzDatabaseHelper to add the FAVORITE column when upgrading from older versions:
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 1) { db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "NAME TEXT, " + "DESCRIPTION TEXT, " + "IMAGE_RESOURCE_ID INTEGER);"); insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte); insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam", R.drawable.cappuccino); insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter); } // Add FAVORITE column for versions older than 2 if (oldVersion < 2) { db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE INTEGER DEFAULT 0;"); } }
This ensures that any existing database will get the new column, and new installations will include it from the start. The DEFAULT 0 sets all existing drinks to not be favorites initially.
2. Fix the Toast Message (Optional but Helpful)
In your DrinkActivity's catch block, the toast says " unavailable"—update it to "Database unavailable" so you get clearer debug feedback:
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
3. Clear the Old Database
To make sure the upgrade logic runs, either:
- Uninstall the app from your emulator/device, then reinstall it
- Or, in Android Studio's Device File Explorer, navigate to
/data/data/com.hfad.starbuzz/databases/and delete thestarbuzz.dbfile
Run the app again, navigate to a DrinkActivity. You should now see the ImageView, both TextViews, and the CheckBox all properly displayed with data from the database.
内容的提问来源于stack exchange,提问作者Nik

