Android错误尝试在空对象引用上调用虚拟方法 [英] Android error Attempt to invoke virtual method on a null object reference

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

问题描述

我是Android Studio的新手(并且讨厌Eclipse的过渡经验).我正在尝试编写当前有两个活动的应用程序.我已经为主要逻辑编写了Java代码,并且可以正常工作,但是还没有将其放入第二个活动中.当我尝试编写和运行该应用程序时,它给了我一个错误.

I'm new to Android Studio (and am hating the transition experience from Eclipse). I'm trying to write an app that currently has two activities. I already wrote the Java code for the main logic and it works fine, but haven't put it in the second activity yet. As I'm trying to write and run the app, it gives me an error.

有一个LoginActivity和MainActivity.当前,LoginActivity仅有一个伪文本和一个将用户带到MainActivity的按钮.当前,MainActivity中只有一个TextView.当我单击它时,应用程序崩溃并给出以下错误.我可以看到它与启动MainActivity有关,但似乎无法修复.

There's a LoginActivity and MainActivity. Currently LoginActivity just has a dummy text and a button that takes the user to MainActivity. Currently MainActivity has just a TextView in it. When I click it, the app crashes and gives the following error. I can see it has something to do with initiating MainActivity but I can't seem to fix it.

09-10 20:16:43.012  21126-21126/com.projects.example.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.projects.example.myapp, PID: 21126
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.projects.example.myapp/com.projects.example.myapp.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:2267)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
            at android.app.ActivityThread.access$900(ActivityThread.java:154)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5289)
            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:904)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
     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:2072)
            at com.projects.example.myapp.MainActivity.<init>(MainActivity.java:22)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1606)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
            at android.app.ActivityThread.access$900(ActivityThread.java:154)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5289)
            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:904)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

我的xml代码:

<LinearLayout 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=".LoginActivity"
    android:orientation="vertical" >

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/loginbtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:onClick="goToMainActivity" />

</LinearLayout>

LoginActivity相关代码:

LoginActivity relevant code:

public void goToMainActivity(View view)
    {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
    }

MainActivity代码要求(第22行由前缀**指示):

MainActivity code as requested (line 22 is indicated by the prefix **):

public class MainActivity extends AppCompatActivity {

    String currentWinnerName = "";

    **TextView currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);**

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

        currentWinnerLabel.setText("Finding...");
        //try
        //{
            //checkCurrentWinner(); //will implement this

        //}
        //catch (Exception e)
        //{
            //print e.getMessage() to log
        //}

    }

    @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);
    }

推荐答案

原因是,您试图在创建活动之前将值分配给currentWinnerLabel.

The reason is, that you are trying to assign value to currentWinnerLabel before activity is created.

除非创建了活动,否则上下文为null,并且您正在对null对象引用调用findViewById方法.

Unless activity is created, the context is null, and you are calling findViewById method on a null object reference.

只需更改代码:

TextView currentWinnerLabel;

及之后:

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

        currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);

...

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

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