How to getting multiple tables in json from sql to android - java

i try to get multiple table from json, i have two tables ( hotline and other ) , i can get data from hotline table, but cannot get from other table
in my php (json):
{"hotline":[{"id":"2","name_hotline":"Tourist Police","phone_hotline":"192"},{"id":"6","name_hotline":"Water","phone_hotline":"1199"}]}{"other":[{"id":"1","name_other":"Lao National Tourism Administration","phone_other":"+85621212248 ","latitude_other":"0","pic_other":"","longtitude_other":"0"},{"id":"2","name_other":"Tourism Police Department","phone_other":"+85621251128 ","latitude_other":"0","pic_other":"","longtitude_other":"0"}]}
MainActivity.java :
InputStream objInputStream = null;
String strJSON = "";
try {
HttpClient objHttpClient = new DefaultHttpClient();
HttpPost objHttpPost = new HttpPost("http://192.168.1.102/emergencycall/php_get_data.php");
HttpResponse objHttpResponse = objHttpClient.execute(objHttpPost);
HttpEntity objHttpEntity = objHttpResponse.getEntity();
objInputStream = objHttpEntity.getContent();
Log.d("Emergency", "Connected HTTP Success !");
} catch (Exception e) {
Log.d("Emergency", "Error Connect to : " + e.toString());
}
try {
BufferedReader objBufferesReader = new BufferedReader(new InputStreamReader(objInputStream, "UTF-8"));
StringBuilder objStrBuilder = new StringBuilder();
String strLine = null;
while ((strLine = objBufferesReader.readLine()) != null) {
objStrBuilder.append(strLine);
}
objInputStream.close();
strJSON = objStrBuilder.toString();
Log.d("Emergency", "Connected JSON Success !");
} catch (Exception e) {
Log.d("Emergency","Error Convert To JSON :" + e.toString() );
}
try {
JSONObject object = new JSONObject(strJSON);
JSONArray objJSONArray = object.getJSONArray("hotline");
JSONArray objJSONAraay2 = object.getJSONArray("other");
for (int i = 0; i < objJSONArray.length(); i++) {
JSONObject objJSONObject = objJSONArray.getJSONObject(i);
strNameHotlineMySQL = objJSONObject.getString("name_hotline");
strPhoneHotlineMySQL = objJSONObject.getString("phone_hotline");
}
for (int j = 0; j < objJSONAraay2.length(); j++) {
JSONObject objJSONObject1 = objJSONAraay2.getJSONObject(j);
strNameHospitalMySQL = objJSONObject1.getString("name_other");
strPhoneHospitalMySQL = objJSONObject1.getString("phone_other");
long insertID4 = objHotlineTable.addDataFromSQLiteHospital(strNameHospitalMySQL, strPhoneHospitalMySQL, strPicHospitalMySQL);
}
} catch (Exception e) {
Log.d("Emergency","Error syncdata to SQLite :" + e.toString() );
}
and i get an error in Logcat:
: Error syncdata to SQLite :org.json.JSONException: No value for other

Your json data format is not correct. Json data format should be like this:
{
"hotline":[
{
"id":"2",
"name_hotline":"Tourist Police",
"phone_hotline":"192"
},
{
"id":"6",
"name_hotline":"Water",
"phone_hotline":"1199"
}
],
"other":[
{
"id":"1",
"name_other":"Lao National Tourism Administration",
"phone_other":"+85621212248 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
},
{
"id":"2",
"name_other":"Tourism Police Department",
"phone_other":"+85621251128 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
}
]
}
And than,
You can use "Retrofit" and "gson" for http request and object mapping.

Related

how do I extract the JSON value?

