0

My app is a simple tacking system where the every users location is updated onto the server and when called for help it is to send back Mobile numbers of all the people within a given range(approx). The app works perfectly updating the location periodically to the server and uses an approximate method to find people within a certain range the problem im facing now is to send the queried list of numbers back to the device. I have tried a few tutorials but with no luck the app keeps crashing. Here is my code where i send data along with the php code. If anyone to help me figure out how to receive the numbers back from the 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 is -\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();
            is = 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();
            is = 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 INTO 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 FROM app_backup WHERE Lat_diff <= 30 AND Long_diff <=30 AND Long_diff <> 0 AND Lat_diff <> 0 AND Long_diff >= -30 AND 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 you in Advance.

Edit: The block of code after which the 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; i < jarray.length(); i++)
    {
        json_data = jarray.getJSONObject(i);
    }}
catch(JSONException e){
    Log.e("error parsing data", "Log_tag");
    e.printStackTrace();}

after adding these two blocks the logcat said 'shutting down VM' and the app crashed. Im not quite sure if my approach is correct on the retrieving side.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
user22845
  • 11
  • 3

1 Answers1

0

To send data to your app in JSON, you have to send headers and at the end send the JSON with json_encode. Another pitfall is the encoding of the PHP file (have to be UTF-8 without BOM), else it corrupt the 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 to do the job, there is the light library Simple JSON for PHP It makes you able to "forge" your JSON as you please and send it (headers included) in a single command.

In your case it would be like :

// At the beginning
$Json = new json();

// Add the data
while ( $row = mysql_fetch_array($query, MYSQL_ASSOC) ) {
  $Json->addContent(new arrayJson("data",$row));
}
$Json->addContent(new propertyJson('message', 'Success'));

// At the end, send the json
json_send($Json)

In the JAVA part :

To get the JSON, you should make a method like 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);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And you should use Google GSON to convert the JSON to a Data Java object, as found at 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 and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the 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 it helps

Alexis Paques
  • 1,885
  • 15
  • 29