how to get json data from framework (Yii) - android

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

Related

Text in textview is not showing strings from java file - openweathermap

I am trying to use openweathermap to get basic data about weather and paste it into textview, but strings to which I am getting data doesn't refresh texts in textviews.
Code:
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
result.append((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
txtCity = findViewById(R.id.txtCity);
txtTemp = findViewById(R.id.txtTemp);
DownloadJSON downloadJSON = new DownloadJSON();
try {
String result = downloadJSON.execute(url).get();
JSONObject jsonObject = new JSONObject(result);
String temp = jsonObject.getJSONObject("main").getString("temp");
String feel_like = jsonObject.getJSONObject("main").getString("feels_like");
txtCity.setText(City);
txtValueFeelLike.setText(feel_like);
txtTemp.setText(temp);
} catch (ExecutionException | InterruptedException | JSONException e) {
e.printStackTrace();
}
}
'''
String City = "Warsaw";
String url = "http://api.openweathermap.org/data/2.5/weather?q="+City+"&units=metric&appid=eace0bd8251cf6ab043ab9858b796256";
TextView txtCity, txtValueFeelLike, txtTemp;
What am I doing wrong?
Ok, I made a change, tried to make it from the scratch again, but now with onPostExecute(). Still nothing...
public class Weather {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?q=Warsaw&units=metric&appid=eace9b6857889076855263cfdb5707c0d00";
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON();
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
public void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
#SuppressLint("DefaultLocale") String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn);
}
} catch (JSONException e) {
}
}
}
public static JSONObject getWeatherJSON() {
try {
URL url = new URL(OPEN_WEATHER_MAP_URL);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder json = new StringBuilder(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if (data.getInt("cod") != 200) {
return null;
}
return data;
} catch (Exception e) {
return null;
}
}}
And Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
Weather.placeIdTask asyncTask = new Weather.placeIdTask() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
}
};
No idea what to do now.

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

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
}

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

Show data in listview with Asynctask

I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(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;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}

Categories

Resources