I am getting and error response from server in android studio. how do I extract the values.
Json:
{
"error": {
"phone": [
"The phone field is required."
]
}
}
Code:
try {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject mJsonObject = arr.getJSONObject(i);
Log.d("OutPut", mJsonObject.getString("phone"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Actually your response is an object not an array. Try below:
String response = "{\"error\":{\"phone\":[\"The phone field is required.\"]}}";
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject errorObject = jsonObject.optJSONObject("error");
JSONArray phoneArray = errorObject.getJSONArray("phone");
for (int i = 0; i < phoneArray.length(); i++) {
String errorString = phoneArray.optString(i);
Log.d("OutPut", errorString);
}
} catch (JSONException e) {
e.printStackTrace();
}

How to use JSON to get value?

Log.d("Hot Text:", response.toString());
try {
JSONArray array = response.getJSONArray("rows");
JSONObject jsonObject = array.getJSONObject(0);
JSONArray a = jsonObject.getJSONArray("elements");
JSONObject js = a.getJSONObject(0);
JSONObject b = js.getJSONObject("distance");
value = b.getString("value");
Log.d("TAG", "title:" + value);
} catch (JSONException e) {
e.printStackTrace();
}
}
how to get "value" to storage for other space? thank u
You can do like this:
String text;
int value;
try {
JSONObject jsonObject = new JSONObject(body);
JSONArray rowArray = jsonObject.optJSONArray("rows");
if(rowArray.length() > 0){
JSONObject row = rowArray.optJSONObject(0);
JSONArray elementArray = row.optJSONArray("elements");
if(elementArray.length() > 0){
JSONObject element = elementArray.optJSONObject(0);
JSONObject distance = element.optJSONObject("distance");
text = distance.optString("text");
value = distance.optInt("value");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("text", text);
Log.e("value", "value : " + value);

how to access jsonarray elemennts

#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
try {
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output3;
}
//The string which is being passed from getVersion comprises of
[{"ipaddress":"10.253.140.116","password":"c0mcast!","username":"bwadmin"},{"ipaddress":"10.253.140.117","password":"bwadmin!","username":"bwadmin"}]
//My requirement is to access the value of ipaddress and password and username and store items in an array and send them to ConnectionStatus.
JSONArray jsonArr = new JSONArray(getVersionJson);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//Now you can fetch values from each JSON Object
}
JSONObject class represents just one JSON. This is generally inside braces { and }.
If the expected input getVersionJson is just one JSON object, your code works.
However, you are getting an array of JSON objects in the input string getVersionJson, so you need to use JSONArray class to handle an array of JSON Objects.
This is generally [ { }, { }, { }, ... ]
JSONArray extends List, so it can be iterated to read each JSONObject value.
Here is documentation for reference: Interface JsonArray.

How to code distance in java android use place_id from autocompleteText

please help, i have some code to show a distance. before i use static code for get lat and long. but i need to get lat and long from user..need help how i can get this latitude and longitude from place_id /.
public void setDirectionMap()
ArrayList list = MainActivity.arrJsonTargetLocation;
JSONObject startLocation = MainActivity.jsonStartLocation;
ArrayList targetLocation = MainActivity.arrJsonTargetLocation;
if( list != null )
{
JSONObject targetLocationList = (JSONObject) list.get(list.size() - 1);
}
LatLng start_point = new LatLng(Double.parseDouble(startLocation.getString(``lat``)),
double.parseDouble(startLocation.getString(``lng``)));
LatLng target_point = new LatLng(Double.parseDouble(targetLocation.indexOf(``lat``)),
double.parseDouble(targetLocation.indexOf(``lng``)));
GoDelivery.geoPoints = new ArrayList<LatLng>();
Log.i(TAG, ``#FROM: `` + start_point.toString() + `` -- #TO : `` + target_point.toString());
System.out.println(``=======================ORDER==================================``);
System.out.println(``#FROM: `` + start_point.toString() + `` -- #TO : `` + target_point.toString());
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
StringBuilder jsonResultsDetail = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(DIRECTION_API_BASE + OUT_JSON);
//sb.append(``&components=country:gr``);
sb.append(``?key=`` + API_KEY);
sb.append(``&origin=`` +
start_point.latitude + ``,`` +
start_point.longitude +
``&destination=`` +
target_point.latitude + ``,`` +
target_point.longitude +
``&avoid=tolls``);
Log.i(TAG, ``Query String: `` + sb.toString());
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
//Log.i(TAG,``===============DIRECTIONS===============``);
//Log.i(TAG,jsonResults.toString());
if (conn != null) {
conn.disconnect();
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, ``MalformedURL ``, e);
} catch (IOException e) {
Log.e(LOG_TAG, ``IOException ``, e);
} catch () {
Log.e(LOG_TAG, ``Throwable``, e);
}
try {
// double place_id = JSONArray.getDouble(``latitude``);
//double place_id = JSONArray.getDouble(``longitude``);
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONObject jsonLeg = jsonObj.getJSONArray(``routes``).getJSONObject(0).getJSONArray(``legs``).getJSONObject(0);
JSONObject jsonSumDistance = jsonLeg.getJSONObject(``distance``);
JSONObject jsonSumDuration = jsonLeg.getJSONObject(``duration``);
JSONArray jsonSteps = jsonLeg.getJSONArray(``steps``);
JSONObject jsonObjlat = new JSONObject().getJSONObject(``lat``);
JSONObject jsonObjlng = new JSONObject().getJSONObject(``lng``);
Don't worry dude , It is not that to tough
Just pass your place id and your key in this url
This url will return json containing all the info of the place.
once you got json then you need to parse the json string to get the lat and lang .

Parsing a flat JSON array with no indice

I am scratching my head to figure out how to parse the following JSON object.
[
{
"result": true,
"response": "Successfully got list of users in radius of 10km"
},
{
"username": "elize",
"photo": "http://www.embedonix.com/apps/mhealth/images/elize/elize.png"
},
{
"username": "mario",
"photo": "http://www.embedonix.com/apps/mhealth/images/mario/mario.png"
}
]
This is I guess a single index json array. The first part tells that the operation of building the json object was ok.
Then there are pairs of username and photo which I have to parse them and put them in a list:
public class User {
private String mName;
private String mPhotoURl;
public User(String name, String url)
{
///
}
}
So if the first entry of json is result -> true I should have a ArrayList<User>.
I tried to do the following but it always raises the JSONParse exception:
try {
JSONObject json = new JSONObject(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONArray obj = json.getJSONArray(String.valueOf(i));
Log.i(TAG, i + " username: " + obj.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Just try this way
try {
JSONArray jsonArray = new JSONArray(data);
int length = jsonArray.length();
for (int i = 1; i < length; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this way,hope this will help you to solve your problem.
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
if(i==0){
Log.i(TAG, i + " result: " + obj.getString("result"));
Log.i(TAG, i + " response: " + obj.getString("response"));
}else{
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try Code...something like this..
try {
JSONArray json = new JSONArray(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONObject childObject = json.getJSONObject(i);
if(i==0){
String result = child.getBoolean("result");
String resp = child.getString("response");
} else {
String username = child.getString("username");
String photo = child.getString("photo");
Log.i(TAG, i + " username: " + username);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories