尝试调用虚方法 [英] Attempt to invoke virtual method

查看:20
本文介绍了尝试调用虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 TimerTimerTask 类制作一个简单的计时器.我不断收到以下错误:

I am trying to make a simple timer using the Timer and TimerTask classes. I keep getting the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

这是我的代码:

package com.austinheitmann.stopwatch;

import android.os.CountDownTimer;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends ActionBarActivity {

TextView timerf;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
timerf = (TextView) findViewById(R.id.timer);
}

int i=0;




TimerTask time = new TimerTask() {
    public void run() {
        i++;
        int k = i/60;
        int j = i%60;
        if (j>9) {
            timerf.setText("seconds remaining: " + k + ":" + j);
        }else {
            timerf.setText("seconds remaining: " + k + ":0" + j);
        }
        Log.d("Uhh", "Sec:" + i);
    }
};

Timer timers = new Timer();

public void startB(View view) {
timers.schedule(time, 100000000, 1000);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}
}

这里是xml文件(布局):

Here is the xml file(layout):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"            android:layout_width="match_parent"
android:layout_height="match_parent"   android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="0:00"
    android:id="@+id/timer"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="54dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start/Pause"
    android:id="@+id/start"
    android:layout_below="@+id/timer"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="119dp"
    android:onClick="startB"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Stop/Reset"
    android:id="@+id/stop"
    android:layout_alignBottom="@+id/start"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
</RelativeLayout>

我所看到的针对此错误的每个解决方案都与布局有关,但无论如何我都不会改变它.我也转移到 startB 类中的 TimerTask 并得到相同的错误.如何修复此错误?

Every solution I have seen to this error has to do with the layout but I am not altering that in anyway. I have moved to the TimerTask in the startB class also and get the same error. How can I fix this error?

这是我在清除 logcat 后从一次运行中得到的整个错误(我将 ** 放在发生错误的位置):

Here's the entire error I get from one run after clearing the logcat (I put ** where the error occurs at):

01-16 12:27:21.008    2455-2455/com.austinheitmann.stopwatch I/art﹕ Not late-enabling -Xcheck:jni (already on)
01-16 12:27:21.119    2455-2455/com.austinheitmann.stopwatch D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
01-16 12:27:21.123    2455-2455/com.austinheitmann.stopwatch E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.austinheitmann.stopwatch, PID: 2455
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.austinheitmann.stopwatch/com.austinheitmann.stopwatch.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.Activity.findViewById(Activity.java:2071)
            at com.austinheitmann.stopwatch.MainActivity.<init>(MainActivity.java:25)
            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:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-16 12:44:57.778    2582-2582/com.austinheitmann.stopwatch D/AndroidRuntime﹕ Shutting down VM
01-16 12:44:57.778    2582-2582/com.austinheitmann.stopwatch E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.austinheitmann.stopwatch, PID: 2582
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.austinheitmann.stopwatch/com.austinheitmann.stopwatch.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.Activity.findViewById(Activity.java:2071)
            at com.austinheitmann.stopwatch.MainActivity.<init>(MainActivity.java:25)
            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:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-16 12:46:25.059    2641-2641/com.austinheitmann.stopwatch D/AndroidRuntime﹕ Shutting down VM
01-16 12:46:25.059    2641-2641/com.austinheitmann.stopwatch E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.austinheitmann.stopwatch, PID: 2641
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.austinheitmann.stopwatch/com.austinheitmann.stopwatch.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.Activity.findViewById(Activity.java:2071)
            at com.austinheitmann.stopwatch.MainActivity.<init>(MainActivity.java:25)
            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:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-16 12:47:50.630    2702-2702/com.austinheitmann.stopwatch D/AndroidRuntime﹕ Shutting down VM
01-16 12:47:50.630    2702-2702/com.austinheitmann.stopwatch E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.austinheitmann.stopwatch, PID: 2702
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.austinheitmann.stopwatch/com.austinheitmann.stopwatch.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     **Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference**
            at android.app.Activity.findViewById(Activity.java:2071)
            at com.austinheitmann.stopwatch.MainActivity.<init>(MainActivity.java:25)
            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:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

推荐答案

您正在尝试在活动上下文准备好之前findViewById.

You are trying to findViewById before the activity's context is ready.

如果你也想在其他方法中访问timerf,创建一个类成员,但是在setContentView之后的onCreate中进行初始化:

If you want to access timerf in other methods too, create a class member but make the initialization in the onCreate after setContentView:

TextView timerf;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timerf = (TextView) findViewById(R.id.timer);
}

更新:

我没有注意到您正在实例化的其他类成员变量.他们正在引用为 null 的 timerf.

I didn't notice the other class member variables you're instantiating. They are referencing timerf which null.

您也需要在 onCreate 中初始化它们.这是应该可以工作的完整代码:

You need to initialize them in the onCreate too. Here's the full code that should work:

package com.austinheitmann.stopwatch;

import android.os.CountDownTimer;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends ActionBarActivity {

    Timer timers = new Timer();
    TextView timerf;
    TimerTask time;
    int i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timerf = (TextView) findViewById(R.id.timer);

        time = new TimerTask() {
            public void run() {
                i++;
                int k = i/60;
                int j = i%60;
                if (j>9) {
                    timerf.setText("seconds remaining: " + k + ":" + j);
                }else {
                    timerf.setText("seconds remaining: " + k + ":0" + j);
                }
                Log.d("Uhh", "Sec:" + i);
            }
        };
    }

    public void startB(View view) {
        timers.schedule(time, 100000000, 1000);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

这篇关于尝试调用虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