开发者

Null Pointer exception for onSetClickListener

OK, what I am trying to get my application to do is the following.

  1. when it is opened, display a start button.
  2. when that button is pressed, two services start, one for the accelerometer and one for GPS and the button turns into a stop button.
  3. the services will continue to run until the stop button is pressed, turning off the listeners and stopping the services.
  4. once the stop button is pressed the app then display's a number of calculations that the app carried out as it was collecting data.

Important facts to know:

  1. all of the calculations work
  2. the problem started after I changed the views, There initially was just one view that displayed both the buttons and all of the calculations as they updated in realtime.
  3. I then changed the app to have 3 views. One for each button and one for the results. after I did this the app stopped working. HOWEVER!!!! I may have made some changes without checking to see if they worked before I changed the views but I have been trying to figure out what the problem is for so long that I cannot remember correctly the precise order of events.

This is my current onCreate method:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.start);

    setGPS();
    context = this;

    Button startButton = (Button) findViewById(R.id.startbutton);
    Button stopButton = (Button) findViewById(R.id.stopbutton);

    Log.d("NULL POINTER", "NULL POINTER");
    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d("NULL POINTER", "NULL POINTER");
            //setContentView(R.layout.stop);
            startService();

        }
    });

    stopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            //setContentView(R.layout.results);
            stopService();

        }
    });

Ok, in this code you will see two Log.d prints that say "NULL POINTER". When I run my code, the first one displays but the second one does not, obviously meaning that the code in the middle is causing the program to crash, with this being displayed in the log cat:

06-15 12:30:25.176: DEBUG/AndroidRuntime(1037): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
06-15 12:30:25.185: DEBUG/AndroidRuntime(1037): CheckJNI is ON
06-15 12:30:25.537: DEBUG/AndroidRuntime(1037): --- registering native functions ---
06-15 12:30:25.806: DEBUG/ddm-heap(1037): Got feature list request
06-15 12:30:26.147: INFO/ActivityManager(52): Starting activity: Intent {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=Hartford.gps/.GPSMain }
06-15 12:30:26.177: INFO/ActivityManager(52): Start proc Hartford.gps for activity Hartford.gps/.GPSMain: pid=1043 uid=10030 gids={}
06-15 12:30:26.196: DEBUG/AndroidRuntime(1037): Shutting down VM
06-15 12:30:26.196: DEBUG/dalvikvm(1037): DestroyJavaVM waiting for non-daemon threads to exit
06-15 12:30:26.196: DEBUG/dalvikvm(1037): DestroyJavaVM shutting VM down
06-15 12:30:26.196: DEBUG/dalvikvm(1037): HeapWorker thread shutting down
06-15 12:30:26.207: DEBUG/dalvikvm(1037): HeapWorker thread has shut down
06-15 12:30:26.207: DEBUG/jdwp(1037): JDWP shutting down net...
06-15 12:30:26.226: INFO/dalvikvm(1037): Debugger has detached; object registry had 1 entries
06-15 12:30:26.226: DEBUG/dalvikvm(1037): VM cleaning up
06-15 12:30:26.246: ERROR/AndroidRuntime(1037): ERROR: thread attach failed
06-15 12:30:26.317: DEBUG/dalvikvm(1037): LinearAlloc 0x0 used 638596 of 5242880 (12%)
06-15 12:30:26.456: DEBUG/ddm-heap(1043): Got feature list request
06-15 12:30:26.906: DEBUG/NULL POINTER(1043): NULL POINTER
06-15 12:30:26.916: DEBUG/AndroidRuntime(1043): Shutting down VM
06-15 12:30:26.916: WARN/dalvikvm(1043): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
06-15 12:30:26.916: ERROR/AndroidRuntime(1043): Uncaught handler: thread main exiting due to uncaught exception
06-15 12:30:26.926: ERROR/AndroidRuntime(1043): java.lang.RuntimeException: Unable to start activity ComponentInfo{Hartford.gps/Hartford.gps.GPSMain}: java.lang.NullPointerException
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.os.Looper.loop(Looper.java:123)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.app.ActivityThread.main(ActivityThread.java:4363)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at java.lang.reflect.Method.invokeNative(Native Method)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at java.lang.reflect.Method.invoke(Method.java:521)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at dalvik.system.NativeStart.main(Native Method)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043): Caused by: java.lang.NullPointerException
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at Hartford.gps.GPSMain.onCreate(GPSMain.java:70)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
06-15 12:30:26.926: ERROR/AndroidRuntime(1043):     ... 11 more

