空指针异常需要帮助搞清楚

时间:2014-11-04 16:52:27

标签: java android eclipse android-intent

我正在尝试创建一个应用程序,在整个高尔夫游戏中跟踪统计数据,并在必要时生成适合您的高尔夫游戏的提示。我通过将它们放入数组列表来跟踪这些漏洞。我发现你可以使用谷歌GSON在活动之间传递对象,我遵循了教程,但我觉得活动之间的数组传递最终导致了NPE,但我不确定。

这是完整的堆栈跟踪

11-04 11:06:02.218: E/Trace(774): error opening trace file: No such file or directory (2)
11-04 11:06:02.949: D/dalvikvm(774): GC_FOR_ALLOC freed 77K, 2% free 10958K/11143K, paused 46ms, total 48ms
11-04 11:06:03.048: D/dalvikvm(774): GC_CONCURRENT freed 168K, 3% free 11241K/11527K, paused >25ms+5ms, total 65ms
11-04 11:06:03.058: D/dalvikvm(774): WAIT_FOR_CONCURRENT_GC blocked 29ms
11-04 11:06:03.448: D/gralloc_goldfish(774): Emulator without GPU emulation detected.
11-04 11:06:06.168: D/AndroidRuntime(774): Shutting down VM
11-04 11:06:06.168: W/dalvikvm(774): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-04 11:06:06.208: E/AndroidRuntime(774): FATAL EXCEPTION: main
11-04 11:06:06.208: E/AndroidRuntime(774): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.testapp/com.example.testapp.StatActivity}: java.lang.NullPointerException
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.os.Looper.loop(Looper.java:137)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.ActivityThread.main(ActivityThread.java:4745)
11-04 11:06:06.208: E/AndroidRuntime(774):  at java.lang.reflect.Method.invokeNative(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774):  at java.lang.reflect.Method.invoke(Method.java:511)
11-04 11:06:06.208: E/AndroidRuntime(774):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-04 11:06:06.208: E/AndroidRuntime(774):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 11:06:06.208: E/AndroidRuntime(774):  at dalvik.system.NativeStart.main(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774): Caused by: java.lang.NullPointerException
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.Activity.findViewById(Activity.java:1825)
11-04 11:06:06.208: E/AndroidRuntime(774):  at com.example.testapp.StatActivity.<init>(StatActivity.java:38)
11-04 11:06:06.208: E/AndroidRuntime(774):  at java.lang.Class.newInstanceImpl(Native Method)
11-04 11:06:06.208: E/AndroidRuntime(774):  at java.lang.Class.newInstance(Class.java:1319)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-04 11:06:06.208: E/AndroidRuntime(774):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-04 11:06:06.208: E/AndroidRuntime(774):  ... 11 more
11-04 11:06:06.388: D/dalvikvm(774): GC_CONCURRENT freed 266K, 4% free 11366K/11719K, paused >17ms+64ms, total 142ms
11-04 11:11:06.349: I/Process(774): Sending signal. PID: 774 SIG: 9

以及相关活动

StatActivity

  package com.example.testapp;

import java.util.ArrayList;
import java.util.List;

