php - Error, my app stops each time it transfers data from the app to the database or vice versa -


here of code. error in logcat. in advance.

error: caused by: java.lang.nullpointerexception: attempt invoke virtual method 'java.lang.string.org.json.jsonobject.tostring()' on null object reference

login.java

public class login extends activity implements onclicklistener {  private edittext user, pass; private button msubmit, mregister;   private progressdialog pdialog;   jsonparser jsonparser = new jsonparser();     private static final string tag_success = "success"; private static final string tag_message = "message";  @override protected void oncreate(bundle savedinstancestate) {     // todo auto-generated method stub     super.oncreate(savedinstancestate);     setcontentview(r.layout.login);      // setup input fields     user = (edittext) findviewbyid(r.id.username);     pass = (edittext) findviewbyid(r.id.password);      // setup buttons     msubmit = (button) findviewbyid(r.id.login);     mregister = (button) findviewbyid(r.id.register);      // register listeners     msubmit.setonclicklistener(this);     mregister.setonclicklistener(this);  }  @override public void onclick(view v) {     int id = v.getid();     if (id == r.id.login) {         new attemptlogin().execute();     } else if (id == r.id.register) {         intent = new intent(this, register.class);         startactivity(i);     } else {     } }  class attemptlogin extends asynctask<string, string, string> {      boolean failure = false;      @override     protected void onpreexecute() {         super.onpreexecute();         pdialog = new progressdialog(login.this);         pdialog.setmessage("attempting login...");         pdialog.setindeterminate(false);         pdialog.setcancelable(true);         pdialog.show();     }      @override     protected string doinbackground(string... args) {          int success;         string username = user.gettext().tostring();         string password = pass.gettext().tostring();         try {              list<namevaluepair> params = new arraylist<namevaluepair>();             params.add(new basicnamevaluepair("username", username));             params.add(new basicnamevaluepair("password", password));              log.d("request!", "starting");              jsonobject json = jsonparser.makehttprequest(login_url, "post",                     params);               log.d("login attempt", json.tostring());               success = json.getint(tag_success);             if (success == 1) {                 log.d("login successful!", json.tostring());                  sharedpreferences sp = preferencemanager                         .getdefaultsharedpreferences(login.this);                 editor edit = sp.edit();                 edit.putstring("username", username);                 edit.commit();                  intent = new intent(login.this, readcomments.class);                 finish();                 startactivity(i);                 return json.getstring(tag_message);             } else {                 log.d("login failure!", json.getstring(tag_message));                 return json.getstring(tag_message);             }         } catch (jsonexception e) {             e.printstacktrace();         }          return null;      }      protected void onpostexecute(string file_url) {          pdialog.dismiss();         if (file_url != null) {             toast.maketext(login.this, file_url, toast.length_long).show();         }      }  } 

}

register.java

public class register extends activity implements onclicklistener{  private edittext user, pass; private button  mregister;   private progressdialog pdialog;   jsonparser jsonparser = new jsonparser();      private static final string tag_success = "success"; private static final string tag_message = "message";  @override protected void oncreate(bundle savedinstancestate) {      super.oncreate(savedinstancestate);     setcontentview(r.layout.register);      user = (edittext)findviewbyid(r.id.username);     pass = (edittext)findviewbyid(r.id.password);       mregister = (button)findviewbyid(r.id.register);     mregister.setonclicklistener(this);  }  @override public void onclick(view v) {               new createuser().execute();  }  class createuser extends asynctask<string, string, string> {       @override     protected void onpreexecute() {         super.onpreexecute();         pdialog = new progressdialog(register.this);         pdialog.setmessage("creating user...");         pdialog.setindeterminate(false);         pdialog.setcancelable(true);         pdialog.show();     }      @override     protected string doinbackground(string... args) {          int success;         string username = user.gettext().tostring();         string password = pass.gettext().tostring();         try {              list<namevaluepair> params = new arraylist<namevaluepair>();             params.add(new basicnamevaluepair("username", username));             params.add(new basicnamevaluepair("password", password));              log.d("request!", "starting");               jsonobject json = jsonparser.makehttprequest(                    register_url, "post", params);               log.d("registering attempt", json.tostring());               success = json.getint(tag_success);             if (success == 1) {                 log.d("user created!", json.tostring());                                 finish();                 return json.getstring(tag_message);             }else{                 log.d("registering failure!", json.getstring(tag_message));                 return json.getstring(tag_message);              }         } catch (jsonexception e) {             e.printstacktrace();         }          return null;      }      protected void onpostexecute(string file_url) {         // dismiss dialog once product deleted         pdialog.dismiss();         if (file_url != null){             toast.maketext(register.this, file_url, toast.length_long).show();         }      }  } 

}

jsonparser.java

public class jsonparser {  static inputstream = null; static jsonobject jobj = null; static string json = "";   public jsonparser() {  }   public jsonobject getjsonfromurl(final string url) {       try {          defaulthttpclient httpclient = new defaulthttpclient();         httppost httppost = new httppost(url);           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());         log.e("log_tag", "failed data was:\n" + json);     }       try {         jobj = new jsonobject(json);     } catch (jsonexception e) {         log.e("json parser", "error parsing data " + e.tostring());         log.e("log_tag", "failed data was:\n" + json);     }       return jobj;  }  public jsonobject makehttprequest(string url, string method,         list<namevaluepair> params) {       try {           if(method == "post"){              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();          }else if(method == "get"){              defaulthttpclient httpclient = new defaulthttpclient();             string paramstring = urlencodedutils.format(params, "utf-8");             url += "?" + paramstring;             httpget httpget = new httpget(url);              httpresponse httpresponse = httpclient.execute(httpget);             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());         log.e("log_tag", "failed data was:\n" + json);     }       try {         jobj = new jsonobject(json);     } catch (jsonexception e) {         log.e("json parser", "error parsing data " + e.tostring());         log.e("log_tag", "failed data was:\n" + json);     }       return jobj;  } 

}

login.php

<?php      require("config.inc.php");     if (!empty($_post)) {  $query = "          select              id,              username,              password         users                       username = :username      ";  $query_params = array(     ':username' => $_post['username'] );  try {     $stmt   = $db->prepare($query);     $result = $stmt->execute($query_params); } catch (pdoexception $ex) {      $response["success"] = 0;     $response["message"] = "database error1. please try again!";     die(json_encode($response));  }    $validated_info = false;   $row = $stmt->fetch(); if ($row) {       if ($_post['password'] === $row['password']) {         $login_ok = true;     } }   if ($login_ok) {     $response["success"] = 1;     $response["message"] = "login successful!";     die(json_encode($response)); } else {     $response["success"] = 0;     $response["message"] = "invalid credentials!";     die(json_encode($response));  }  } else {  ?>     <h1>login</h1>      <form action="login.php" method="post">          username:<br />          <input type="text" name="username" placeholder="username" />          <br /><br />          password:<br />          <input type="password" name="password" placeholder="password"      value="" />          <br /><br />          <input type="submit" value="login" />      </form>      <a href="register.php">register</a> <?php  }  ?>  

register.php

 require("config.inc.php");     if (!empty($_post)) {  if (empty($_post['username']) || empty($_post['password'])) {        $response["success"] = 0;     $response["message"] = "please enter both username , password.";       die(json_encode($response)); }    $query        = " select 1 users username = :user";  $query_params = array(     ':user' => $_post['username'] );   try {      $stmt   = $db->prepare($query);     $result = $stmt->execute($query_params); } catch (pdoexception $ex) {        $response["success"] = 0;     $response["message"] = "database error1. please try again!";     die(json_encode($response)); }   $row = $stmt->fetch(); if ($row) {      $response["success"] = 0;     $response["message"] = "i'm sorry, username in use";     die(json_encode($response)); }   $query = "insert users ( username, password ) values ( :user, :pass ) ";   $query_params = array(     ':user' => $_post['username'],     ':pass' => $_post['password'] );   try {     $stmt   = $db->prepare($query);     $result = $stmt->execute($query_params); } catch (pdoexception $ex) {      $response["success"] = 0;     $response["message"] = "database error2. please try again!";     die(json_encode($response)); }   $response["success"] = 1; $response["message"] = "username added!"; echo json_encode($response);     } else { ?> <h1>register</h1>  <form action="register.php" method="post">      username:<br />      <input type="text" name="username" value="" />      <br /><br />      password:<br />      <input type="password" name="password" value="" />      <br /><br />      <input type="submit" value="register new user" />   </form>   <?php    }     ?> 


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -