Android Handler Chain NullPointerException

时间:2015-04-15 14:01:53

标签: java android multithreading android-handler

我正试图通过ActivityService - Thread - Handlers之间建立沟通。 Activity启动Service,即ThreadThread向服务器发送请求,等待回复并通过Service将其重新发送到Handler(正常工作)。但是,当我尝试使用NullPointerException从Service的{​​{1}}发送到Handler app的消息时。我做错了什么?

基于Android Handler changing WeakReference

的处理程序代码

我的活动

Activity

我的服务

public class ActivityLogin extends Activity{

    public static LoginHandler loginHandler = null;

    public static class LoginHandler extends Handler {

        private WeakReference<ActivityLogin> target = null;

        LoginHandler(ActivityLogin target) {
            this.target = new WeakReference<ActivityLogin>(target);
        }

        public void setTarget(ActivityLogin target) {
            this.target.clear();
            this.target = new WeakReference<ActivityLogin>(target);
        }

        @Override
        public void handleMessage(Message msg) {
            ActivityLogin activity = this.target.get();
            if(activity == null) return;

            String response = msg.getData().getString("RESPONSE");
            System.err.println("RESPONSE "+response);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d("TAG","---------------------APP STARTED---------------------");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_login);

        if(loginHandler == null) loginHandler = new LoginHandler(this);
        else loginHandler.setTarget(this);
    }

    public void onLogin(View v){

        JsonUser user = new JsonUser();
        user.login = "Name";
        user.password = "Pazzword";
        user.device = "4567-753-5768-2343";

        Intent intent = new Intent(this,ComService.class);
        intent.putExtra("DATA_KEY", new Gson().toJson(user));

        this.startService(intent);
    }
}

我的主题

public class ComService extends Service {

    public static ServiceHandler serviceHandler = null;

    public static class ServiceHandler extends Handler {

        private WeakReference<ComService> target = null;
        ServiceHandler(ComService target) {
            this.target = new WeakReference<ComService>(target);
        }

        public void setTarget(ComService target) {
            this.target.clear();
            this.target = new WeakReference<ComService>(target);
        }

        @Override
        public void handleMessage(Message msg) {
            //ComService service = this.target.get();
            //Process message (msg) and resend to activity
            ActivityLogin.loginHandler.sendMessage(msg);
        }
    }

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

        if(serviceHandler == null) serviceHandler = new ServiceHandler(this);
        else serviceHandler.setTarget(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String message = intent.getStringExtra("DATA_KEY");

        new SendData("http://xxx.xxx.xxx.xxx:27019/WebService.svc/login",message);
        stopSelf(startId);
        return START_REDELIVER_INTENT;
    }
}

更新

public class SendData extends Thread {

    private String requestUrl;
    private String message;

    public SendData(String requestUrl, String message){
        super();
        this.requestUrl = requestUrl;
        this.message = message;
        this.start();
    }

    public void run(){

        String serverResponse = request();
        if(serverResponse == null) return;

        System.err.println(serverResponse);

        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("RESPONSE", serverResponse);
        msg.setData(bundle);

        ComService.serviceHandler.sendMessage(msg);
    }

    private String request(){...}//if need, i can post request code too
}

AndroidManifext.xml

04-15 18:36:35.292  24524-24524/com.example.test E/Trace﹕ error opening trace file: No such file or directory (2)
04-15 18:36:35.332  24524-24524/com.example.test D/TAG﹕ ---------------------APP STARTED---------------------
04-15 18:36:35.462  24524-24524/com.example.test D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
04-15 18:36:35.462  24524-24524/com.example.test D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
04-15 18:36:35.462  24524-24524/com.example.test D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
04-15 18:36:35.492  24524-24524/com.example.test D/OpenGLRenderer﹕ Enabling debug mode 0
04-15 18:36:36.442  24554-24554/com.example.test:background E/Trace﹕ error opening trace file: No such file or directory (2)
04-15 18:36:36.682  24554-24567/com.example.test:background W/System.err﹕ {"status":{"success":false,"message":"some_text"},"result":null}
04-15 18:36:36.682  24554-24554/com.example.test:background D/AndroidRuntime﹕ Shutting down VM
04-15 18:36:36.682  24554-24554/com.example.test:background W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41712300)
04-15 18:36:36.682  24554-24554/com.example.test:background E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.example.test.ComService$ServiceHandler.handleMessage(ComService.java:31)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

总之,我从我的申请中删除了Service。 Android Service是癌症肿瘤,线程没有任何好处。这只是我的意见。