I am at my wit's end trying to get this to work! I have tried everything I can think of but I think at this stage I have tunnle vision and that it just needs another set of eyes to look at it.

I can post more code if needs be

Any help that anyone can offer would be awesome!

@ Mark

oh, ok thanks! How do you mean that they might be null? Here is the start.xml file, it is identical to the stop.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:id="@+id/startbutton"
        android:layout_width="100px" 
        android:layout_height="100px" 
        android:text="Start"
        android:layout_centerInParent="true"
    />

</LinearLayout>

@ Egor and Mah

here is the full file with line 70 marked

import java.text.DecimalFormat;
import java.text.NumberFormat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class GPSMain extends Activity   {

PowerManager powerManager;
PowerManager.WakeLock wL;

//text views to display latitude and longitude
static TextView latituteField;
static TextView longitudeField;
static TextView kmphSpeedField;
static TextView avgKmphField;
static TextView topKmphField;
static TextView accText;

//objects to store positional information
protected static double lat;
protected static double lon;

//objects to store values for current and average speed
protected static double kmphSpeed;
protected static double avgKmph;
protected static double totalKmph;
protected static double topKmph=0;

static String a, b, c;

private Context context;

//counter that is incremented every time a new position is received, used to calculate average speed
static int counter = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.start);

    setGPS();
    context = this;

    Button startButton = (Button) findViewById(R.id.startbutton);
    Button stopButton = (Button) findViewById(R.id.stopbutton);

    Log.d("NULL POINTER", "NULL POINTER");
    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d("NUL开发者_JS百科L POINTER", "NULL POINTER");
            //setContentView(R.layout.stop);
            startService();

        }
    });

70      stopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            //setContentView(R.layout.results);
            stopService();

        }
    });

    latituteField = (TextView) findViewById(R.id.lat);
    longitudeField = (TextView) findViewById(R.id.lon);     
    kmphSpeedField = (TextView) findViewById(R.id.kmph);
    avgKmphField = (TextView) findViewById(R.id.avgkmph);
    topKmphField = (TextView) findViewById(R.id.topkmph);
    accText = (TextView) findViewById(R.id.acctext);

}

void setGPS(){
    powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wL = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"My Tag");

}

static String roundTwoDecimalFloat(float a){

    String formattedNum;
    NumberFormat nf = new DecimalFormat();
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);
    formattedNum = nf.format(a);
    return formattedNum;
}

void startService(){

    wL.acquire();
    Log.d("DEBUG", "start");
    startService(new Intent(this, AccelerometerReader.class));
    Toast.makeText(context, "Accessing Accelerometer", Toast.LENGTH_LONG).show();
    //startService(new Intent(this, Calculations.class));
    //Toast.makeText(context, "Acquiring GPS Locations", Toast.LENGTH_LONG).show();

}

void stopService(){

    wL.release();
    Calculations.locationManager.removeUpdates(Calculations.locationListener);
    stopService(new Intent(this, AccelerometerReader.class));
    Toast.makeText(context, "Terminating Accelerometer", Toast.LENGTH_LONG).show();
    //stopService(new Intent(this, Calculations.class));
    //Toast.makeText(context, "Terminating Connection", Toast.LENGTH_LONG).show();

}

static void update(){

    latituteField.setText("Current Latitude: "+String.valueOf(lat));
    longitudeField.setText("Current Longitude: "+String.valueOf(lon));
    kmphSpeedField.setText("Cuttent Speed (kmph): "+String.valueOf(kmphSpeed));
    avgKmphField.setText("Average Speed (kmph): "+String.valueOf(avgKmph));
    topKmphField.setText("Top Speed (kmph): "+String.valueOf(topKmph));
    accText.setText("Accelerometer Values: "+" x: " + a + " y: " + b + " z: " + c);

}

}


You're wrong in your assertion that the two Log statements prove that the error occurs between them. The onClick() code will be executed at a later point.

The most likely cause of your error is that either startButton or stopButton is null, and that one or both of your findViewById lookups is failing. Try dumping those in log statements, or run it under a debugger and inspecting them to see which is null.

EDIT: Seeing your XML files, the problem is now clear. You are inflating start.xml, and this contains a definition for R.id.startbutton. But it does not contain a definition for R.id.stopbutton. Therefore your Button stopButton = (Button) findViewById(R.id.stopbutton); is setting stopButton to null because it does not exist in your layout. You then try and add an OnClickListener to this null object, which is causing your NPE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