java 错误:尝试在空对象引用上调用虚拟方法“android.view.Window$Callback android.view.Window.getCallback()”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37573638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:37:36  来源:igfitidea点击:

Error: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

javaandroidnullpointerexceptioninvokevirtual-functions

提问by Shanna de Lang

I am making an app which shows a line graph in the MainActiviy. The top button, directs to another activity. When I made the graph the, the second activity only contained a TextView, and the app was running.

我正在制作一个在 MainActiviy 中显示折线图的应用程序。顶部按钮,指向另一个活动。当我制作图表时,第二个活动只包含一个 TextView,并且应用程序正在运行。

Afer, I wanted to implement a system in which user can add data which will be saved in a SQLite database in this other activity. I followed the tutorials 49 to 54 from thenewboston.

之后,我想实现一个系统,用户可以在其中添加数据,这些数据将在其他活动中保存在 SQLite 数据库中。我遵循了来自新波士顿的教程 49 到 54。

I (believe) I did the same as in the tutorials. Nevertheless, my app is not running and it gives this error:

我(相信)我在教程中做了同样的事情。然而,我的应用程序没有运行,它给出了这个错误:

FATAL EXCEPTION: main. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference.

致命例外:主要。引起:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.view.Window$Callback android.view.Window.getCallback()”。

The full error can be be found below. Can someone help me to fix the error?

可以在下面找到完整的错误。有人可以帮我修复错误吗?

Error message

错误信息

FATAL EXCEPTION: main Process: com.example.shanna.linechartgenerator, PID: 27077 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.shanna.linechartgenerator/com.example.shanna.linechartgenerator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365) at android.app.ActivityThread.access$800(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5272) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:68) at android.support.v7.app.AppCompatDelegateImplV7.(AppCompatDelegateImplV7.java:146) at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:28) at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:41) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:190) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:172) at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:512) at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:184) at com.example.shanna.linechartgenerator.MainActivity.(MainActivity.java:18) at java.lang.reflect.Constructor.newInstance(Native Method) at java.lang.Class.newInstance(Class.java:1572) at android.app.Instrumentation.newActivity(Instrumentation.java:1065) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2206) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)? at android.app.ActivityThread.access$800(ActivityThread.java:148)? at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)? at android.os.Handler.dispatchMessage(Handler.java:102)? at android.os.Looper.loop(Looper.java:135)? at android.app.ActivityThread.main(ActivityThread.java:5272)? at java.lang.reflect.Method.invoke(Native Method)? at java.lang.reflect.Method.invoke(Method.java:372)? at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)? at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

ActivityThread.performLaunchActivity(ActivityThread.java:2206) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)?在 android.app.ActivityThread.access$800(ActivityThread.java:148)?在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)?在 android.os.Handler.dispatchMessage(Handler.java:102)?在安卓。os.Looper.loop(Looper.java:135)?在 android.app.ActivityThread.main(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) Looper.loop(Looper.java:135)?在 android.app.ActivityThread.main(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) Looper.loop(Looper.java:135)?在 android.app.ActivityThread.main(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 循环(Looper.java:135)?在 android.app.ActivityThread.main(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 循环(Looper.java:135)?在 android.app.ActivityThread.main(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 第 135 章 在 android.app.ActivityThread.main(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 第 135 章 在 android.app.ActivityThread.main(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 主要(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 主要(ActivityThread.java:5272)?在 java.lang.reflect.Method.invoke(Native Method)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 调用(本地方法)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 调用(本地方法)?在 java.lang.reflect.Method.invoke(Method.java:372)?在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 第909章?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 第909章?在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

MainActivity.Java:

MainActivity.Java:

package com.example.shanna.linechartgenerator;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    //public static final int ThresholdValue = 1;
    LineChart lineChart = (LineChart) findViewById(R.id.chart);
    //float newThreshold;

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


        // creating list of entry
        ArrayList<Entry> entries = new ArrayList<>();
        entries.add(new Entry(4f, 0));
        entries.add(new Entry(8f, 1));
        entries.add(new Entry(6f, 2));
        entries.add(new Entry(2f, 3));
        entries.add(new Entry(18f, 4));
        entries.add(new Entry(9f, 5));

        LineDataSet dataset = new LineDataSet(entries, "# of Calls");

        // creating labels
        ArrayList<String> labels = new ArrayList<String>();
        labels.add("January");
        labels.add("February");
        labels.add("March");
        labels.add("April");
        labels.add("May");
        labels.add("June");

        LineData data = new LineData(labels, dataset);
        lineChart.setData(data); // set the data and list of lables into chart
    }

    public void goToActivityOne(View view){
        Intent intent = new Intent(this,ActivityOne.class);
        startActivity(intent); //go to other activity in app
    }

    public void goToOtherApp(View view){
        Intent intent2 = new Intent("HelloWorld_MakeValue");
        //intent2.putExtra("newThreshold", newThreshold);

        startActivity(intent2); //To go to activity in the other app
        //startActivityForResult(intent2, ThresholdValue);
    }
}

ActivityOne.java (The Activity with the input to save in the database)

ActivityOne.java(将输入保存在数据库中的Activity)

package com.example.shanna.linechartgenerator;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class ActivityOne extends AppCompatActivity {

    private EditText userInput;
    private TextView userText;
    private MyDBHandler dbHandler;

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

        userInput = (EditText) findViewById(R.id.userInput);
        userText = (TextView) findViewById(R.id.userText);
        dbHandler = new MyDBHandler(this, null, null, 1); //has 4 paramethers: context, DATABASE_NAME, factory, DATABASE_VERSION, see class

        //method for add button, see below
        printDataBase();

        //method for the delete button, see below

        //method for printing, see below
    }

    public void addButtonClicked(View view){
        Painscales painscales = new Painscales(userInput.getText().toString());
        dbHandler.addPainscale(painscales);
        printDataBase();
        //whenever user clicks the add button, take the input, add it to the database and print in below
    }

    public void printDataBase(){
        String dbString = dbHandler.databaseToSting(); //get sting we retreived
        userText.setText(dbString); //store it in here
        userInput.setText(" "); //take input and set text to 'refresh' the input
    }

    public void deleteButtonClicked(View view){
        String inputText = userInput.getText().toString();
        dbHandler.deletePainscale(inputText);
        printDataBase();

    }


}

The MyDBHandler class

MyDBHandler 类

package com.example.shanna.linechartgenerator;

/**
 * Created by Shanna on 1-6-2016.
 * clas to work with the database
 * with the help of the youtube tutorial, "Android App Development for Beginners - 51, 52 & 53 " from thenewboston
 */
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;

public class MyDBHandler extends SQLiteOpenHelper{
    //name that database
    //column name etx
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "painscale.db";
    public static final String TABLE_PAINSCALE = "painscale";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_PAINSCALENAME = "painscaleName";

    public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    } //constructor to pass info to class that works direclu with android (myDGHandler)

    //on first call it needs to know what you are going to do, which is creating a table
    @Override
    public void onCreate(SQLiteDatabase db) {
        //specify the table
        String query = "CREATE_TABLE" + TABLE_PAINSCALE + "(" +
                COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT" +
                COLUMN_PAINSCALENAME + "TEXT" + ")";
        db.execSQL(query); //create the table

    }

    //to update the table
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_PAINSCALE); //delete the current table
        onCreate(db); //create new updated table
    }

    //Add a new row to the database
    public void addPainscale(Painscales painscales){
        ContentValues values = new ContentValues();
        values.put(COLUMN_PAINSCALENAME, painscales.get_painscaleName());
        SQLiteDatabase db = getWritableDatabase(); //key to the
        db.insert(TABLE_PAINSCALE, null, values); //inset new row into table
        db.close();//close database, we are done
    }

    //Delete painscale from the database
    public void deletePainscale(String painscaleName){
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM" + TABLE_PAINSCALE + "WHERE" + COLUMN_PAINSCALENAME + "=\"" +painscaleName + "=\";" ); //delete where productname is same as the input
    }

    //print out the database, as a string
    public String databaseToSting(){
        String dbString = "";
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT + FROM " + TABLE_PAINSCALE + "WHERE 1";

        //cursor point at location in results
        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();

        while(!c.isAfterLast()){
            if(c.getString(c.getColumnIndex("painscaleName"))!= null){
                dbString += c.getString(c.getColumnIndex("painscaleName"));
                dbString += "\n";
            } //loops throuhg all painsclase names, everytime it does, it would place a new one on a new row. Is needed so thevalesarenotwritenlikethis
        }
        db.close();
        return dbString;
    }
}

The Painscales.java class

Painscales.java 类

package com.example.shanna.linechartgenerator;

/**
 * Created by Shanna on 1-6-2016.
 * class to deal with the user input
 * with the help of the youtube tutorial, "Android App Development for Beginners - 49 and 50, from thenewboston
 */
public class Painscales {
    //java needs an id number and the pain scale
    private int _id;
    private String _painscaleName;

    public Painscales(){

    }

    public Painscales(String painscaleName) {
        this._painscaleName = painscaleName; //give input data automatically string to whatever user typed in
    }

    public void set_id(int _id) {
        this._id = _id; //give input an id
    }

    public void set_painscaleName(String _painscaleName) {
        this._painscaleName = _painscaleName; //set input as a name
    }

    public int get_id() {
        return _id; //get input id
    }

    public String get_painscaleName() {
        return _painscaleName; //get input name
    }
}

回答by Vucko

You cannot have this initialization here:

您不能在此处进行此初始化:

LineChart lineChart = (LineChart) findViewById(R.id.chart);

You can declare your variable there like: LineChart lineChart; And then in onCreateAFTERcalling setContentViewput the initialization like:

您可以在那里声明您的变量,例如: LineChart lineChart; 然后在onCreateAFTER调用中setContentView放置如下初始化:

lineChart = (LineChart) findViewById(R.id.chart);