java - Null pointer exception: invoking virtual method -


i trying design basic chat app. app build without errors click button on emulator app crashes , log shows following error:

07-01 22:50:39.367  30016-30032/com.example.ibm_admin.chat e/buffer error﹕ error converting result java.lang.nullpointerexception: lock == null 07-01 22:50:39.367  30016-30032/com.example.ibm_admin.chat e/json parser﹕ error parsing data org.json.jsonexception: end of input @ character 0 of 07-01 22:50:39.370  30016-30016/com.example.ibm_admin.chat d/androidruntime﹕ shutting down vm 07-01 22:50:39.370  30016-30016/com.example.ibm_admin.chat e/androidruntime﹕ fatal exception: main     process: com.example.ibm_admin.chat, pid: 30016     java.lang.nullpointerexception: attempt invoke virtual method 'int org.json.jsonarray.length()' on null object reference             @ com.example.ibm_admin.chat.userfragment$load.onpostexecute(userfragment.java:84)             @ com.example.ibm_admin.chat.userfragment$load.onpostexecute(userfragment.java:71)             @ android.os.asynctask.finish(asynctask.java:632)             @ android.os.asynctask.access$600(asynctask.java:177)             @ android.os.asynctask$internalhandler.handlemessage(asynctask.java:645)             @ android.os.handler.dispatchmessage(handler.java:102)             @ android.os.looper.loop(looper.java:135)             @ android.app.activitythread.main(activitythread.java:5221)             @ java.lang.reflect.method.invoke(native method)             @ java.lang.reflect.method.invoke(method.java:372)             @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:899)             @ com.android.internal.os.zygoteinit.main(zygoteinit.java:694) 07-01 22:50:40.975  30016-30023/com.example.ibm_admin.chat w/art﹕ suspending threads took: 15.530ms 07-01 22:51:02.766  30016-30023/com.example.ibm_admin.chat w/art﹕ suspending threads took: 6.893ms 

mainactivity.java

import android.app.activity; import android.app.fragment; import android.app.fragmenttransaction; import android.content.context; import android.content.sharedpreferences; import android.os.asynctask; import android.os.bundle; import android.util.log; import android.widget.toast;  import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.googleplayservicesutil; import com.google.android.gms.gcm.googlecloudmessaging;  import java.io.ioexception;   public class mainactivity extends activity {      private final static int play_services_resolution_request = 9000;      string sender_id = "your project number";       static final string tag = "l2c";      googlecloudmessaging gcm;     sharedpreferences prefs;     context context;     string regid;     @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);         prefs = getsharedpreferences("chat", 0);         context = getapplicationcontext();         if(!prefs.getstring("reg_from","").isempty()){             fragment user = new userfragment();             fragmenttransaction ft = getfragmentmanager().begintransaction();             ft.replace(r.id.content_frame, user);             ft.settransition(fragmenttransaction.transit_fragment_fade);             ft.addtobackstack(null);             ft.commit();         }else  if(!prefs.getstring("reg_id", "").isempty()){             fragment reg = new loginfragment();             fragmenttransaction ft = getfragmentmanager().begintransaction();             ft.replace(r.id.content_frame, reg);             ft.settransition(fragmenttransaction.transit_fragment_fade);             ft.addtobackstack(null);             ft.commit();          }else if(checkplayservices()){              new register().execute();          }else{             toast.maketext(getapplicationcontext(),"this device not supported",toast.length_short).show();         }     }     private boolean checkplayservices() {         int resultcode = googleplayservicesutil.isgoogleplayservicesavailable(this);         if (resultcode != connectionresult.success) {             if (googleplayservicesutil.isuserrecoverableerror(resultcode)) {                 googleplayservicesutil.geterrordialog(resultcode, this,                         play_services_resolution_request).show();             } else {                 log.i(tag, "this device not supported.");                 finish();             }             return false;         }         return true;     }       private class register extends asynctask<string, string, string> {          @override         protected string doinbackground(string... args) {             try {                 if (gcm == null) {                     gcm = googlecloudmessaging.getinstance(context);                     regid = gcm.register(sender_id);                     log.e("regid",regid);                      sharedpreferences.editor edit = prefs.edit();                     edit.putstring("reg_id", regid);                     edit.commit();                  }                  return  regid;              } catch (ioexception ex) {                 log.e("error", ex.getmessage());                 return "fails";              }         }         @override         protected void onpostexecute(string json) {             fragment reg = new loginfragment();             fragmenttransaction ft = getfragmentmanager().begintransaction();             ft.replace(r.id.content_frame, reg);             ft.settransition(fragmenttransaction.transit_fragment_fade);             ft.addtobackstack(null);             ft.commit();         }     } } 

