Android error Attempt to invoke virtual method on a null object reference [duplicate]

丶灬走出姿态 提交于 2020-01-15 17:38:34

问题


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.

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)

My xml code:

<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 relevant code:

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

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

回答1:


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

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

Just change your code:

TextView currentWinnerLabel;

and after:

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

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

...


来源:https://stackoverflow.com/questions/32513625/android-error-attempt-to-invoke-virtual-method-on-a-null-object-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!