import com.example.testapp.StatActivity;
import com.example.testapp.CustomOnItemSelectedListener;
import com.example.testapp.R;
import com.google.gson.Gson;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class StatActivity extends Activity implements OnClickListener {
    private Spinner driving_spinner;
    private Spinner approach_spinner;
    private Spinner chipping_spinner;
    private Spinner sandshot_spinner;
    private Spinner putting_spinner;
    private int hole = 1;
    private boolean driving_spinner_selected = false;
    private boolean approach_spinner_selected = false;
    private boolean chipping_spinner_selected = false;
    private boolean sandshot_spinner_selected = false;
    private boolean putting_spinner_selected = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stat);
        Button homeButton = (Button) findViewById(R.id.homeButton);
        Button helpButton = (Button) findViewById(R.id.helpButton);
        Button nextHoleButton = (Button) findViewById(R.id.nextHoleButton);
        driving_spinner = (Spinner) findViewById(R.id.drivingSpinner);
        approach_spinner = (Spinner) findViewById(R.id.approachSpinner);
        chipping_spinner = (Spinner) findViewById(R.id.chippingSpinner);
        sandshot_spinner = (Spinner) findViewById(R.id.sandShotSpinner);
        putting_spinner = (Spinner) findViewById(R.id.puttingSpinner);
        nextHoleButton.setOnClickListener(this);
        helpButton.setOnClickListener(this);
        homeButton.setOnClickListener(this);
        addItemsToDrivingSpinner();
        addItemsToChippingSpinner();
        addItemsToPuttingSpinner();
        addItemsToApproachSpinner();
        addItemsToSandShotSpinner();
        addListenerOnDrivingSpinnerItemSelection();
        addListenerOnChippingSpinnerItemSelection();
        addListenerOnPuttingSpinnerItemSelection();
        addListenerOnApproachSpinnerItemSelection();
        addListenerOnSandShotSpinnerItemSelection();

    }


    Gson gS = new Gson();
   String src = getIntent().getStringExtra("round");
   Round round = gS.fromJson(src, Round.class);

    // add items into spinner dynamically
      public void addItemsToDrivingSpinner() {

        List<String> list = new ArrayList<String>();
            list.add("Left");
            list.add("Right");
            list.add("Fairway Hit");
            list.add("Par Three");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        driving_spinner.setAdapter(dataAdapter);
      }

      public void addItemsToApproachSpinner() {

          List<String> list = new ArrayList<String>();
            list.add("Left");
            list.add("Right");
            list.add("Short");
            list.add("Long");
            list.add("Green Hit");
            list.add("No Oppurtunity");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            approach_spinner.setAdapter(dataAdapter);
          }

      public void addItemsToChippingSpinner() {

          List<String> list = new ArrayList<String>();
            list.add("Yes Up and Down");
            list.add("No Up and Down");
            list.add("No Oppurtunity");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            chipping_spinner.setAdapter(dataAdapter);
          }

      public void addItemsToSandShotSpinner() {

          List<String> list = new ArrayList<String>();
            list.add("Yes Sand Save");
            list.add("No Sand Save");
            list.add("No Oppurtunity");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sandshot_spinner.setAdapter(dataAdapter);
          }

      public void addItemsToPuttingSpinner() {

          List<String> list = new ArrayList<String>();
            list.add("0");
            list.add("1");
            list.add("2");
            list.add("3");
            list.add("4");
            list.add("5+");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            putting_spinner.setAdapter(dataAdapter);
          }

      public void addListenerOnDrivingSpinnerItemSelection() {
            driving_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
            driving_spinner_selected = true;
      }
      public void addListenerOnApproachSpinnerItemSelection() {
            approach_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
            approach_spinner_selected = true;
      }
      public void addListenerOnChippingSpinnerItemSelection() {
            chipping_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
            chipping_spinner_selected = true;
      }
      public void addListenerOnPuttingSpinnerItemSelection() {
            putting_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
            putting_spinner_selected = true;
      }
      public void addListenerOnSandShotSpinnerItemSelection() {
            sandshot_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
            sandshot_spinner_selected = 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.stat, 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);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.homeButton){
            Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(intent);  

        }else if(v.getId() == R.id.helpButton){
            Intent intent = new Intent(getApplicationContext(), InstructionsActivity.class);
                startActivity(intent); 

        }else if(v.getId() == R.id.nextHoleButton){
            boolean filledIn = false;
            if(driving_spinner_selected && chipping_spinner_selected && putting_spinner_selected && sandshot_spinner_selected && approach_spinner_selected)
                filledIn = true;
            if(filledIn) {
            hole++;
            round.setStats(String.valueOf(driving_spinner.getSelectedItem()),String.valueOf(putting_spinner.getSelectedItem()),String.valueOf(sandshot_spinner.getSelectedItem()),String.valueOf(chipping_spinner.getSelectedItem()),String.valueOf(approach_spinner.getSelectedItem()),hole);
             Intent intent = new Intent(getApplicationContext(), StatActivity.class);
                String target = gS.toJson(round);
                intent.putExtra("round", target);
            if(round.needTip()) {

                String tip  = round.generateTip();
                Toast.makeText(StatActivity.this,
                    tip,
                Toast.LENGTH_LONG).show();
            }
            startActivity(intent);
            }
            else {
                Toast.makeText(StatActivity.this,
                        "Please fill in all statistics before continuing.",
                    Toast.LENGTH_SHORT).show();
            }
          }
        }
    }