jsonparser.java

import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.unsupportedencodingexception; import java.util.list;  import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.namevaluepair; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import android.util.log;   public class jsonparser {     static inputstream = null;     static jsonobject jobj = null;     static jsonarray jary = null;     static string json = "";     // constructor     public jsonparser() {     }     public jsonobject getjsonfromurl(string url,list<namevaluepair> params) {         // making http request         try {             // defaulthttpclient             defaulthttpclient httpclient = new defaulthttpclient();             httppost httppost = new httppost(url);             if(params != null){                 httppost.setentity(new urlencodedformentity(params));             }             httpresponse httpresponse = httpclient.execute(httppost);             httpentity httpentity = httpresponse.getentity();             = httpentity.getcontent();         } catch (unsupportedencodingexception e) {             e.printstacktrace();         } catch (clientprotocolexception e) {             e.printstacktrace();         } catch (ioexception e) {             e.printstacktrace();         }         try {             bufferedreader reader = new bufferedreader(new inputstreamreader(                     is, "iso-8859-1"), 8);             stringbuilder sb = new stringbuilder();             string line = null;             while ((line = reader.readline()) != null) {                 sb.append(line + "n");             }             is.close();             json = sb.tostring();         } catch (exception e) {             log.e("buffer error", "error converting result " + e.tostring());         }         // try parse string json object         try {             jobj = new jsonobject(json);         } catch (jsonexception e) {             log.e("json parser", "error parsing data " + e.tostring());         }         // return json string         return jobj;     }      public jsonarray getjsonarray(string url,list<namevaluepair> params) {         // making http request         try {             // defaulthttpclient             defaulthttpclient httpclient = new defaulthttpclient();             httppost httppost = new httppost(url);             httppost.setentity(new urlencodedformentity(params));             httpresponse httpresponse = httpclient.execute(httppost);             httpentity httpentity = httpresponse.getentity();             = httpentity.getcontent();         } catch (unsupportedencodingexception e) {             e.printstacktrace();         } catch (clientprotocolexception e) {             e.printstacktrace();         } catch (ioexception e) {             e.printstacktrace();     }         try {             bufferedreader reader = new bufferedreader(new inputstreamreader(                     is, "iso-8859-1"), 8);             stringbuilder sb = new stringbuilder();             string line = null;             while ((line = reader.readline()) != null) {                 sb.append(line + "n");             }             is.close();             json = sb.tostring();             log.e("jss",json);         } catch (exception e) {             log.e("buffer error", "error converting result " + e.tostring());         }         // try parse string json object         try {             jary = new jsonarray(json);         } catch (jsonexception e) {             log.e("json parser", "error parsing data " + e.tostring());         }         // return json string         return jary;     } } 

loginfragment.java

import android.app.fragment; import android.app.fragmenttransaction; import android.app.progressdialog; import android.content.sharedpreferences; import android.os.asynctask; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.button; import android.widget.edittext; import android.widget.toast;   import org.apache.http.namevaluepair; import org.apache.http.message.basicnamevaluepair; import org.json.jsonexception; import org.json.jsonobject;  import java.util.arraylist; import java.util.list;   public class loginfragment extends fragment {     sharedpreferences prefs;     edittext name, mobno;     button login;     list<namevaluepair> params;     progressdialog progress;     @override     public view oncreateview(layoutinflater inflater,viewgroup container, bundle savedinstancestate) {         view view = inflater.inflate(r.layout.login_fragment, container, false);         prefs = getactivity().getsharedpreferences("chat", 0);          name = (edittext)view.findviewbyid(r.id.name);         mobno = (edittext)view.findviewbyid(r.id.mobno);         login = (button)view.findviewbyid(r.id.log_btn);         progress = new progressdialog(getactivity());         progress.setmessage("registering ...");         progress.setprogressstyle(progressdialog.style_spinner);         progress.setindeterminate(true);            login.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 progress.show();                 sharedpreferences.editor edit = prefs.edit();                 edit.putstring("reg_from", mobno.gettext().tostring());                 edit.putstring("from_name", name.gettext().tostring());                 edit.commit();                 new login().execute();             }         });          return view;     }     private class login extends asynctask<string, string, jsonobject> {          @override         protected jsonobject doinbackground(string... args) {             jsonparser json = new jsonparser();             params = new arraylist<namevaluepair>();             params.add(new basicnamevaluepair("name", name.gettext().tostring()));             params.add(new basicnamevaluepair("mobno", mobno.gettext().tostring()));             params.add((new basicnamevaluepair("reg_id",prefs.getstring("reg_id",""))));              jsonobject jobj = json.getjsonfromurl("http://10.0.2.2:8080/login",params);             return jobj;            }         @override         protected void onpostexecute(jsonobject json) {             progress.dismiss();             try {                 string res = json.getstring("response");                 if(res.equals("sucessfully registered")) {                     fragment reg = new userfragment();                     fragmenttransaction ft = getfragmentmanager().begintransaction();                     ft.replace(r.id.content_frame, reg);                     ft.settransition(fragmenttransaction.transit_fragment_fade);                     ft.addtobackstack(null);                     ft.commit();                 }else{                     toast.maketext(getactivity(),res,toast.length_short).show();                  }              } catch (jsonexception e) {                 e.printstacktrace();             }          }     }  } 

