嗨我要調用一個服務來填充數組,但是我得到異常致命例外時,數組填充print_result中的值。如果聲明items.add(orig)被調用,我有這個問題。致命的例外:線程10
異常
W/dalvikvm(11235): threadid=9: thread exiting with uncaught exception (group=0x4
001e578)
E/AndroidRuntime(11235): FATAL EXCEPTION: Thread-10
E/AndroidRuntime(11235): java.lang.NullPointerException
E/AndroidRuntime(11235): at com.example.MyService.print_result(MyService.
java:62)
E/AndroidRuntime(11235): at com.example.MyService$1.run(MyService.java:54
)
E/AndroidRuntime(11235): at java.lang.Thread.run(Thread.java:1019)
W/ActivityManager(2696): Force finishing activity com.example/.ServicesDemo
I/OrientationDebug(2696): [pwm] in updateOrientationListenerLp()
V/OrientationDebug(2696): in updateOrientationListenerLp(), Screen status=true,
current orientation=1, SensorEnabled=true
I/OrientationDebug(2696): [pwm] needSensorRunningLp(), return true #4
I/Launcher(2852): onResume(). mIsNewIntent : false screenOff: false
E/ (2696): Dumpstate > /data/log/dumpstate_app_error
I/dumpstate(11275): begin
D/KeyguardViewMediator(2696): handleTimeout
W/PowerManagerService(2696): Timer 0x3->0x3|0x3
代碼:
package com.example;
import java.util.ArrayList;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
ArrayList<String> items = null;
public String ORIG = "";
private static final String TAG = "MyService";
public Bundle data = new Bundle();
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static String getTag() {
return TAG;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Log.d(TAG, "onStart");
data = intent.getExtras();
ORIG = data.getString("originator");
Log.d(TAG, "onCreate");
Thread initBkgdThread = new Thread(new Runnable() {
public void run() {
print_result(ORIG);
}
});
initBkgdThread.start();
}
public void print_result(String orig){
Log.d(TAG, "HELLO WORLD:" + orig);
items.add(orig);
if (items != null) {
items.add(orig);
String toadd = orig.toString();
if(items.contains(toadd)){
Log.d(TAG, "Element already exists exiting ");
} else {
Log.d(TAG, "Adding Element");
items.add(toadd);
}
}
else {
Log.d(TAG, "IS NULL");
}
}
}
謝謝, –