php - Retrieving data back from my database android? -


my app simple tacking system every users location updated onto server , when called send mobile numbers of people within given range(approx). app works updating location periodically server , uses approximate method find people within range problem im facing send queried list of numbers device. have tried few tutorials no luck app keeps crashing. here code send data along php code. if me figure out how receive numbers server.

private void serverconnection() {     // todo auto-generated method stub       gpstracker gps1 = new gpstracker(mainactivity.this);     double latitude = gps1.getlatitude();     double longitude = gps1.getlongtitude();     toast.maketext(getapplicationcontext(),"your location -\nlat:"+latitude+"\nlon:"+longitude,toast.length_long).show();     string lat = string.valueof(latitude);     string log = string.valueof(longitude);      string svdnum;      registrationactivity gsm = new registrationactivity();     sharedpreferences shareddata = getsharedpreferences(gsm.filename,0);     svdnum = shareddata.getstring("mobile number", "no number registered");       list<namevaluepair>  namevaluepairs = new arraylist<namevaluepair>(1);      namevaluepairs.add(new basicnamevaluepair("lat",lat));     namevaluepairs.add(new basicnamevaluepair("long",log));     namevaluepairs.add(new basicnamevaluepair("number",svdnum));      try{         if(distress == 0){             httpclient httpclient = new defaulthttpclient();             httppost httppost = new httppost("http://10.0.2.2/tech/serverconnection.php");             httppost.setentity(new urlencodedformentity(namevaluepairs));             httpresponse response = httpclient.execute(httppost);             httpentity entity = response.getentity();             = entity.getcontent();         }else{             httpclient httpclient = new defaulthttpclient();             httppost httppost = new httppost("http://10.0.2.2/tech/serverconnection2.php");             httppost.setentity(new urlencodedformentity(namevaluepairs));             httpresponse response = httpclient.execute(httppost);             httpentity entity = response.getentity();             = entity.getcontent();          }     }     catch(clientprotocolexception e){         log.e("clientprotocol", "log_tag");         e.printstacktrace();     }     catch(ioexception e){         log.e("log_tag", "ioexception");         e.printstacktrace();     } 

the php code

<?php $conn = mysql_connect(localhost, 'root', ''); mysql_select_db('finalyearproject'); if(! $conn ) {   die('could not connect: ' . mysql_error()); }  $number=$_post['number']; $latitudes=$_post['lat']; $longitudes=$_post['long'];  $latitude = floatval($latitudes); $longitude = floatval($longitudes);  $sql = "insert app_backup(number,latitude, longitude) values('$number', '$latitude', '$longitude') on duplicate key update latitude=values(latitude), longitude=values(longitude)";   $sql = "update app_backup set lat_diff=latitude-$latitude ,long_diff=longitude-$longitude";  $query= mysql_query("select number app_backup lat_diff <= 30 , long_diff <=30 , long_diff <> 0 , lat_diff <> 0 , long_diff >= -30 , lat_diff >= -30");    $column = array();  while ( $row = mysql_fetch_array($query, mysql_assoc) ) {   $column[] = $row['number']; }  echo json_encode(column);   $retval = mysql_query( $sql, $conn ); if(! $retval ) {   die('could not enter data: ' . mysql_error()); } echo "entered data successfully\n"; mysql_close($conn);  ?> 

thank in advance.

edit: block of code after app kept crashing

httpentity entity2 = response.getentity();                 inputstream nums = entity2.getcontent();                 try{                 bufferedreader reader = new bufferedreader(new inputstreamreader(nums,"iso-8859-1") );                 stringbuilder sb = new stringbuilder();                 string line = null;                 while ((line = reader.readline()) != null){                     sb.append(line + "\n");                      }             nums.close();             res = sb.tostring();              }             catch(ioexception e){                 log.e("log_tag", "ioexception");                 e.printstacktrace();             } 

json loop

try{     jsonarray jarray = new jsonarray(res);      jsonobject json_data = null;     for(int i=0; < jarray.length(); i++)     {         json_data = jarray.getjsonobject(i);     }} catch(jsonexception e){     log.e("error parsing data", "log_tag");     e.printstacktrace();} 

after adding these 2 blocks logcat said 'shutting down vm' , app crashed. im not quite sure if approach correct on retrieving side.

to send data app in json, have send headers , @ end send json json_encode. pitfall encoding of php file (have utf-8 without bom), else corrupt json.

header('cache-control: no-cache, must-revalidate'); header('expires: mon, 26 jul 1997 05:00:00 gmt'); header('content-type: application/json');//*/ echo json_encode(column); 

but job, there light library simple json php makes able "forge" json please , send (headers included) in single command.

in case :

// @ beginning $json = new json();  // add data while ( $row = mysql_fetch_array($query, mysql_assoc) ) {   $json->addcontent(new arrayjson("data",$row)); } $json->addcontent(new propertyjson('message', 'success'));  // @ end, send json json_send($json) 

in java part :

to json, should make method here

public string getjson(string url, int timeout) {     httpurlconnection c = null;     try {         url u = new url(url);         c = (httpurlconnection) u.openconnection();         c.setrequestmethod("get");         c.setrequestproperty("content-length", "0");         c.setusecaches(false);         c.setallowuserinteraction(false);         c.setconnecttimeout(timeout);         c.setreadtimeout(timeout);         c.connect();         int status = c.getresponsecode();          switch (status) {             case 200:             case 201:                 bufferedreader br = new bufferedreader(new inputstreamreader(c.getinputstream()));                 stringbuilder sb = new stringbuilder();                 string line;                 while ((line = br.readline()) != null) {                     sb.append(line+"\n");                 }                 br.close();                 return sb.tostring();         }      } catch (malformedurlexception ex) {         logger.getlogger(getclass().getname()).log(level.severe, null, ex);     } catch (ioexception ex) {         logger.getlogger(getclass().getname()).log(level.severe, null, ex);     } {        if (c != null) {           try {               c.disconnect();           } catch (exception ex) {              logger.getlogger(getclass().getname()).log(level.severe, null, ex);           }        }     }     return null; } 

and should use google gson convert json data java object, found @ stackoverflow.

import java.util.list; import com.google.gson.gson;  public class test {      public static void main(string... args) throws exception {         string json =              "{"                 + "'title': 'computing , information systems',"                 + "'id' : 1,"                 + "'children' : 'true',"                 + "'groups' : [{"                     + "'title' : 'level 1 cis',"                     + "'id' : 2,"                     + "'children' : 'true',"                     + "'groups' : [{"                         + "'title' : 'intro computing , internet',"                         + "'id' : 3,"                         + "'children': 'false',"                         + "'groups':[]"                     + "}]"                  + "}]"             + "}";          // magic.         data data = new gson().fromjson(json, data.class);          // show it.         system.out.println(data);     }  }  class data {     private string title;     private long id;     private boolean children;     private list<data> groups;      public string gettitle() { return title; }     public long getid() { return id; }     public boolean getchildren() { return children; }     public list<data> getgroups() { return groups; }      public void settitle(string title) { this.title = title; }     public void setid(long id) { this.id = id; }     public void setchildren(boolean children) { this.children = children; }     public void setgroups(list<data> groups) { this.groups = groups; }      public string tostring() {         return string.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);     } } 

hope helps


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -