Json Parser data
I am creating JSONPARSE data for my android apps. I am using LogCat to view Json using Log.d ("id", id) but it showed an error when I want to set the textview to id. Please help, thanks. Below is the code I am using for java and php
Below is my code.
Log cat:
MainActivity.Java
private static String url_Retrieve = "http://hospital.leeyengyang.com/android_connect/Retrieve.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json2 = jsonParser.makeHttpRequest(url_Retrieve, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json2.toString());
try {
// Checking for SUCCESS TAG
int success2 = json2.getInt(TAG_SUCCESS);
if (success2 == 1) {
// products found
// Getting Array of Products
JSONArray Retrieve = json2.getJSONArray("tracking");
// looping through All Products
for (int i = 0; i < Retrieve.length(); i++) {
JSONObject c = Retrieve.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("Data");
String name = c.getString("Username");
Log.d("id", id);
Log.d("name", name);
// creating new HashMap
txtUpdate.setText(id);
// adding each child node to HashMap key => value
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Bluetooth.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
Retrive.php
<?php
// Locate WP Location
$location = $_SERVER['DOCUMENT_ROOT'];
include ($location . '/wp-config.php');
include ($location . '/wp-load.php');
include ($location . '/wp-includes/pluggable.php');
// array for JSON response
$response = array();
date_default_timezone_set('Asia/Kuala_Lumpur');
$date = date("Y-m-d");
$sql="SELECT Data,Username FROM tracking Where Username='jin' AND Date= '".$date."'";
// Initial Add data to HM
$result = mysql_query($sql) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["tracking"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$tracking = array();
$tracking["Data"] = $row["Data"];
$tracking["Username"] = $row["Username"];
// push single product into final response array
array_push($response["tracking"], $tracking);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
JsonParser.Java
package com.example.Leeyengyang;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is 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();
is = 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());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
source to share
To set int value in TextView use
txtUpdate.setText(""+id);
// OR
txtUpdate.setText(Integer.toString(id));
basically you need to convert the int value to String. It doesn't set the int value directly on the TextView.
Make sure you update the UI from the main thread only.
Hope this helps!
Thank.
source to share
You cannot change your UI outside of the UI thread (like a doInBackground()
method AsyncTask
).
Although you can still do this update in onPostExecute, which is called after background work has been done and executed on the main thread (UI).
Also consider using one of the libraries that can simplify the whole process, like Jake Wharton Retrofit: http://square.github.io/retrofit/
source to share