Button may produce null pointer exception (Android

2020-07-09 09:05发布

new to Android Studio, and I thought I was doing okay, but ran into an error last night that I just can't seem to fix despite all my best googling efforts. A button on one of my activities 'may produce java.lang.NullPointerException', except it keeps failing every time it's pushed. It may just be something as simple as ordering a line of code in the wrong place etc, but I'm so new to Android studio I don't really know where I'm going wrong.

   public class searchPage extends AppCompatActivity {

    private GoogleApiClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_page);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Button goBackButton = (Button) findViewById(R.id.goBackButton);

    goBackButton.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View v) {

            startActivity(new Intent(searchPage.this, MainActivity.class));
        }
     });

Here's the XML

 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/goBackButton"
    android:layout_marginTop="88dp"
    android:layout_below="@+id/spinner4"
    android:layout_centerHorizontal="true"
    />

And the Manifest file

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.onein.mobilefinalapp">

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".searchPage"
        android:label="@string/title_activity_search_page"
        android:theme="@style/AppTheme.NoActionBar" />

    <activity
        android:name=".MoviePage"
        android:label="@string/title_activity_movie_page"
        android:theme="@style/AppTheme.NoActionBar"></activity>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
 </application>

 </manifest>

Here's the activity_search_page.xml

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

  </android.support.design.widget.AppBarLayout>

 <include layout="@layout/content_search_page" />

 <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

If you need any other information, please let me know.

Any help greatly appreciated! Thanks.

EDIT - removed duplicate button, and adding in activity_search_page.xml

3条回答
Explosion°爆炸
2楼-- · 2020-07-09 09:28

First of all, your Button needs to be in activity_search_page.xml file for findViewById() to work.

Second, I think you want the back button functionality, in that case

  1. Remove the code related to Button
  2. Add toolbar.setDisplayHomeAsUpEnabled(true);
  3. Add below code

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
                startActivity(new Intent(searchPage.this, MainActivity.class));
          }
    });
    
  4. Optional, use toolbar.setNavigationIcon(R.drawable.your_own_back_button_drawable_here); to use your own drawable.

This may help as well

查看更多
乱世女痞
3楼-- · 2020-07-09 09:42

As pointed out correctly by@cricket007 This is a warning that in case if no resource is found then, null is returned which actually makes the app crash.

Some ways to solve this problem:

1) Use the command

assert object_name != null

or simply do alt+enter, it's among one of the top suggestions by the android studio.

2) Use

if(object!=null)

3) Edit: This is a working method but a bad practice, a simple if is preferred over this.

Use try and catch block (Java's way of handling errors.)

try{
    your entire code here;
}
catch(Exception e){
    what to do when exception happens
}
查看更多
Lonely孤独者°
4楼-- · 2020-07-09 09:47

Method invocation 'setOnClickListener' may produce 'java.lang.NullPointerException' less...

This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.

This is only a warning because findViewById will return null if the given id cannot be found in the layout.

You can safely ignore it if you know for sure that the id is in the layout you are using, or you can ignore it with an assertion (And possibly an @Nullable annotation).

View v = findViewById(R.id.someId);
assert v != null;
v.setOnClickListener(...);
查看更多
登录 后发表回答