数据库错误:“NullPointerException:尝试在空对象引用上调用虚拟方法 getApplicationInfo()...”[重复]

Posted

技术标签:

【中文标题】数据库错误:“NullPointerException:尝试在空对象引用上调用虚拟方法 getApplicationInfo()...”[重复]【英文标题】:Database Error: "NullPointerException: Attempt to invoke virtual method getApplicationInfo()... on a null object reference" [duplicate] 【发布时间】:2020-03-26 01:50:14 【问题描述】:

我正在构建一个简单的多活动列表应用程序来练习 SQLite。当这开始时,我试图从数据库中获取字符串以显示在listview 中。我收到了错误

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()”

这里是代码

public class MainActivity extends AppCompatActivity 
    SharedPreferences sharedPreferences;
    ArrayList<String> listItem;
    ArrayAdapter adapter;
    ListView lv = (ListView) findViewById(R.id.list_view);
    DatabaseHelper db = new DatabaseHelper(this);
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        listItem = new ArrayList<>();
        viewData();
        context = this;

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                startActivity(new Intent(MainActivity.this, textInput.class));
            
        );
    

    // cast from sql database to the listview
    private void viewData() 
        Cursor res = db.viewData();

        if (res.getCount() == 0 )
            Toast.makeText(this,"No Data!",Toast.LENGTH_SHORT).show();
        
        else
            while (res.moveToNext())
                listItem.add(res.getString(1));
            
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,listItem);
            lv.setAdapter(adapter);
        
    

这是数据库助手:

public class DatabaseHelper extends SQLiteOpenHelper 
public static final String DATABASE_NAME = "item.db";
public static final String TABLE_NAME = "item_table";
public static final String ID = "item_id";
public static final String NAME = "item_name";
public static final String PRICE = "item_price";
public static final String URL = "item_url";

public DatabaseHelper(@Nullable Context context) 
    super(context, DATABASE_NAME, null, 1);


@Override
public void onCreate(SQLiteDatabase db) 
    db.execSQL("create table " + TABLE_NAME +" ( item_id INTEGER PRIMARY 
KEY AUTOINCREMENT,item_name TEXT,item_price INTEGER,item_url TEXT) ");


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);


public boolean insertData(String name, String price, String url)
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(NAME, name);
    contentValues.put(PRICE, price);
    contentValues.put(URL, url);
    long result = db.insert(TABLE_NAME,null,contentValues);
    if(result == -1)
        return false;
    else
        return true;



public Cursor viewData()
    SQLiteDatabase db  = this.getReadableDatabase();
    Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
    return res;

这是文本输入活动

public class textInput extends AppCompatActivity 
SharedPreferences sharedPreferences;
//    Editor editor;
//    Context _context;
//    int PRIVATE_MODE = 0;
//    private static final String PREF_NAME = "Items";
//    public static final String NAME_LIST = "name";


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text_input);
    //DatabaseHelper db;

    //return's to main activity on press
    Button addButton = (Button) findViewById(R.id.addButton);
    final EditText name = (EditText) findViewById(R.id.itemName);
    final EditText url = (EditText) findViewById(R.id.itemURL);
    final EditText price = (EditText) findViewById(R.id.itemPrice);
 //   final SharedPreferences sharedPreferences = 
getApplicationContext().getSharedPreferences("items", 0);
    final DatabaseHelper db = new DatabaseHelper(this);
    addButton.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            //Checks to make sure that all fields are filled out, if yes 
then returns to MainActivity
            if (name.length() != 0 && price.length() != 0 && url.length() 
 !=0)
                boolean isInserted = 
db.insertData(name.getText().toString(),
                        price.getText().toString(),
                        url.getText().toString());
                if(isInserted == true)
                    Toast.makeText(textInput.this, "New Item Added", 
 Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(textInput.this, "Failed to Add", 
Toast.LENGTH_SHORT).show();
                //The graphic and the return to MainActivity
                Intent returnToMain = new Intent(getApplicationContext(), 
MainActivity.class);
                startActivity(returnToMain);
            
            else
                Toast.makeText(textInput.this, "Please fill out all 
fields!", Toast.LENGTH_SHORT).show();
            

        
    );

调试(错误?)日志

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.xmaswishlist, PID: 25470
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfocom.example.xmaswishlist/com.example.xmaswishlist.MainActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2841)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
        at android.content.Context.obtainStyledAttributes(Context.java:655)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
        at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
        at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
        at com.example.xmaswishlist.MainActivity.<init>(MainActivity.java:36)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1180)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6944) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

我已尝试使用以下方法解决此问题:

    Android studio “ Attempt to invoke virtual method android.database.Cursor on a null object reference” problem Database error: Attempt to invoke virtual method 'Cursor .getScene()' on a null object reference 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference when notify notification Android

【问题讨论】:

如果还能加上错误日志就好了。查明问题会更容易、更快捷。 好的,给我一点时间,我会搞定的! 【参考方案1】:

您在设置setContentView 中的内容之前尝试获取视图,这会导致exception。在onCreate 内实例化ListViewDatabaseHelper

ListView lv;
DatabaseHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ...

    lv = (ListView) findViewById(R.id.list_view);
    db = new DatabaseHelper(this);
    ...

【讨论】:

感谢您的回复!我刚刚修复了这些,错误发生了变化。我会更新帖子! 编辑:我会为新的错误创建一个新帖子,再次感谢!【参考方案2】:

来自堆栈跟踪:

在 com.example.xmaswishlist.MainActivity.(MainActivity.java:36) 上的 androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)

MainActivity 类中,您需要将ListView lv = (ListView) findViewById(R.id.list_view); 这一行上的作业移动到onCreate。所以定义它已经存在的变量,但将= (ListView)... 移动到onCreate

findViewById 在类被实例化时被调用,在onCreate 被调用之前,因此内部工作正在爆炸,因为活动本身尚未初始化。

您还需要在 onCreate 中初始化数据库助手。

【讨论】:

以上是关于数据库错误:“NullPointerException:尝试在空对象引用上调用虚拟方法 getApplicationInfo()...”[重复]的主要内容,如果未能解决你的问题,请参考以下文章

TokenEndpoint 中的 NullPointerException

在 Zeppelin 0.7.1 中运行 Spark 代码时出现 NullPointerException

springboot拦截器注入bean失败实例

onPostExecute 中的空指针异常

StringUtils.isEmpty和StringUtils.isBlank用法

android中的NullPointerException,同时在menu.xml中使用actionLayout