Batz Pogi Batz Pogi - 1 month ago 11
JSON Question

Android Studio get get Data from from Database to TextView

can I make the encoded json of my data not the format of this

{"tbl_accepted":[{"renterLat":"15.706376","renterLng":"121.065852"}]}


I only want to get is the values of the Lat and the Lng so I can display them in seperate textViews accordingly. And here is how I'm getting it.

private void getJSON(String url){
class GetJSON extends AsyncTask<String, Void, String>{
protected String doInBackground(String... params){
String uri = params[0];
BufferedReader bufferedReader = null;
try{

URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

String json;
while((json=bufferedReader.readLine()) != null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}

@Override
protected void onPostExecute(String s){
super.onPostExecute(s);
tvLat.setText(s);
Log.d(TAG,tvLat.getText().toString());
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}


PHP



<?php
include_once("connection.php");
$where = '';
if (isset($_GET['renter'])){
$where = " WHERE renter like '%".addslashes($_GET['renter'])."%'";
}
$sql = "SELECT renterLat, renterLng FROM tbl_accepted ".$where." ORDER BY acceptedID DESC";

$result = mysqli_query($conn, $sql);
$json = array();

if(mysqli_num_rows($result)){

while($row = mysqli_fetch_assoc($result)){

$json['tbl_accepted'][]=$row;
}
}

mysqli_close($conn);
echo json_encode($json);

?>


Thanks in advance sirs.

Answer

You're getting following string as a result in onPostExecute.

{"tbl_accepted":[{"renterLat":"15.706376","renterLng":"121.065852"}]}

Use JSONObject and JSONArray to convert the JSON String to Object.

To convert string to object your could would look something like this in onPostExecute.

@Override
        protected void onPostExecute(String s){
            super.onPostExecute(s);
            JSONObject latObj=new JSONObject(s);
            JSONArray tbl_accepted=latObj.getJSONArray('tbl_accepted');
            tvLat.setText(tbl_accepted.getJSONObject(0).getString('renterLat'));
            Log.d(TAG,tvLat.getText().toString());
        }
Comments