您好我正在调用一个服务来填充数组,但是当使用print_result中的值填充数组时,我得到异常FATAL EXCEPTION。如果调用语句items.add(orig)我有这个问题。
例外
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");
}
}
}
答案 0 :(得分:1)
您必须先初始化数组
items = new ArrayList<String>();
答案 1 :(得分:0)
您永远不会初始化items
arrayList。将其添加到您的onCreate()
方法:
items = new ArrayList<String>();
答案 2 :(得分:0)
您需要初始化项目。您还要在检查项目是否为空之前添加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 ");
}
}