这是我的Java。

当我尝试运行时,它给了我空指针异常

在以下行:

back.setOnClickListener(new View.OnClickListener()

我调试了,并且的确“后退”按钮为空。

但为什么?

编辑

它运行在姜饼手机上,而不是Nexus 7上

public class QuotesActivity extends Activity implements MyInterface {
private String url2;
public static ArrayList<Stock> lt;
public static ArrayList<Stock> favQ;
public MyAdapter myAdap;
public Intent intent;
public ListView lv;
public FavManager fm;
private AdView adView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.search);


    AdRequest request = new AdRequest();

    // request.addTestDevice(AdRequest.TEST_EMULATOR);
    request.setGender(AdRequest.Gender.MALE);
    boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
    if (tabletSize) {
        // Create the adView
        adView = new AdView(this, AdSize.SMART_BANNER, "dgfdfgdfgdfgd");
    } else {
        // Create the adView
        adView = new AdView(this, AdSize.BANNER, "sfsdfsdfsdfsfs");
    }

    // Lookup your LinearLayout assuming it's been given
    // the attribute android:id="@+id/mainLayout"
    LinearLayout layout = (LinearLayout) findViewById(R.id.ad);

    // Add the adView to it
    layout.addView(adView);

    // Initiate a generic request to load it with an ad
    adView.loadAd(request);

    lt = new ArrayList<Stock>();
    favQ = new ArrayList<Stock>();
    fm = new FavManager(getApplicationContext());
    favQ.clear();
    favQ.addAll(fm.ritiraFav());
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    lt.clear();
    // ////////////
    try {
        InputStream in = getResources().openRawResource(R.raw.markets3);

        if (in != null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(tmp);
            String str;
            String str1 = null;
            String str2 = null;
            boolean flag = true;
            while ((str = reader.readLine()) != null) {
                if (flag) {
                    str1 = str;
                    flag = false;
                } else {
                    str2 = str;
                    lt.add(new Stock(str1, str2, "0", "0"));
                    flag = true;
                }
            }
            in.close();
        }
    }

    catch (Throwable t) {
        // Log.e("", "Exception: " + t.toString());
    }
    // ///////
    Collections.sort(lt, new Comparator<Stock>() {
        public int compare(Stock s1, Stock s2) {
            return s1.nome.compareToIgnoreCase(s2.nome);
        }
    });
    lv = (ListView) findViewById(android.R.id.list);
    lv.setScrollbarFadingEnabled(false);
    Button favourites = (Button) findViewById(R.id.favoritesbtn);
    favourites.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(QuotesActivity.this,
                    QuotesActivityFavourites.class);
            startActivity(intent);

        }
    });

    Button back = (Button) findViewById(R.id.buttonFinish);

    back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            finish();
        }
    });


这是XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<RelativeLayout
    android:id="@+id/RequestFocusLayout"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:focusable="true"
    android:focusableInTouchMode="true" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient_box"
    android:orientation="vertical"
    android:textColor="#FFFFFF" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="20dip" >

        <TextView
            android:id="@+id/lista"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="All stocks on US Markets"
            android:textSize="15dip" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/nome"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="2"
            android:paddingLeft="5dp"
            android:text="Name"
            android:textColor="@android:color/white"
            android:textSize="10sp" />

        <Button
            android:id="@+id/googsearch"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_margin="0dp"
            android:layout_weight="4"
            android:background="@drawable/button"
            android:drawableLeft="@drawable/actionsearch"
            android:focusable="false"
            android:padding="0dp"
            android:text="Search"
            android:textColor="@android:color/white"
            android:textSize="7dp" />

        <View
            android:id="@+id/View"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="2" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="2"
            android:text="Symbol"
            android:textColor="@android:color/white"
            android:textSize="8sp" />

        <TextView
            android:id="@+id/prezzo"
            android:layout_width="0px"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="2"
            android:text="Price"
            android:textColor="@android:color/white"
            android:textSize="8sp" />

        <TextView
            android:id="@+id/freccia"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:text=""
            android:textColor="@android:color/white"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/cambiamento"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="2"
            android:text="Change %"
            android:textColor="@android:color/white"
            android:textSize="8dip" />

        <TextView
            android:id="@+id/aggiorna"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_margin="0dp"
            android:layout_weight="2"
            android:focusable="false"
            android:gravity="center"
            android:padding="0dp"
            android:text="Click to\nupdate"
            android:textColor="@android:color/white"
            android:textSize="8dp" />
    </LinearLayout>
</LinearLayout>

<ListView
    android:id="@+id/android:list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
</ListView>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient_box"
    android:orientation="vertical"
    android:textColor="#FFFFFF" >

    <LinearLayout
        android:id="@+id/ad"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="50dp" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/preferencebutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/button"
            android:drawableLeft="@drawable/actionsettings"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:text="Preferences\n&amp;\nHelp"
            android:textColor="@android:color/white"
            android:textSize="8sp" />

        <Button
            android:id="@+id/favoritesbtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/button"
            android:drawableLeft="@drawable/ratingfavorite"
            android:paddingLeft="0dp"
            android:paddingRight="5dp"
            android:text="Your\nPortfolio"
            android:textColor="@android:color/white"
            android:textSize="8sp" />

        <Button
            android:id="@+id/buttonFinish"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:background="@drawable/button"
            android:drawableLeft="@drawable/contentundo"
            android:paddingLeft="0dp"
            android:paddingRight="5dp"
            android:text="Return"
            android:textColor="@android:color/white"
            android:textSize="8sp" />
    </RelativeLayout>
</LinearLayout>




这是LogCat:

09-17 19:18:41.372: E/AndroidRuntime(25221): FATAL EXCEPTION: main
09-17 19:18:41.372: E/AndroidRuntime(25221): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.marketsinyourpocket/com.marketsinyourpocket.QuotesActivity}: java.lang.NullPointerException
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.os.Looper.loop(Looper.java:137)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.ActivityThread.main(ActivityThread.java:5103)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at java.lang.reflect.Method.invokeNative(Native Method)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at java.lang.reflect.Method.invoke(Method.java:525)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at dalvik.system.NativeStart.main(Native Method)
09-17 19:18:41.372: E/AndroidRuntime(25221): Caused by: java.lang.NullPointerException
09-17 19:18:41.372: E/AndroidRuntime(25221):    at com.marketsinyourpocket.QuotesActivity.onCreate(QuotesActivity.java:136)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.Activity.performCreate(Activity.java:5133)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-17 19:18:41.372: E/AndroidRuntime(25221):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
09-17 19:18:41.372: E/AndroidRuntime(25221):    ... 11 more

最佳答案

这行:

Button back = (Button) findViewById(R.id.buttonFinish);


不一定返回按钮。如果可以找到该按钮,它将返回该按钮。否则,您将获得空引用,这将在下一行导致错误。

检查按钮是否确实存在,并使用传递给findViewById方法的ID。如果那是您真正打算用来获取按钮的方法。

关于java - 莫名其妙的空指针异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18856254/

10-10 00:53