JSON Get Value by Edittext - android

I'm trying to get JSON value by EditText.
At first I had a bunch of nullpointer exceptions, solved that. But now my function just isn't working. Been wrapping my brain over this...
I tried to create a EditText, get that value to a String, and get it over to the JSON Object. Don't know what I'm doing wrong... Or am I forgetting something?
public class MyActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
EditText edt;
Button Btngetdata;
//URL to get JSON Array
private static String url = "*";
//JSON Node Names
private static final String TAG_TAG = "tag";
private static final String TAG_ID = "id";
private static final String TAG_LAST_NAME = "last_name";
private static final String TAG_EMAIL = "country";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Btngetdata = (Button)findViewById(R.id.getdata);
edt = (EditText)findViewById(R.id.edittext);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_TAG);
JSONObject c = user.getJSONObject(0);
String xyz = edt.getText().toString();
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
edt.setText(xyz);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
{"tag":[{"id":"1","first_name":"Philip","last_name":"Porter","email":"pporter0#admin.ch","country":"China","ip_address":"26.83.255.206"},{"id":"2","first_name":"Nancy","last_name":"Martin","email":"nmartin1#google.ca","country":"Colombia","ip_address":"160.93.80.1"},{"id":"3","first_name":"Ann","last_name":"Peterson","email":"apeterson2#utexas.edu","country":"China","ip_address":"251.254.74.162"},{"id":"4","first_name":"Rachel","last_name":"Clark","email":"rclark3#mayoclinic.com","country":"Brazil","ip_address":"58.218.248.5"},{"id":"5","first_name":"Heather","last_name":"Burton","email":"hburton4#creativecommons.org","country":"Ethiopia","ip_address":"244.69.119.16"},{"id":"6","first_name":"Ruth","last_name":"Lane","email":"rlane5#va.gov","country":"Brazil","ip_address":"18.173.102.54"},{"id":"7","first_name":"Andrew","last_name":"Turner","email":"aturner6#devhub.com","country":"United States","ip_address":"13.119.240.234"},{"id":"8","first_name":"Wanda","last_name":"Medina","email":"wmedina7#pagesperso-orange.fr","country":"Netherlands","ip_address":"151.139.21.237"},{"id":"9","first_name":"Robert","last_name":"Elliott","email":"relliott8#joomla.org","country":"United States","ip_address":"34.200.249.109"},{"id":"10","first_name":"Kevin","last_name":"Harrison","email":"kharrison9#nih.gov","country":"Brazil","ip_address":"106.84.164.86"}]}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
}
EDIT
JSONObject c = user.getJSONObject(Integer.parseInt(xyz));
I Modified to this, im getting a response other than default 1 when base value was getJSONObject(0), but now im entering 1 and im getting 2, entering 4 getting 5..
Does anyone know how to solve this one?

If you are trying to parse the whole json array then use this.In you post execute
List<String> allid = new ArrayList<String>();
JSONArray obj= jsonResponse.getJSONArray("tag");
for (int i=0; i<obj.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String id= actor.getString("id");
allNames.add(id);
}
Then you can use a for loop to get the id in the list accordingly.
Otherwise you can do this parsing Using the Gson Library(you can download Gson library here
Just create a class in your package
public class DetailArray {
public boolean status;
public List<Detail_User> details;
public class Detail_User {
public String id;
public String first_name;
public String last_name;
public String email;
public String country;
}
}
In your post execute
Where response is the json response
DetailArray detail1 = (new Gson()).fromJson(response.toString(),
DetailArray.class);
Now Suppose , if you want to set the names in a list view then
//return a arraylist
private ArrayList<String> getName(DetailArray detail) {
ArrayList name = new ArrayList<String>();
for (int i=0;i< detail.details.size();i++) {
name.add(splitStr[i]);
}
return names;
}
Setting the array adapter and setting it to a list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
getName(detail);
listview.setAdapter(arrayAdapter);

For a particular position try like this
int positionToShow = Integer.parseInt(edt.getText().toString()) - 1;
user = json.getJSONArray(TAG_TAG);
for(int i = 0; i < user.length(); i++) {
if(positionToShow == i) {
JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
uid.setText(id);
name1.setText(name);
email1.setText(email);
}
}

i've parse your json ...acc to number entered ..and it shows exact result....refer this....
final EditText no=(EditText)findViewById(R.id.editText1);
final Button click=(Button)findViewById(R.id.button1);
click.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
Toast.makeText(MainActivity.this, no.getText().toString(), 0).show();
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet("http://192.168.0.30/test.js");
HttpResponse response=client.execute(request);
HttpEntity entity=response.getEntity();
String json=EntityUtils.toString(entity);
JSONObject j1=new JSONObject(json);
JSONArray ja1=j1.getJSONArray("tag");
JSONObject j2=ja1.getJSONObject(Integer.parseInt(no.getText().toString())-1);
Toast.makeText(MainActivity.this, j2.getString("first_name").toString() , 0).show();
entity.consumeContent();
}
catch(Exception e)
{
e.getStackTrace();
Toast.makeText(MainActivity.this, e.toString() , 0).show();
}
}
});

Related

Android Json unicode parsin

my sql server collation is utf8 unicode
my php works fine
my android project is working fine with normal characters but in case of arabic char it display error "Error parsing json" line 233 in the activity listed below
I've tried my sql and php on other project its works but here I dont know whats the error json must be utf8 by defult
public class DealsListActivity extends Activity {
private String id;
// Progress Dialog
private ProgressDialog pDialog;
// creating JSON Parser object
JSONParser jParser = new JSONParser();
private static String url = "http://xxxxxxxxxxxx.get_all_deals_by_id.php";
// JSON Node names
private static final String TAG_DEALS = "deals";
private static final String TAG_ID = "id";
private static final String TAG_DEALNAME = "dealName";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_RESTID = "restID";
private static final String TAG_RESTNAME = "restName";
private static final String TAG_RESTTYPE = "restType";
private static final String TAG_LAT = "restLat";
private static final String TAG_LNG = "restLng";
private static final String TAG_SUCCESS = "success";
private JSONObject json;
JSONArray restaurantDealsData = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> restaurantDealsList = new ArrayList<HashMap<String, String>>();
ListView myList;
private String[] dealID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deals_list);
id = getIntent().getStringExtra("id");
myList = (ListView) findViewById(R.id. restDealListView);
new LoadDeals().execute();
}
/**
* Background Async Task to Load all deals by making
* HTTP Request
* */
class LoadDeals extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DealsListActivity.this);
pDialog.setMessage("Loading Restaurant Deals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.v("id", id);
params.add(new BasicNameValuePair("id", id));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
// check log cat for JSON string from URL
Log.v("restaurantDealsJSON: ", json.toString());
// return json as string to using in the user interface
return json.toString();
}
#Override
protected void onPostExecute(final String jsonStr) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into listview
* */
try {
json = new JSONObject(jsonStr);
} catch (JSONException e1) {
// print error message to log
e1.printStackTrace();
error("There are no Deals");
}
try {
// Checking for SUCCES TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// restaurant found
// Getting Array of restaurant
restaurantDealsData = json.getJSONArray(TAG_DEALS);
displayDeals(restaurantDealsData.toString());
} else {
error("There is no Deals available!");
}
} catch (JSONException e) {
error("There has been an error please try again!");
e.printStackTrace();
}
}
});
}
}
public void error(String error) {
// Log.v("ERROR", "2");
AlertDialog.Builder builder = new AlertDialog.Builder(
DealsListActivity.this);
// Log.v("ERROR", "3");
builder.setTitle("Error");
builder.setMessage(error);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Log.v("TEST", "1");
Intent i = new Intent(getApplicationContext(),
TabsViewPagerFragmentActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void displayDeals(String result) {
JSONArray restaurantDealsData = null;
try {
restaurantDealsList.clear();
restaurantDealsData = new JSONArray(result);
dealID = new String[restaurantDealsData.length()];
// looping through all technical data
for (int i = 0; i < restaurantDealsData.length(); i++) {
JSONObject td = restaurantDealsData.getJSONObject(i);
// Storing each json item in variable
String id = td.getString(TAG_ID);
dealID[i] = id;
String name = td.getString(TAG_DEALNAME);
String price = td.getString(TAG_PRICE);
String description = td.getString(TAG_DESCRIPTION);
String restaurantID = td.getString(TAG_RESTID);
String restaurantName = td.getString(TAG_RESTNAME);
String restaurantType = td.getString(TAG_RESTTYPE);
String lat = td.getString(TAG_LAT);
String lng = td.getString(TAG_LNG);
Log.v("lat", lat);
Log.v("lng", lng);
// Creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_DEALNAME, name);
map.put(TAG_PRICE, price);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_RESTID, restaurantID);
map.put(TAG_RESTNAME, restaurantName);
map.put(TAG_RESTTYPE, restaurantType);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
// adding HashMap to ArrayList
restaurantDealsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
error("Error parsing json");
}
// add to list view
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
restaurantDealsList, R.layout.deals_list_item, new String[] {
TAG_DEALNAME, TAG_RESTNAME, TAG_RESTTYPE }, new int[] {
R.id.dealName, R.id.restaurantName, R.id.type });
// updating listview
myList.setAdapter(adapter);
//handling user click list item
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//start the next activity - Restaurant Details
Intent i = new Intent(getApplicationContext(), DealDetails.class);
i.putExtra("ID", dealID[arg2]);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
}
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;
}
}
You should read the input stream using the charset UTF-8 like this:
replace
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
by
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8));
I use this to decode json with japanese inside.

Android - retrieving json via HTTPS

I've a problem with parsing json from facebook graph api.
When I'm using facebook URL:https://graph.facebook.com/interstacjapl/feed?access_token=MyTOKEN to grab json it's no working, but when I copied that json (it works in browser) and paste to my webiste http://mywebsite/fb.json and change site URL in the code, it works good.
When I'm using fb graph URL it shows error:
W/System.err(5534): org.json.JSONException: No value for data
Is this problem with parsing from https or URL or code?
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
}
MainActivity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "https://graph.facebook.com/interstacjapl/feed?access_token=CAACEdEose0cBANLR...";
//JSON Node Names
private static final String TAG = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "message";
private static final String TAG_API = "type";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_ID,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This works
String reply = "";
BufferedReader inStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
reply = buffer.toString();
} catch (Exception e) {
//Handle Execptions
}

how to get json data from framework (Yii)

i'm trying to get json data from website that i build using Yii framework.
when i open mozilla and i go to http://localhost/restayii/index.php/employee/getemployee?id it's showing employee json data.
this is my employee jsondata :
{"employee":[{"id":"1","departmentId":"1","firstName":"Hendy","lastName":"Nugraha","gender":"female","birth_date":"1987-03-16","marital_status":"Single","phone":"856439112","address":"Tiban Mutiara View ","email":"hendy.nugraha87#yahoo.co.id","ext":"1","hireDate":"2012-06-30 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"2","departmentId":"2","firstName":"Jay","lastName":"Branham","gender":"male","birth_date":"0000-00-00","marital_status":"Single","phone":"0","address":"","email":"jaymbrnhm#labtech.org","ext":"2","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"3","departmentId":"3","firstName":"Ahmad","lastName":"Fauzi","gender":"male","birth_date":"0000-00-00","marital_status":"Single","phone":"0","address":"","email":"ahmadfauzi#labtech.org","ext":"3","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"4","departmentId":"1","firstName":"Henny","lastName":"Lidya Simanjuntak","gender":"female","birth_date":"1986-01-27","marital_status":"Married","phone":"2147483647","address":"Tiban Mutiara View ","email":"henokh_v#yahoo.com","ext":"1","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"5","departmentId":"2","firstName":"sfg","lastName":"sfgsfg","gender":"male","birth_date":"2013-10-23","marital_status":"Single","phone":"356356","address":"sfgsfg","email":"sfgsfg","ext":"4","hireDate":"2012-05-30 00:00:00","leaveDate":"0000-00-00 00:00:00"}]}
this is on Android Activity.
Akses_Server_Aktivity :
public class Akses_Server_Activity extends Activity {
static String url ;
static final String Employee_ID = "id";
static final String Employee_Dept_ID = "departmentId";
static final String Employee_First_Name = "firstName";
static final String Employee_Last_Name = "lastName";
static final String Employee_Gender = "gender";
static final String Employee_Birth_Date = "birth_date";
static final String Employee_Marital_Status = "marital_status";
static final String Employee_Phone_Number = "phone";
static final String Employee_Address = "address";
static final String Employee_Email = "email";
static final String Employee_Ext = "ext";
static final String Employee_Hire_Date = "hireDate";
static final String Employee_Leave_Date = "leaveDate";
JSONArray employee = null;
JSONObject json_object;
Button callService;
EditText ip;
HashMap<String, String> map = new HashMap<String, String>();
String get_ip;
ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_resta);
ip = (EditText)findViewById(R.id.ip_address);
get_ip = ip.getText().toString();
callService = (Button) findViewById(R.id.call_services);
callService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
// masuk ke class Task
new Task().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private class Task extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
// tampilkan progress dialog
pDialog = new ProgressDialog(Akses_Server_Activity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
JSONParser json_parse = new JSONParser();
url = "http://10.0.2.2/restayii/protected/controllers/EmployeeController.php";
employee= json_parse.GetJson(url);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
// masuk ke method LoadEmployee()
LoadEmployee();
}
}
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Constructor
public JSONParser(){
}
public JSONObject GetJson(String url) {
// masuk ke class myasyntask
new MyAsynTask().execute();
return jObj;
}
public class MyAsynTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
return null;
}
protected void onPostExecute(JSONArray Result){
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 {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void LoadEmployee(){
try {
employee = json_object.getJSONArray("employee");
TableLayout table_layout =(TableLayout) findViewById(R.id.table_layout);
table_layout.removeAllViews();
int jml_baris = employee.length();
String [][] data_employee = new String [jml_baris][13];
for(int i=0;i<jml_baris;i++){
JSONObject Result = employee.getJSONObject(i);
data_employee[i][0] = Result.getString(Employee_ID);
data_employee[i][1] = Result.getString(Employee_Dept_ID);
data_employee[i][2] = Result.getString(Employee_First_Name);
data_employee[i][3] = Result.getString(Employee_Last_Name);
data_employee[i][4] = Result.getString(Employee_Gender);
data_employee[i][5] = Result.getString(Employee_Birth_Date);
data_employee[i][6] = Result.getString(Employee_Marital_Status);
data_employee[i][7] = Result.getString(Employee_Phone_Number);
data_employee[i][8] = Result.getString(Employee_Address);
data_employee[i][9] = Result.getString(Employee_Email);
data_employee[i][10] = Result.getString(Employee_Ext);
data_employee[i][11] = Result.getString(Employee_Hire_Date);
data_employee[i][12] = Result.getString(Employee_Leave_Date);
}
TableLayout.LayoutParams ParameterTableLayout = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
for(int j=0; j<jml_baris; j++){
TableRow table_row = new TableRow(null);
table_row.setBackgroundColor(Color.BLACK);
table_row.setLayoutParams(ParameterTableLayout);
TableRow.LayoutParams ParameterTableRow = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
ParameterTableRow.setMargins(1,1,1,1);
for(int kolom = 0; kolom < 13; kolom++){
TextView TV= new TextView(null);
TV.setText(data_employee[j][kolom]);
TV.setTextColor(Color.BLACK);
TV.setPadding(1, 4, 1, 4);
TV.setGravity(Gravity.LEFT);
TV.setBackgroundColor(Color.BLUE);
table_row.addView(TV,ParameterTableRow);
}
table_layout.addView(table_row);
pDialog.dismiss();
}
} catch (Exception e) {
}
}
}
(On Android)
The problem is:
when this app launch, and i clicked button refresh, it's not showing table row that contains employee json data. but there's no error too on the logcat. Is it wrong with my url on class Task extends AsyncTask http://10.0.2.2/restayii/protected/controllers/EmployeeController.php ??
or should i replaced it with the same link just when i open it from mozilla http://localhost/restayii/index.php/employee/getemployee?id??
Edit:
I already change the url to http://localhost/restayii/index.php/employee/getemployee?id inside Task Class extends AsyncTask, but is still won't get employee json data from localhost.
please, Any help would be greatly apreciated. thanks
i already find an answer. my problem is in sub class Task extends asyntask and also in jsonParser sub class.
private class Task extends AsyncTask<JSONObject, Void, JSONObject>{
#Override
protected JSONObject doInBackground(JSONObject... params) {
try {
JSONParser json_parser = new JSONParser();
json_object = json_parser.getJson(url);
} catch (Exception e) {
e.printStackTrace();
}
return json_object;
}
#Override
protected void onPostExecute(JSONObject result){
LoadEmployee(result);
}
}
private class JSONParser {
.....
public JSONObject getJson(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuffer hasil = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
hasil.append(line);
}
json = hasil.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
}
now i can get all json data from my Yii web service. hope it will help someone.
I know that, you have to refresh android screen when you called an ajax data...
May be this will show you the way...
Now you use wrong URL in the AsyncTask. The right URL is something like http://localhost/restayii/index.php/employee/getemployee?id

How to parse json similar inner objects?

I am having the following code
{"sports" :[{"name" :"baseball","id" :1,"links" :{"api" :{"sports" :{"href" :"http://api.espn.com/v1/sports/baseball"},"news" :{"href" :"http://api.espn.com/v1/sports/baseball/news"},"notes" :{"href" :"http://api.espn.com/v1/sports/baseball/news/notes"},"headlines" :{"href" :"http://api.espn.com/v1/sports/baseball/news/headlines"},"events" :{"href" :"http://api.espn.com/v1/sports/baseball/events"}}},"leagues" :[{"name" :"Major League Baseball","abbreviation" :"mlb","id" :10,"groupId" :9,"shortName" :"MLB","season" :{"year" :2012,"type" :2,"description" :"regular","startDate" :"2012-03-27T19:00:00Z","endDate" :"2012-10-05T06:59:59Z"},"week" :{"number" :23,"startDate" :"2012-08-28T19:00:00Z","endDate" :"2012-09-04T18:59:00Z"}}]}],"timestamp" :"2012-08-30T18:01:29Z","status" :"success"}
I want to parse the json objects, in sports object we are having another sports object how to parse inner json objects with array of elements.
I am trying with the following code:
public class BaseballActivity extends ListActivity{
private static String url = "http://api.espn.com/v1/sports/baseball?apikey=h29yphwtf7893hktfbn7cd5g";
private static final String TAG_SPORTS = "sports";
private static final String TAG_ID = "id";
private static final String TAG_TIMESTAMP = "timestamp";
private static final String TAG_NAME = "name";
private static final String TAG_NEWS = "news";
private static final String TAG_HEADLINES = "headlines";
private static final String TAG_LINKS = "links";
private static final String TAG_API = "api";
private static final String TAG_SPORTS1 = "sports";
private static final String TAG_HREF = "href";
JSONArray sports = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// HashMap for ListView
ArrayList<HashMap<String, String>> sportsList = new ArrayList<HashMap<String, String>>();
// creating Json parser instance
JSONParser jParser = new JSONParser();
// getting Json String from url
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Getting Array of Contacts
sports = json.getJSONArray(TAG_SPORTS);
// looping through All Contacts
for(int i = 0; i < sports.length(); i++){
JSONObject c = sports.getJSONObject(i);
//String news = c.getString(TAG_NEWS);
// String headlines = c.getString(TAG_HEADLINES);
String name = c.getString(TAG_NAME);
// String timestamp = c.getString(TAG_TIMESTAMP);
String id = c.getString(TAG_ID);
// JSONObject links = c.getJSONObject(TAG_LINKS);
// JSONObject api = c.getJSONObject(TAG_API);
// JSONObject sports = c.getJSONObject(TAG_SPORTS1);
// String href = c.getString(TAG_HREF);
HashMap<String, String> map = new HashMap<String, String>();
// map.put(TAG_TIMESTAMP, timestamp);
map.put(TAG_NAME, name);
// map.put(TAG_NEWS, news);
// map.put(TAG_HEADLINES, headlines);
map.put(TAG_ID, id);
// map.put(TAG_HREF, href);
sportsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, sportsList,
R.layout.list_item,
new String[]{TAG_NAME,TAG_ID} , new int[] {
R.id.id,R.id.name});
setListAdapter(adapter);
}}
ublic class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}}
Name and id can be displayed when i try to parse inner objects there is no output please help me.
You should have a class Sports that has the objects that come on your JSON string
Than this should do the job for you
JSONObject jObject = new JSONObject(json);
jObject.getJSONObject("sports");
this will make a JSONOBJECT outof your JsonString
Than you will use Googles Gson library to do the following
Gson gson = new Gson();
Sports sports = gson.fromJson(jObject.toString(), Sports.class);
I advise u to have a class to handle all the WebReqeuisitions and not have this code on your Activitys makes your project more structured and your code will be cleaner

How to download a JSON Object array from URL, and Store for Android App?

I'm trying to integrate an API into an android application I am writing, but am having a nightmare trying to get the JSON array. The API has a URL that returns a an JSON array, but having never used JSON before I have no idea how this works, or how to do it.
I've looked and found tons, and tons of examples, but nothing to explain why/how it is done. Any help understanding this would be greatly appreciated.
This is what I've ended up with, again with no understanding of JSON, it was a shot in the dark on my part (using examples/tutorials as a guide)...but it doesn't work :(
import org.json.*;
//Connect to URL
URL url = new URL("URL WOULD BE HERE");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
//Get Data from URL Link
int ok = connection.getResponseCode();
if (ok == 200) {
String line = null;
BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = buffer.readLine()) != null)
sb.append(line + '\n');
//FROM HERE ON I'm Kinda Lost & Guessed
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString()); //ERROR HERE:complains it dosn't know what JSONValue is
JSONArray array = (JSONArray)obj.get("response");
for (int i=0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("name")); //Used to debug
}
}
UPDATE/SOLUTION:
So, it turns out that there was nothing wrong w/t the code. I was missusing what I thought it returns. I thought it was a JSONObject array. In actuality it was a JSONObjects wrapped in an array, wrapped in a JSONObject.
For those interested/ having similar issues, this is what I ended up with. I broke it into two methods. First connect/download, then:
private String[] buildArrayList(String Json, String Find) {
String ret[] = null;
try {
JSONObject jObject = new JSONObject(Json);
JSONArray jArray = jObject.getJSONArray("response");
ret = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String var = json_data.getString(Find);
ret[i] = var;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
1) use webservice to download your required Json string
2) convert it to your desired object using Google Gson
Gson gson = new Gson();
MyClass C1 = gson.fromJson(strJson, MyClass.class);
Here you used JSONValue.parse() that is invalid.
Insted of that Line write this code:
JSONObject obj = new JSONObject(<String Value>);
Ok my friend, i solved the same problem in my app with the next code:
1.- Class to handle the Http request:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONObject jObj1 = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
//Log.e("JSONObject(JSONParser1):", json);
} catch (Exception e) {
Log.e("Buffer Error json1" +
"", "Error converting result json1:" + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj1 = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser1:", "Error parsing data json1:" + e.toString());
}
// return JSON String
return jObj;
}
}
Later, a class to handle the json info (Arrays, Objects, String, etc...)
public class ListViewer extends ListActivity{
TextView UserName1;
TextView LastName1;
// url to make request
private static String url = "http://your.com/url";
// JSON Node names
public static final String TAG_COURSES = "Courses"; //JSONArray
//public static final String TAG_USER = "Users"; //JSONArray -unused here.
//Tags from JSon log.aspx All Data Courses.
public static final String TAG_COURSEID = "CourseId"; //Object from Courses
public static final String TAG_TITLE = "title";
public static final String TAG_INSTRUCTOR = "instructor";
public static final String TAG_LENGTH = "length";
public static final String TAG_RATING = "Rating"; //Object from Courses
public static final String TAG_SUBJECT = "subject";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_STATUS = "Status"; //Object from Courses
public static final String TAG_FIRSTNAME = "FirstName"; //Object from User
public static final String TAG_LASTNAME = "LastName"; //Object from User
// contacts JSONArray
JSONArray Courses = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
// Hashmap for ListView
final ArrayList<HashMap<String, String>> coursesList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance (json2)
JSONParser2 jParser2 = new JSONParser2();
// getting JSON string from URL json2
final JSONObject json2 = jParser2.getJSONFromUrl(url);
try {
// Getting Array of Contacts
Courses = json2.getJSONArray(TAG_COURSES);
// looping through All Courses
for(int i = 0; i < Courses.length(); i++){
JSONObject courses1 = Courses.getJSONObject(i);
// Storing each json item in variable
String courseID = courses1.getString(TAG_COURSEID);
//String status = courses1.getString(TAG_STATUS);
String Title = courses1.getString(TAG_TITLE);
String instructor = courses1.getString(TAG_INSTRUCTOR);
String length = courses1.getString(TAG_LENGTH);
String rating = courses1.getString(TAG_RATING);
String subject = courses1.getString(TAG_SUBJECT);
String description = courses1.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COURSEID,courseID);
map.put(TAG_TITLE, Title);
map.put(TAG_INSTRUCTOR, instructor);
map.put(TAG_LENGTH, length);
map.put(TAG_RATING, rating);
map.put(TAG_SUBJECT, subject);
map.put(TAG_DESCRIPTION, description);
//adding HashList to ArrayList
coursesList.add(map);
}} //for Courses
catch (JSONException e) {
e.printStackTrace();
}
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, coursesList,
R.layout.list_courses,
new String[] { TAG_COURSEID, TAG_TITLE, TAG_INSTRUCTOR, TAG_LENGTH, TAG_RATING, TAG_SUBJECT, TAG_DESCRIPTION }, new int[] {
R.id.txt_courseid, R.id.txt_title, R.id.txt_instructor, R.id.txt_length, R.id.txt_rating, R.id.txt_topic, R.id.txt_description });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
//#Override --------check this override for onClick event---------
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String courseID = ((TextView) view.findViewById(R.id.txt_courseid)).getText().toString();
String Title = ((TextView) view.findViewById(R.id.txt_title)).getText().toString();
String instructor = ((TextView) view.findViewById(R.id.txt_instructor)).getText().toString();
String length = ((TextView) view.findViewById(R.id.txt_length)).getText().toString();
String rating = ((TextView) view.findViewById(R.id.txt_rating)).getText().toString();//Check place in layout
String subject = ((TextView) view.findViewById(R.id.txt_topic)).getText().toString();// <- HERE
String description = ((TextView) view.findViewById(R.id.txt_description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(TAG_COURSEID, courseID);
in.putExtra(TAG_TITLE, Title);
in.putExtra(TAG_INSTRUCTOR, instructor);
in.putExtra(TAG_LENGTH, length);
in.putExtra(TAG_RATING, rating);
in.putExtra(TAG_SUBJECT, subject);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});//lv.SetOnclickListener
}//onCreate
}// Activity
in this case, i'll get the Arrays, objects... Hope this give you ideas...

Categories

Resources