userfragment.java

import android.app.fragment; import android.app.fragmenttransaction; import android.content.intent; import android.content.sharedpreferences; import android.os.asynctask; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.adapterview; import android.widget.button; import android.widget.listadapter; import android.widget.listview; import android.widget.simpleadapter; import android.widget.toast;  import org.apache.http.namevaluepair; import org.apache.http.message.basicnamevaluepair; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject;  import java.util.arraylist; import java.util.hashmap; import java.util.list;   public class userfragment extends fragment {     listview list;     arraylist<hashmap<string, string>> users = new arraylist<hashmap<string, string>>();     button refresh,logout;     list<namevaluepair> params;     sharedpreferences prefs;       @override     public view oncreateview(layoutinflater inflater,viewgroup container, bundle savedinstancestate) {         view view =inflater.inflate(r.layout.user_fragment, container, false);         prefs = getactivity().getsharedpreferences("chat", 0);          list = (listview)view.findviewbyid(r.id.listview);         refresh = (button)view.findviewbyid(r.id.refresh);         logout = (button)view.findviewbyid(r.id.logout);         logout.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 new  logout().execute();              }         });         refresh.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                  getfragmentmanager().begintransaction().remove(getfragmentmanager().findfragmentbyid(r.id.content_frame)).commit();                 fragment reg = new userfragment();                 fragmenttransaction ft = getfragmentmanager().begintransaction();                 ft.replace(r.id.content_frame, reg);                 ft.settransition(fragmenttransaction.transit_fragment_fade);                 ft.addtobackstack(null);                 ft.commit();              }         });         new load().execute();          return view;     }      private class load extends asynctask<string, string, jsonarray> {          @override         protected jsonarray doinbackground(string... args) {             jsonparser json = new jsonparser();             params = new arraylist<namevaluepair>();             params.add(new basicnamevaluepair("mobno", prefs.getstring("reg_from","")));             jsonarray jary = json.getjsonarray("http://10.0.2.2:8080/getuser",params);              return jary;         }         @override         protected void onpostexecute(jsonarray json) {             for(int = 0; < json.length(); i++){                 jsonobject c = null;                 try {                     c = json.getjsonobject(i);                     string name = c.getstring("name");                     string mobno = c.getstring("mobno");                     hashmap<string, string> map = new hashmap<string, string>();                     map.put("name", name);                     map.put("mobno", mobno);                     users.add(map);                 } catch (jsonexception e) {                     e.printstacktrace();                 }              }             listadapter adapter = new simpleadapter(getactivity(), users,                     r.layout.user_list_single,                     new string[] { "name","mobno" }, new int[] {                     r.id.name, r.id.mobno});             list.setadapter(adapter);             list.setonitemclicklistener(new adapterview.onitemclicklistener() {                 @override                 public void onitemclick(adapterview<?> parent, view view,                                         int position, long id) {                     bundle args = new bundle();                     args.putstring("mobno", users.get(position).get("mobno"));                     intent chat = new intent(getactivity(), chatactivity.class);                     chat.putextra("info", args);                     startactivity(chat);                 }             });         }     }     private class logout extends asynctask<string, string, jsonobject> {          @override         protected jsonobject doinbackground(string... args) {             jsonparser json = new jsonparser();             params = new arraylist<namevaluepair>();             params.add(new basicnamevaluepair("mobno", prefs.getstring("reg_from","")));             jsonobject jobj = json.getjsonfromurl("http://10.0.2.2:8080/logout",params);              return jobj;         }         @override         protected void onpostexecute(jsonobject json) {              string res = null;             try {                 res = json.getstring("response");                 toast.maketext(getactivity(),res,toast.length_short).show();                 if(res.equals("removed sucessfully")) {                     fragment reg = new loginfragment();                     fragmenttransaction ft = getfragmentmanager().begintransaction();                     ft.replace(r.id.content_frame, reg);                     ft.settransition(fragmenttransaction.transit_fragment_fade);                     ft.addtobackstack(null);                     ft.commit();                     sharedpreferences.editor edit = prefs.edit();                     edit.putstring("reg_from", "");                     edit.commit();                 }             } catch (jsonexception e) {                 e.printstacktrace();             }            }     }  } 