HomeActivity

package com.example.testapp;

import com.google.gson.Gson;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class HomeActivity extends Activity implements OnClickListener{



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Button startRoundButton = (Button) findViewById(R.id.startRoundButton);
        Button homeHelpButton = (Button) findViewById(R.id.homeHelpButton);
        homeHelpButton.setOnClickListener(this);
        startRoundButton.setOnClickListener(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    public void onClick(View v)
    {
        if(v.getId() == R.id.startRoundButton){
            Round round = new Round();
            Intent i = new Intent(getApplicationContext(),StatActivity.class);
            Gson gS = new Gson();
            String target = gS.toJson(round);
            i.putExtra("round", target);
            startActivity(i);



        }else if(v.getId() == R.id.homeHelpButton){
            Intent intent = new Intent(getApplicationContext(), InstructionsActivity.class);
                startActivity(intent);  
        }
    }

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

的AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".StatActivity"
            android:label="@string/title_activity_stat" >
        </activity>
        <activity
            android:name=".InstructionsActivity"
            android:label="@string/title_activity_instructions" >
        </activity>
    </application>

</manifest>

Activity_Stat.xml

<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:background="@drawable/here_link"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testapp.StatActivity" >

    <Spinner
        android:id="@+id/puttingSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/approachSpinner"
        android:layout_alignLeft="@+id/approachSpinner"
        android:entries="@array/puttArr"
        android:prompt="@string/putting" />

    <Button
        android:id="@+id/nextHoleButton"
        android:layout_width="150dp"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="@drawable/next_button_background" />

    <Spinner
        android:id="@+id/approachSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/sandShotSpinner"
        android:layout_alignLeft="@+id/sandShotSpinner"
        android:entries="@array/approachArr"
        android:prompt="@string/aproach" />

    <Spinner
        android:id="@+id/sandShotSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/nextHoleButton"
        android:layout_alignLeft="@+id/drivingSpinner"
        android:layout_marginBottom="19dp"
        android:entries="@array/sandShotArr"
        android:prompt="@string/sand_shot" />

    <Spinner
        android:id="@+id/drivingSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/puttingSpinner"
        android:layout_centerHorizontal="true"
        android:entries="@array/drivingArr"
        android:prompt="@string/driving" />

    <Button
        android:id="@+id/helpButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/sandShotSpinner"
        android:layout_alignTop="@+id/homeButton"
        android:text="@string/help" />

    <Button
        android:id="@+id/homeButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/nextHoleButton"
        android:layout_alignParentLeft="true"
        android:text="@string/home" />

    <Spinner
        android:id="@+id/chippingSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/drivingSpinner"
        android:entries="@array/chippingArr"
        android:prompt="@array/chippingArr" />

</RelativeLayout>

在打开应用程序(有效)时启动Home活动,然后在单击Start round按钮时启动stat活动,这是应用程序停止时的状态。 任何想法或想法都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

这一行

String src = getIntent().getStringExtra("round");

是你的问题。当它被调用时,没有意图获得。

需要意图的所有设置都需要在onCreate()内完成,此时意图可用。您的代码正在构建时运行,这太早了。

您还没有真正提供足够的信息来确定这是否会产生您正在制作的NPE,但它确实需要修复,即使它有&#39 ;还有其他错误。