Android Studio调用Database.getName()遇空对象引用错误求助
Hey there! Let's break down the issue you're hitting and get it fixed quickly.
What's Causing the Error?
The crash log clearly points to a NullPointerException:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.demo.Database.Database.getName()' on a null object reference
This means when your code tries to call getName() on your Database object at line 98 of MainActivity.java, that Database instance hasn't been initialized yet—it's null. The call happens inside LoadSuggestList(), which you're invoking at line 42 of onCreate().
How to Fix It
Follow these steps to resolve the issue:
Initialize Your Database Instance Before Using It
Make sure you create a valid instance ofDatabasebefore callingLoadSuggestList()in youronCreate()method. Depending on yourDatabaseclass's constructor, you'll likely need to pass aContext(since Android database helpers usually require one).Example code for
MainActivity.java:public class MainActivity extends AppCompatActivity { // Declare a member variable for your Database private Database mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // First, initialize the Database instance mDatabase = new Database(this); // Adjust parameters if your constructor needs more // Now safely call LoadSuggestList() LoadSuggestList(); } private void LoadSuggestList() { // Use the initialized Database instance to call getName() List<String> nameList = mDatabase.getName(); // Rest of your logic here... } }Verify Your Database Class Constructor
Double-check that yourDatabaseclass's constructor properly sets up the database connection. If it's supposed to open a database or initialize internal components, make sure those steps aren't failing silently (like missing permissions or incorrect database path).Check for Singleton Patterns (If Applicable)
If yourDatabaseuses a singleton pattern (common for database helpers), ensure you're retrieving the instance correctly via a method likeDatabase.getInstance(context)instead of creating a new instance directly. Make sure the singleton's initialization logic is working as expected.
Quick Debug Tip
If you're still stuck, add a log statement right before line 98 in LoadSuggestList() to check if the Database object is null:
Log.d("MainActivity", "Database instance: " + mDatabase);
If the log shows null, you know the issue is definitely that the instance wasn't initialized properly before this point.
内容的提问来源于stack exchange,提问作者Hasini