chatactivity.java

import android.app.activity; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.content.sharedpreferences; import android.graphics.color; import android.os.asynctask; import android.os.bundle; import android.support.v4.content.localbroadcastmanager; import android.text.html;  import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.tablelayout; import android.widget.tablerow; import android.widget.textview; import android.widget.toast;  import org.apache.http.namevaluepair; import org.apache.http.message.basicnamevaluepair; import org.json.jsonexception; import org.json.jsonobject;  import java.util.arraylist; import java.util.list;   public class chatactivity extends activity {     sharedpreferences prefs;     list<namevaluepair> params;     edittext chat_msg;     button send_btn;     bundle bundle;     tablelayout tab;     @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_chat);         tab = (tablelayout)findviewbyid(r.id.tab);          prefs = getsharedpreferences("chat", 0);         bundle = getintent().getbundleextra("info");         sharedpreferences.editor edit = prefs.edit();         edit.putstring("current_active", bundle.getstring("mobno"));         edit.commit();         localbroadcastmanager.getinstance(this).registerreceiver(onnotice, new intentfilter("msg"));           if(bundle.getstring("name") != null){             tablerow tr1 = new tablerow(getapplicationcontext());             tr1.setlayoutparams(new tablerow.layoutparams( tablerow.layoutparams.wrap_content, tablerow.layoutparams.wrap_content));             textview textview = new textview(getapplicationcontext());             textview.settextsize(20);             textview.settextcolor(color.parsecolor("#0b0719"));             textview.settext(html.fromhtml("<b>"+bundle.getstring("name")+" : </b>"+bundle.getstring("msg")));             tr1.addview(textview);             tab.addview(tr1);          }          chat_msg = (edittext)findviewbyid(r.id.chat_msg);         send_btn = (button)findviewbyid(r.id.sendbtn);          send_btn.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 tablerow tr2 = new tablerow(getapplicationcontext());                 tr2.setlayoutparams(new tablerow.layoutparams( tablerow.layoutparams.wrap_content, tablerow.layoutparams.wrap_content));                 textview textview = new textview(getapplicationcontext());                 textview.settextsize(20);                 textview.settextcolor(color.parsecolor("#a901db"));                 textview.settext(html.fromhtml("<b>you : </b>" + chat_msg.gettext().tostring()));                 tr2.addview(textview);                 tab.addview(tr2);                 new send().execute();             }         });       }      private broadcastreceiver onnotice= new broadcastreceiver() {          @override         public void onreceive(context context, intent intent) {             string str = intent.getstringextra("msg");             string str1 = intent.getstringextra("fromname");             string str2 = intent.getstringextra("fromu");             if(str2.equals(bundle.getstring("mobno"))){                  tablerow tr1 = new tablerow(getapplicationcontext());                 tr1.setlayoutparams(new tablerow.layoutparams( tablerow.layoutparams.wrap_content, tablerow.layoutparams.wrap_content));                 textview textview = new textview(getapplicationcontext());                 textview.settextsize(20);                 textview.settextcolor(color.parsecolor("#0b0719"));                 textview.settext(html.fromhtml("<b>"+str1+" : </b>"+str));                 tr1.addview(textview);                 tab.addview(tr1);             }            }     };     private class send extends asynctask<string, string, jsonobject> {          @override         protected jsonobject doinbackground(string... args) {             jsonparser json = new jsonparser();             params = new arraylist<namevaluepair>();              params.add(new basicnamevaluepair("from", prefs.getstring("reg_from","")));             params.add(new basicnamevaluepair("fromn", prefs.getstring("from_name","")));             params.add(new basicnamevaluepair("to", bundle.getstring("mobno")));             params.add((new basicnamevaluepair("msg",chat_msg.gettext().tostring())));              jsonobject jobj = json.getjsonfromurl("http://10.0.2.2:8080/send",params);             return jobj;            }         @override         protected void onpostexecute(jsonobject json) {             chat_msg.settext("");              string res = null;             try {                 res = json.getstring("response");                 if(res.equals("failure")){                     toast.maketext(getapplicationcontext(),"the user has logged out. cant send message anymore !",toast.length_short).show();                  }             } catch (jsonexception e) {                 e.printstacktrace();             }          }     } } 

please can me?

this:

java.lang.nullpointerexception: attempt invoke virtual method 'int org.json.jsonarray.length()' on null object reference         @ com.example.ibm_admin.chat.userfragment$load.onpostexecute(userfragment.java:84) 

means, in file userfragment.java @ line 84 in inner class load of class com.example.ibm_admin.chat.userfragment there method length called on object, null.

i suppose, line:

        for(int = 0; < json.length(); i++){ 

in method parameter json equals null.

probably, in doinbackroung method, jobj.getjsonarray returns null.

it hard know happened, because jsonparser.getjsonarray suppresses exceptions , returns null, if any.

look @ next 2 lines of logcat:

07-01 22:50:39.367  30016-30032/com.example.ibm_admin.chat e/buffer error﹕ error converting result java.lang.nullpointerexception: lock == null 07-01 22:50:39.367  30016-30032/com.example.ibm_admin.chat e/json parser﹕ error parsing data org.json.jsonexception: end of input @ character 0 of 

that's means somewhere inside block in getjsonarray have null reference, comes topmost part of getjsonarray other exceptions suppressed, , is variable become null.

you have debug through code.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -