简体   繁体   中英

Why is my view object reference still null?

If I'm interpreting the error message below correctly, the "view" object seems to be null for some reason. Looking online, most people who had a similar problem usually created the reference before setting the content view. However, as you can see by my code, this is not my case. I'm not sure what the problem is.

Here is the error message I get when trying to run the app (using my own phone as a debugging medium, if it matters):

04-24 20:54:03.848: E/AndroidRuntime(13773): FATAL EXCEPTION: main
04-24 20:54:03.848: E/AndroidRuntime(13773): Process: com.example.fiddle, PID: 13773
04-24 20:54:03.848: E/AndroidRuntime(13773): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fiddle/com.example.fiddle.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.ActivityThread.access$1100(ActivityThread.java:222)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.os.Looper.loop(Looper.java:158)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.ActivityThread.main(ActivityThread.java:7229)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at java.lang.reflect.Method.invoke(Native Method)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
04-24 20:54:03.848: E/AndroidRuntime(13773): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
04-24 20:54:03.848: E/AndroidRuntime(13773):    at com.example.fiddle.MainActivity.onCreate(MainActivity.java:25)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.Activity.performCreate(Activity.java:6876)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
04-24 20:54:03.848: E/AndroidRuntime(13773):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
04-24 20:54:03.848: E/AndroidRuntime(13773):    ... 9 more

Here is my MainActivity.java code:

package com.example.fiddle;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout view = (RelativeLayout) findViewById(R.layout.activity_main);

        view.setOnTouchListener (new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                Toast.makeText(getBaseContext(), String.valueOf(event.getX()) + ", " + String.valueOf(event.getY()), Toast.LENGTH_LONG);
                return true;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

And here is the XML document for the view:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context="com.example.fiddle.MainActivity" >

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

</RelativeLayout>

You should add an id for your RelativeLayout

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        ... 
        android:id="@+id/root_relativelayout"
        ...
       >
       ...
   </RelativeLayout>

then in onCreate method, find the RelativeLayout by

  protected void onCreate(Bundle savedInstanceState) {        
        ...
         //RelativeLayout view = (RelativeLayout) findViewById(R.layout.activity_main);
        RelativeLayout view = (RelativeLayout) findViewById(R.id.root_relativelayout);
        ...
  } 

You need to add android:id="@+id/relative_layout" to RelativeLayour in xml file.
And replace this line
RelativeLayout view = (RelativeLayout) findViewById(R.layout.activity_main);
with RelativeLayout view = (RelativeLayout) findViewById(R.id.relative_layout);
Btw, you need to read and do more example carefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM