空指针异常。无法弄清楚如何修复

Posted

技术标签:

【中文标题】空指针异常。无法弄清楚如何修复【英文标题】:Null Pointer exception. Can't figure out how to fix 【发布时间】:2012-03-08 23:37:23 【问题描述】:

好的,我有一个简单的主要活动,它只是向用户显示一个可供单击的按钮,稍后我将添加更多按钮。 当我去编译时,它会编译,但它会立即在我的设备上强制关闭。

这是我的活动代码,后面是我的 logcat 输出。

package com.michaelpeerman.probability;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.michaelpeerman.probability.R;
public class MainActivity extends BaseActivity

  View.OnClickListener buttonhandler = new View.OnClickListener()
  
    public void onClick(View v)
    
      Intent localIntent;
      switch (v.getId())
      
      case R.id.cointoss:

        localIntent = new Intent(MainActivity.this, CoinActivity.class);
        MainActivity.this.startActivity(localIntent);
        break;

      
    
  ;

  public void onCreate(Bundle savedInstanceState)
  
    super.onCreate(savedInstanceState);
    tracker.trackPageView("/ApplicationHomeScreen");
    setContentView(R.layout.main);
    Button localButton1 = (Button)findViewById(R.id.cointoss);
    //Button localButton2 = (Button)findViewById(R.id.doctor10);
    //Button localButton3 = (Button)findViewById(R.id.doctor11);
    localButton1.setOnClickListener(this.buttonhandler);
    //localButton2.setOnClickListener(this.buttonhandler);
    //localButton3.setOnClickListener(this.buttonhandler);
  






这是我的 LogCat 输出。

03-08 18:29:12.664: E/AndroidRuntime(6467): FATAL EXCEPTION: main
03-08 18:29:12.664: E/AndroidRuntime(6467): java.lang.RuntimeException: Unable to start activity ComponentInfocom.michaelpeerman.probability/com.michaelpeerman.probability.MainActivity: java.lang.NullPointerException
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.os.Looper.loop(Looper.java:137)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.ActivityThread.main(ActivityThread.java:4424)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at java.lang.reflect.Method.invokeNative(Native Method)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at java.lang.reflect.Method.invoke(Method.java:511)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at dalvik.system.NativeStart.main(Native Method)
03-08 18:29:12.664: E/AndroidRuntime(6467): Caused by: java.lang.NullPointerException
03-08 18:29:12.664: E/AndroidRuntime(6467):     at com.michaelpeerman.probability.MainActivity.onCreate(MainActivity.java:36)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.Activity.performCreate(Activity.java:4465)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-08 18:29:12.664: E/AndroidRuntime(6467):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-08 18:29:12.664: E/AndroidRuntime(6467):     ... 11 more

这是基础活动

package com.michaelpeerman.probability;


import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class BaseActivity extends Activity 
private String donate_link = "market://details?id=com.michaelpeerman.donate";
private String rate_link = "market://details?id=com.michaelpeerman.probability";
private String more_apps = "market://search?q=pub:Michael Peerman";
private String sharetext = "Check out this amazing Probability app." + "\n"
        + "\n" + "http://goo.gl/yU3jy";
GoogleAnalyticsTracker tracker;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);

    tracker = GoogleAnalyticsTracker.getInstance();
    tracker.startNewSession("REMOVED", 60, this);
    
@Override
public boolean onCreateOptionsMenu(Menu menu) 
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    switch (item.getItemId()) 
    case R.id.donate:
        tracker.trackEvent("Menu_Item", "donate", "clicked", 0);
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(donate_link)));
        break;
    case R.id.rate:
        tracker.trackEvent("Menu_Item", "rate", "clicked", 0);
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rate_link)));
        break;
    case R.id.moreapps:
        tracker.trackEvent("Menu_Item", "more_apps", "clicked", 0);
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(more_apps)));
        break;
    case R.id.share:
        tracker.trackEvent("Menu_Item", "share", "clicked", 0);
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent
                .putExtra(android.content.Intent.EXTRA_TEXT, sharetext);
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
        break;
    
    return true;

@Override
public void onPause() 
     super.onPause();
     tracker.dispatch();


 
@Override
 public void onDestroy() 
     super.onDestroy();
     tracker.dispatch();
     tracker.stopSession();

 

这是 Main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical" >
    <TableRow 
        android:background="@drawable/coin_toss_banner"
        android:layout_
        android:layout_></TableRow>
   <Button android:id="@+id/cointoss"
                android:layout_
                android:layout_
                android:text="Coin Toss" />
    </LinearLayout>

【问题讨论】:

看起来 findViewById() 没有找到按钮。仔细检查您的 XML 以确保正确分配了 id。 【参考方案1】:

编辑:这与 main.xml 或 Button 无关。以下行抛出空指针:

tracker.trackPageView("/ApplicationHomeScreen");

查看BaseActivity 没有为tracker 指定访问修饰符,因此它采用默认访问修饰符,这显然不允许访问继承类,即使它们在同一个包中。查看您的代码,这两个类似乎在同一个包中。无论如何,将tracker 显式定义为protected 将允许从继承类访问它,而不管包是什么。

我仍然对此感到有些困惑。就我而言,它不应该编译。不知何故,tracker 变量是可访问的,但它的实例化不是......任何潜伏的 Java 专家来揭示一些信息?

【讨论】:

您可以尝试将跟踪器声明为受保护吗? 好的,现在可以了。你能解释一下它的作用并更新你的答案并且不接受它。 我自己有点迷茫,我尽我所能更新答案:)【参考方案2】:

无论tracker 是什么,它都没有被初始化。我看到您有一个要扩展的基类,因此请确保 tracker 已在超类中正确设置。这意味着要么在构造函数中,要么在super.onCreate()

【讨论】:

跟踪器在基本活动中初始化我已经更新了包含基类的问题

以上是关于空指针异常。无法弄清楚如何修复的主要内容,如果未能解决你的问题,请参考以下文章

空指针异常 - 片段活动

使用 Spring MVC 运行 Spring Boot 时引发空指针异常

尝试打开 Android XML 文件时如何修复 Eclipse 中出现的空指针异常?

如何修复 Google DataFlow Pipeline (args) 空指针异常?

使用 LibGDX 和 BaseGameUtils 创建 gameHelper 时如何修复空指针异常?

NULL空指针常见情况(修复和定位)