JSON from php file to java array - android

I know that there are a few question about this subject, but I read them and I tried the soluttion but it didn't work :(
the PHP script give this json array result: data[x] =
["alon","62","1.82","22","0","70","0","1"]
(this is the data[x] variable)
I have to convert this result to Java variabls like name,weight,height etc.. but I don't know how..
please help me
my function:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
String name = null,weight = null;
if (Error != null) {
} else {
// here I have to do something with the arrays...
Toast.makeText(getApplicationContext(),"d:" + data[x] + "o:" + name + " : " + weight, Toast.LENGTH_LONG).show();
}
x++;
}
}

Create a Modal Class for that.
class myModal {
private String name, weight, height, ...;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
//and more getters and setters
}
JSONObject json = new JSONObject(data[x]); // in your sample its a JSONArray but its wrong formatted. make sure you encode it properply with php json_encode(array("data", yourdata))...);
myModal modal = new myModal();
modal.setName(json.getString("name"));
php should be something like
<?php
$data = array("name" => "myname", "weight" => 20);
print json_encode( $data );
?>
while the json can be parsed in this case with
JSONArray json = new JSONArray(data);
for (int i = 0; i <= json.length();i++){
JSONObject jsonObj = json.getJsonObject(i);
myModal modal = new myModal();
modal.setString(jsonObj.getString("name"));
//and so on
}
make sure to read the basics for understanding

Related

How to Retrieve two or more json from multiple Url in MainActivity class Android

I've made a GetJSONTask class which extend AsynkTaskClass. In the onPostExecute method I get the result if I pass single URL in onCreate. like
newCustomAsync().execute("http://abcd.com/fetch/Service1.svc/GetStates?"+
"CCode=" +country+ "");
I want to call multiple URL and retrieve multiple JSON in different variables.
private class CustomAsync extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... URL) {
HttpClient Client = new DefaultHttpClient();
try{
String SetServerString = "";
HttpGet httpget = new HttpGet(URL[0]);
ResponseHandler<String> responseHandler =
new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
JSONArray myListsAll= new JSONArray(SetServerString);
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonobject= (JSONObject) myListsAll.get(i);
String states = jsonobject.optString("states");
}
return SetServerString;
}catch(Exception e){}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONArray myListsAll = null;
try {
myListsAll = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonobject= null;
try {
jsonobject = (JSONObject) myListsAll.get(0);
} catch (JSONException e) {
e.printStackTrace();
}
String msg =jsonobject.optString("states");
}
}
call all the url's in your doInbackground() and get the result. For passing multiple results to your onPostExecute(), use a wrapper class, you've to pass the object of the wrapper class.
public class CustomAsync extends AsyncTask<String, Integer, Wrapper> {
#Override
protected Wrapper doInBackground(String... params) {
String url1 = params[0];
String url2 = params[1]
Wrapper wrapper = new Wrapper();
wrapper.result1 = Get(url1);
wrapper.result2 = Get(url2);
return wrapper;
}
#Override
protected void onPostExecute(Wrapper wrapper) {
String result1 = wrapper.result1;
String result2 = wrapper.result2;
// Do your operation
}
public class Wrapper {
public String result1;
public String result2;
}
}
define Get() as separate function. Code is more clean that way
public static synchronized String Get(String url){
HttpClient Client = new DefaultHttpClient();
try{
String SetServerString = "";
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler =
new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
JSONArray myListsAll= new JSONArray(SetServerString);
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonobject= (JSONObject) myListsAll.get(i);
String states = jsonobject.optString("states");
}
return SetServerString;
}catch(Exception e){}
return null;
}

Android JsonArray into ListView

Im trying to parse json array data into listview!I searched the whole internet and always was on one point! Json aray must have header something like this
"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
Where by my understanding the "emp_info" is the header file by which i must search for rest data inside it in android!My College pretending that i can accept and parse the same data into listview without that header name,but every bit of code where i searched to parse json in android was a single line like this!
JSONObject obj = new JSONObject(jsonString);
JSONArray stations = obj.getJSONArray("emp_inf");
where i just have to put the jsonarray header file as you can see in this piece of code!So please help me is that possible to accept json array without this code?because if i try to remove this code i get nullpointer in my code!Will be very happy if you could at least say yes or no!
Posting Full Codes!
Here is the android class which gets the Json and loads it into List View
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://54.148.41.171/server/index/dompy");
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
String outPut = name + "-" + number;
employeeList.add(createEmployee("data", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employee no" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
And by this json array im successfully able to fetch the json which type is the next!
{"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
And here is the json array which my college pretends that i must accept!
{"data":"123"}
And im Saying that its not possible to load this json into list view just because it dont have header file like mine the emp_info,but hes saying its not matter i just MUST accept!We just on same project and i just cant understand is it even possible to do what he says?
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
How can you get the data by "etc." tag I could not understand it firstly. It should return "" instead of employee number.

JSON Get Value by Edittext

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();
}
}
});

Android JSON Fetch Record of particular column

I want to fetch the record of particular column using JSON Parsing.Here is my screen shot of PHP MySql which is included some data.
Here is above i want to fetch all the record of cat_id = 2 in My Android Application in spinner .But i can't understand how to do this.Can some one help me please . Thanks in advanced.
create a PHP code to get the rows and print it in JSON fromat
$res=mysql_query("select * from table_name where cat_id = '2'") or die(mysql_error());
$assInfo = array();
$num=mysql_num_rows($res);
if($num>0){
$obj=mysql_fetch_array($res);
$assInfo["first"]=$obj["column_name"];
$assInfo["second"]=$obj["another_column"];
array_push($response["info"], $assInfo);
}else{
$response["success"] = 0;
}
echo json_encode($response);
and in android start an Asynctask to grab printed text in background.
public class gettingData extends AsyncTask<Void, Void, Void> {
private String jsonResult;
public gettingData() {
}
#Override
protected Void doInBackground(Void... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("canpass", "herevalue"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
Log.v("jr", jsonResult);
}
catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (jsonResult != null) {
try {
if (jsonResponse.optString("success").matches("0")) {
//your code for no rows selected
}else{
JSONArray jsonMainNode = jsonResponse.optJSONArray("info");
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
String first = jsonChildNode.optString("first");
String second = jsonChildNode.optString("second");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Connection Time Out", Toast.LENGTH_LONG)
.show();
}
}
Execute this class in you activity -
new gettingData().execute();

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

Categories

Resources