Android using JSON to register and get results from web service - PHP -


i made android application last year, worked fine, i've been reassigned develop application.

but registration of user has stopped working. reason why, havnt clue.

here start screen, activity user registers:

public class prompt extends activity {      public edittext u, p, e;     public string username, password, emailadd;     public button createclient;     final context context = this;     public textview registererrormsg;      // json response node names     private static string key_success = "success";     @suppresswarnings("unused")     private static string key_error = "error";     @suppresswarnings("unused")     private static string key_error_msg = "error_msg";     private static string key_uid = "uid";     private static string key_name = "name";     private static string key_email = "email";     private static string key_created_at = "created_at";      @override     public void onconfigurationchanged(configuration newconfig) {         super.onconfigurationchanged(newconfig);         setrequestedorientation(activityinfo.screen_orientation_portrait);     }      @override     public void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.prompt);         // importing assets buttons, text fields          u = (edittext) findviewbyid(r.id.username);         p = (edittext) findviewbyid(r.id.password);         e = (edittext) findviewbyid(r.id.emailaddress);         createclient = (button) findviewbyid(r.id.createclient);         registererrormsg = (textview) findviewbyid(r.id.register_error);         u.settext("usernametest");         p.settext("passwordtest");         e.settext("test@gmail.com");          //toast.maketext(getapplicationcontext(), "...", toast.length_long).show();          createclient.setonclicklistener(new view.onclicklistener() {             public void onclick(view view) {                 username = u.gettext().tostring();                 password = p.gettext().tostring();                 emailadd = e.gettext().tostring();                 userfunctions userfunction = new userfunctions();                  //toast.maketext(getapplicationcontext(), username+" "+password+" "+emailadd, toast.length_long).show();                  //now have text input, validate them                 if(username.length() < 5 || password.length() < 5 || emailadd.length() < 5){                     //minimum input each field > 5 characters                     registererrormsg.settext("username, password , email must have must 5 characters");                 }                 else{                     //if validated correctly upload                     jsonobject json = userfunction.registeruser(username, emailadd, password);                     log.e("json result", "json result: " + json);                      //successfully make check file , redirect homepage                     try {                             string file_name = "filename.txt";                             fileoutputstream fos = openfileoutput(file_name, context.mode_world_readable);                             try{                                 fos.write(username.getbytes());                             }catch (ioexception e){                                 e.printstacktrace();                             }                             fos.close();                              //if complete, redirect home page                             intent intent2 = new intent(prompt.this, strategicenergyactivity.class);                             intent2.addflags(intent.flag_activity_clear_top);                             startactivity(intent2);                             finish();                     }                      catch (filenotfoundexception e) {                         e.printstacktrace();                     }                      catch (ioexception e) {                         e.printstacktrace();                     }                 }             }         });     } } 

here json parser class handle json returned web service:

public class jsonparser {      static inputstream = null;     static jsonobject jobj = null;     static string json = "";      // constructor     public jsonparser() {     }      public jsonobject getjsonfromurl(string url, list<namevaluepair> params) {          log.e("testttt", " " + params.get(0) + " " + params.get(1) + " " + params.get(2)  + " " + params.get(3));         // making http request         try {             httpclient httpclient = new defaulthttpclient();             httppost httppost = new httppost(url);             httppost.setheader("content-type", "application/x-www-form-urlencoded");             httppost.setentity(new urlencodedformentity(params, "utf-8"));              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);             }             is.close();             json = sb.tostring();             log.e("json", json);         }          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;     } } 

here user functions class, class data handling/ method calling:

public class userfunctions {      private jsonparser jsonparser;      private static string registerurl = "http://www.website.com/api/index.php?";     private static string register_tag = "register";      // constructor     public userfunctions(){         jsonparser = new jsonparser();     }      /**      * function make login request      * @param name      * @param email      * @param password      * */     public jsonobject registeruser(string name, string email, string password){         // building parameters         list<namevaluepair> params = new arraylist<namevaluepair>();         params.add(new basicnamevaluepair("tag", register_tag));         params.add(new basicnamevaluepair("name", name));         params.add(new basicnamevaluepair("email", email));         params.add(new basicnamevaluepair("password", password));          log.e("credentials", "username: " + name + "\nemail: " + email + "\npassword: " + password);         //toast.maketext(getparent(), name+" "+email+" "+password, toast.length_long).show();          jsonobject json = jsonparser.getjsonfromurl(registerurl, params);         return json;     } } 

here code on web service:

<?php     print_r($_post);     $tag = "register";      // include db handler     require_once 'include/db_functions.php';     $db = new db_functions();      // response array     $response = array("tag" => $tag, "success" => 0, "error" => 0);      // check tag type     if ($tag == 'register') {         // request type register new user         $name = $_post['name'];         $email = $_post['email'];         $password = $_post['password'];          // check if user existed         if($db->isuserexisted($email)){             // user exists - error response             $response["error"] = 2;             $response["error_msg"] = "user exists";             echo json_encode($response). "user exists";         }          else{                    // store user             $user = $db->storeuser($name, $email, $password);              if($user){                 // user stored                 $response["success"] = 1;                 $response["uid"] = $user["unique_id"];                 $response["user"]["name"] = $user["name"];                 $response["user"]["email"] = $user["email"];                 $response["user"]["created_at"] = $user["created_at"];                 $response["user"]["updated_at"] = $user["updated_at"];                 echo json_encode($response). "user stored successfully";             }              else{                 // user failed store                 $response["error"] = 1;                 $response["error_msg"] = "error occured in registration";                 echo json_encode($response);             }         }     }      else{         echo "invalid request";     } ?> 

finally error being thrown @ me, occurs in sb.append(line) line in jsonparser class:

05-21 16:35:46.304: e/buffer error(4278): error converting result java.lang.nullpointerexception 05-21 16:35:46.308: e/json parser(4278): error parsing data org.json.jsonexception: end of input @ character 0 of  05-21 16:35:46.308: e/json result(4278): json result: null 

can spot i'm doing wrong here? appreciate ever.

thanks in advance!

the error you're getting occurs when try parse json nothing in it. example, you'd see similar response if phone no connected internet , tried connect server. there'd no data parse , and you'd jsonexception.

my guess related you're i/o functions not being on background thread. based on code provided running httppost within jsonparser class on main ui thread. has been disallowed since api 11. result no value parse , throw jsonexception.

try moving function asynctask. if execute httppost within task's doinbackground method remove error. here link android docs related asynctask. provide helpful code examples.

the basic structure of asynctask follows:

private class downloadfilestask extends asynctask<url, void, long> {      protected long doinbackground(url... urls) {         //stuff in background          return result;      }       protected void onpostexecute(long result) {         //stuff runs on ui thread using result of background thread       }  } 

in example, taken android docs, can see number of key parameters. (1) arguments/return values task indicated in < > (2) doinbackground method which, shocker, runs on background thread (3) onpostexecute method runs on ui thread following completion of doinbackground method. onpostexecute takes argument value returned doinbackground. if notice, type of argument corresponds third type in < > @ start of class.

you're going have play around fits in code basic idea that, i/o function - httppost takes place on background thread. ui updates, changing text in textview, using toast or moving things on screen takes place in onpostexecute. in other words, download need in doinbackground , return result - in case json/string - onpostexecute can notify user of change, e.g. registered or not.

how pass values asynctask

you asked question in comment how pass url asynctask. passing of values asynctask occurs execute() method used start task. asynctask because own class requires create instance of task first

downloadfilestask t = new downloadfilestask(); 

once create instance of task use execute() method start task. there pass in values want task recieve in doinbackgroundmethod.

t.execute(myurl); 

to pass more tha 1 value add them in seperate commas

t.execute(myurl1, myurl2, myurl3); 

to retrieve values passed in access them within doinbackground method. asynctask takes arguments called varargs. these basiclly lists of values of specific type. in case, urls. access them values index.

url first = urls[0]  

for examples, refers first url value passed asynctask. name use retrieve corresponds name after . . . provide arguments doinbackground method. example if passed 1 url asynctask , wanted retrieve later getwhatever method use

getwhatever(urls[0]); 

if there's more 1 url , iteratvie process use loop or other method of going through urls provided


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -