android - BluetoothChat like app not communicating -


have problem while developing app based in bluetoothchat example, divided in 2 activities.

  1. the main bluetooth actions ()btactivity
  2. the chat (btcommunication)

i have bluetoothchatservice divided in following files, aren't activities:

  1. transmission: handler actions
  2. connectthread
  3. connectedthread
  4. accpetthread

the app finds de device, starts connecting , crashes. i'm trying find out i'm doing wrong comparing bluetoothchat app, don't find problem.

07-23 10:58:43.076: d/abslistview(17279): unregisterirlistener() called  07-23 10:58:43.076: d/abslistview(17279): unregisterirlistener() called  07-23 10:58:43.086: d/bluetoothutils(17279): issocketallowedbysecuritypolicy start : device null 07-23 10:58:43.086: w/bluetoothadapter(17279): getbluetoothservice() called no bluetoothmanagercallback 07-23 10:58:43.106: e/spannablestringbuilder(17279): span_exclusive_exclusive spans cannot have 0 length 07-23 10:58:43.106: e/spannablestringbuilder(17279): span_exclusive_exclusive spans cannot have 0 length 07-23 10:58:43.116: d/abslistview(17279): ondetachedfromwindow 07-23 10:58:43.116: d/abslistview(17279): unregisterirlistener() called  07-23 10:58:43.116: d/abslistview(17279): ondetachedfromwindow 07-23 10:58:43.116: d/abslistview(17279): unregisterirlistener() called  07-23 10:58:44.527: d/androidruntime(17279): shutting down vm 07-23 10:58:44.527: w/dalvikvm(17279): threadid=1: thread exiting uncaught exception (group=0x41d58ac8) 07-23 10:58:44.537: e/androidruntime(17279): fatal exception: main 07-23 10:58:44.537: e/androidruntime(17279): java.lang.nullpointerexception 07-23 10:58:44.537: e/androidruntime(17279):    @ com.example.btaplication.btactivity$1.handlemessage(btactivity.java:288) 07-23 10:58:44.537: e/androidruntime(17279):    @ android.os.handler.dispatchmessage(handler.java:99) 07-23 10:58:44.537: e/androidruntime(17279):    @ android.os.looper.loop(looper.java:137) 07-23 10:58:44.537: e/androidruntime(17279):    @ android.app.activitythread.main(activitythread.java:5328) 07-23 10:58:44.537: e/androidruntime(17279):    @ java.lang.reflect.method.invokenative(native method) 07-23 10:58:44.537: e/androidruntime(17279):    @ java.lang.reflect.method.invoke(method.java:511) 07-23 10:58:44.537: e/androidruntime(17279):    @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1102) 07-23 10:58:44.537: e/androidruntime(17279):    @ com.android.internal.os.zygoteinit.main(zygoteinit.java:869) 07-23 10:58:44.537: e/androidruntime(17279):    @ dalvik.system.nativestart.main(native method) 07-23 10:58:55.428: i/process(17279): sending signal. pid: 17279 sig: 9 

/ here main activity

public class btactivity extends activity {   @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);      setcontentview(r.layout.main);      final button button1 = (button) findviewbyid(r.id.boton1);     final button button2 = (button) findviewbyid(r.id.boton2);     final button button4 = (button) findviewbyid(r.id.boton4);     final button button5 = (button) findviewbyid(r.id.boton5);      button5.setonclicklistener(new onclicklistener() {         @override         public void onclick(view view) {             lanzarcomunicacion (null);         }     });       globalvar.mbluetoothadapter = bluetoothadapter.getdefaultadapter();      if (globalvar.mbluetoothadapter == null) {         toast.maketext(this, "bluetooth not available", toast.length_long).show();         finish();         return;     }      button2.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             lanzarbusqueda(null);          }     });      button1.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             if (!globalvar.mbluetoothadapter.isdiscovering()) {                  context context = getapplicationcontext();                 charsequence text = "making device discoverable";                 int duration = toast.length_short;                  toast toast = toast.maketext(context, text, duration);                 toast.show();                  intent discoverableintent = new intent(bluetoothadapter.action_request_discoverable);                 discoverableintent.putextra(bluetoothadapter.extra_discoverable_duration, 300);                  startactivity(discoverableintent);             }         }     });      button4.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             globalvar.mbluetoothadapter.disable();              context context = getapplicationcontext();             charsequence text = "turning off bluetooth";             int duration = toast.length_long;              toast toast = toast.maketext(context, text, 15);             toast.show();          }     }); }   @override public void onstart() {     super.onstart();      if (!globalvar.mbluetoothadapter.isenabled()) {          intent enablebtintent = new intent(bluetoothadapter.action_request_enable);         startactivityforresult(enablebtintent, globalvar.request_enable_bt);     }     else {         if (globalvar.mtransmission == null) setupcaller();     } }   @override public void onresume() {     super.onresume();      if (globalvar.mtransmission != null) {         /**only if state state_none, know haven't started already*/         if (globalvar.mtransmission.getstate() == globalvar.state_none) {          }     } }   @override public void onactivityresult(int requestcode, int resultcode, intent data) {     switch (requestcode) {         case globalvar.request_connect_device:             /**when devicelistactivity returns device connect*/             if (resultcode == activity.result_ok) {                 connectdevice(data);             }         case globalvar.request_enable_bt:             /**when request enable bluetooth returns*/             if (resultcode == activity.result_ok) {                 /**bluetooth enabled, set chat session*/                 setupcaller();             } else {                 /**user did not enable bluetooth or error occurred*/                 toast.maketext(this, r.string.bt_not_enabled_leaving, toast.length_short).show();                 finish();             }             break;     }  }   private void connectdevice(intent data) {     /**get device mac address*/     string address = data.getextras().getstring(devicelistdialog.extra_device_address);     /**get bluetoothdevice object*/     bluetoothdevice device = globalvar.mbluetoothadapter.getremotedevice(address);     /**attempt connect device*/     try{         globalvar.mtransmission.connect(device);     }catch(exception ex) {     } }   @override public boolean oncreateoptionsmenu(menu menu) {     /**inflate menu; adds items action bar if present.*/     getmenuinflater().inflate(r.menu.bt, menu);     return true; }  public void lanzarcomunicacion (view view) {     intent = new intent(this, btcommunication.class);     startactivity(i); }  public void lanzarbusqueda (view view) {     intent serverintent = new intent(this, devicelistdialog.class);     startactivityforresult(serverintent, globalvar.request_connect_device); }   private final void setstatus(int resid) {     final actionbar actionbar = getactionbar();     actionbar.setsubtitle(resid); }  private final void setstatus(charsequence subtitle) {     final actionbar actionbar = getactionbar();     actionbar.setsubtitle(subtitle); }   /**  * handler gets information transmission  */ private final handler mhandler = new handler() {     @override     public void handlemessage(message msg) {         switch (msg.what) {             case globalvar.message_state_change:                 switch (msg.arg1) {                     case globalvar.state_connected:                         setstatus(getstring(r.string.title_connected_to, globalvar.mconnecteddevicename));                         globalvar.mconversationarrayadapter.clear();                         break;                     case globalvar.state_connecting:                         setstatus(r.string.title_connecting);                         break;                     case globalvar.state_listen:                     case globalvar.state_none:                         setstatus(r.string.title_not_connected);                         break;                 }                 break;             case  globalvar.message_write:                 byte[] writebuf = (byte[]) msg.obj;                 /**construct string buffer*/                 string writemessage = new string(writebuf);                 globalvar.mconversationarrayadapter.add("me:  " + writemessage);                 break;             case  globalvar.message_read:                 byte[] readbuf = (byte[]) msg.obj;                 /**construct string valid bytes in buffer*/                 string readmessage = new string(readbuf, 0, msg.arg1);                 globalvar.mconversationarrayadapter.add(globalvar.mconnecteddevicename+":  " + readmessage);                 break;             case  globalvar.message_device_name:                 /**save connected device's name*/                 globalvar.mconnecteddevicename = msg.getdata().getstring(globalvar.device_name);                 toast.maketext(getapplicationcontext(), "connected " + globalvar.mconnecteddevicename, toast.length_short).show();                 break;             case  globalvar.message_toast:                 toast.maketext(getapplicationcontext(), msg.getdata().getstring(globalvar.toast), toast.length_short).show();                 break;         }     } };  public void setupcaller() {     /**initialize transmission perform bluetooth connections*/     globalvar.mtransmission = new transmission(this, mhandler); } 

}

/ chat avtivity

public class btcommunication extends activity {   @override public void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);      /**set window layout*/     setcontentview(r.layout.chat);      /**start bluetooth chat services*/     globalvar.mtransmission.start();     setupchat(); //probamos llamar aqui\\ }    public void setupchat() {     /**initialize array adapter conversation thread*/     globalvar.mconversationarrayadapter = new arrayadapter<string>(this, r.layout.message);     globalvar.mconversationview = (listview) findviewbyid(r.id.in);     globalvar.mconversationview.setadapter(globalvar.mconversationarrayadapter);      /**initialize compose field listener return key*/     globalvar.moutedittext = (edittext) findviewbyid(r.id.edit_text_out);     globalvar.moutedittext.setoneditoractionlistener(mwritelistener);      /**initialize send button listener click events*/     globalvar.msendbutton = (button) findviewbyid(r.id.button_send);     globalvar.msendbutton.setonclicklistener(new onclicklistener() {         @override         public void onclick(view v) {             /**send message using content of edit text widget*/             textview view = (textview) findviewbyid(r.id.edit_text_out);             string message = view.gettext().tostring();             sendmessage(message);         }     });      /**initialize transmission perform bluetooth connections*/     //done in btactivity in function "setupcaller()"\\       /**initialize buffer outgoing messages*/     globalvar.moutstringbuffer = new stringbuffer(""); }    @override public void ondestroy() {     super.ondestroy();     /**stop bluetooth chat services*/     if (globalvar.mtransmission != null) globalvar.mtransmission.stop(); }   /**  * sends message.  * @param message  string of text send.  */ public void sendmessage(string message) {     /**check we're connected before trying anything*/     if (globalvar.mtransmission.getstate() != globalvar.state_connected) {         toast.maketext(this, r.string.not_connected, toast.length_short).show();         return;     }      /**check there's send*/     if (message.length() > 0) {         /**get message bytes , tell bluetoothchatservice write*/         byte[] send = message.getbytes();         globalvar.mtransmission.write(send);          /**reset out string buffer 0 , clear edit text field*/         globalvar.moutstringbuffer.setlength(0);         globalvar. moutedittext.settext(globalvar.moutstringbuffer);     } }  /**the action listener edittext widget, listen return key*/ private final textview.oneditoractionlistener mwritelistener = new textview.oneditoractionlistener() {     @override     public boolean oneditoraction(textview view, int actionid, keyevent event) {         /**if action key-up event on return key, send message*/         if (actionid == editorinfo.ime_null && event.getaction() == keyevent.action_up) {             string message = view.gettext().tostring();             sendmessage(message);         }         return true;     } }; 

}

/the transmission file:

public class transmission {  /**  * constructor. prepares new session.  * @param context  ui activity context  * @param handler  handler send messages ui activity  */ public transmission(context context, handler handler) {     globalvar.madapter = bluetoothadapter.getdefaultadapter();     globalvar.mstate = globalvar.state_none;     globalvar.mhandler = handler; }  /**  * set current state of connection  * @param state  integer defining current connection state  */ public synchronized void setstate(int state) {     globalvar.mstate = state;      /**give new state handler ui activity can update*/     globalvar.mhandler.obtainmessage(globalvar.message_state_change, state, -1).sendtotarget(); }  /**  * return current connection state.  */ public synchronized int getstate() {     return globalvar.mstate; }  /**  * start chat service. start acceptthread begin  * session in listening (server) mode. called activity onresume()  */ public synchronized void start() {     /**cancel thread attempting make connection*/     if (globalvar.mconnectthread != null) {globalvar.mconnectthread.cancel(); globalvar.mconnectthread = null;}      /**cancel thread running connection*/     if (globalvar.mconnectedthread != null) {globalvar.mconnectedthread.cancel(); globalvar.mconnectedthread = null;}      setstate(globalvar.state_listen);      /**start thread listen on bluetoothserversocket*/     if (globalvar.macceptthread == null) {         globalvar.macceptthread = new acceptthread();         globalvar.macceptthread.start();     } }  /**  * start connectthread initiate connection remote device.  * @param device  bluetoothdevice connect  */ public synchronized void connect(bluetoothdevice device) {     /**cancel thread attempting make connection*/     if (globalvar.mstate == globalvar.state_connecting) {         if (globalvar.mconnectthread != null) {globalvar.mconnectthread.cancel(); globalvar.mconnectthread = null;}     }      /**cancel thread running connection*/     if (globalvar.mconnectedthread != null) {globalvar.mconnectedthread.cancel(); globalvar.mconnectedthread = null;}      /**start thread connect given device*/     globalvar.mconnectthread = new connectthread(device);     globalvar.mconnectthread.start();     setstate(globalvar.state_connecting); }  /**  * start connectedthread begin managing bluetooth connection  * @param socket  bluetoothsocket on connection made  * @param device  bluetoothdevice has been connected  */ public synchronized void connected(bluetoothsocket socket, bluetoothdevice device) {     /**cancel thread completed connection*/     if (globalvar.mconnectthread != null) {globalvar.mconnectthread.cancel(); globalvar.mconnectthread = null;}      /**cancel thread running connection*/     if (globalvar.mconnectedthread != null) {globalvar.mconnectedthread.cancel(); globalvar.mconnectedthread = null;}      /**cancel accept thread because want connect 1 device*/     if (globalvar.macceptthread != null) {         globalvar.macceptthread.cancel();         globalvar.macceptthread = null;     }      /**start thread manage connection , perform transmissions*/     globalvar.mconnectedthread = new connectedthread(socket);     globalvar.mconnectedthread.start();      /**send name of connected device ui activity*/     message msg = globalvar.mhandler.obtainmessage(globalvar.message_device_name);     bundle bundle = new bundle();     bundle.putstring(globalvar.device_name, device.getname());     msg.setdata(bundle);     globalvar.mhandler.sendmessage(msg);      setstate(globalvar.state_connected); }  /**  * stop threads  */ public synchronized void stop() {      if (globalvar.mconnectthread != null) {         globalvar.mconnectthread.cancel();         globalvar.mconnectthread = null;     }      if (globalvar.mconnectedthread != null) {         globalvar.mconnectedthread.cancel();         globalvar.mconnectedthread = null;     }      if (globalvar.macceptthread != null) {         globalvar.macceptthread.cancel();         globalvar.macceptthread = null;     }      setstate(globalvar.state_none); }  /**  * write connectedthread in unsynchronized manner  * @param out bytes write  * @see connectedthread#write(byte[])  */ public void write(byte[] out) {     /**create temporary object*/     connectedthread r;     /**synchronize copy of connectedthread*/     synchronized (this) {         if (globalvar.mstate != globalvar.state_connected) return;         r = globalvar.mconnectedthread;     }     /**perform write unsynchronized*/     r.write(out); }  /**  * indicate connection attempt failed , notify ui activity.  */ public void connectionfailed() {     /**send failure message activity*/     message msg = globalvar.mhandler.obtainmessage(globalvar.message_toast);     bundle bundle = new bundle();     bundle.putstring(globalvar.toast, "unable connect device");     msg.setdata(bundle);     globalvar.mhandler.sendmessage(msg);      /**tart service on restart listening mode*/     transmission.this.start(); }  /**  * indicate connection lost , notify ui activity.  */ public void connectionlost() {     /**send failure message activity*/     message msg = globalvar.mhandler.obtainmessage(globalvar.message_toast);     bundle bundle = new bundle();     bundle.putstring(globalvar.toast, "device connection lost");     msg.setdata(bundle);     globalvar.mhandler.sendmessage(msg);      /**start service on restart listening mode*/     transmission.this.start(); } 

}

/the accept, connect , connected threads same in bleutoothchat app each 1 has it's own file.

07-23 10:58:44.537: e/androidruntime(17279):    @ com.example.btaplication.btactivity$1.handlemessage(btactivity.java:288) 

you need more condition in handler. crashes because have null pointer in btactivity.

i had problem 2 weeks ago (i trying change text of textview in handler). so, in handler put :

if(mtextview == null) {mtextview = (textview) findviewbyid(r.id.tv)} 

even if mtextview define before. in case sure attribute define, , avoid npe

hope helps


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -