Populate spinner from database dosn't work - java

I am trying to populate spinner from darabase but the application crashes, "Unfortunately, "Application" has stopped." and in the logcat I have got this error "
at com.exemple.user.modele.Categorie.onCreate(Categorie.java:43)"
when I remove all the try catch code the activity works, but I copied this code from another activity in the same application to populate a listView and it worked, so please if anyone could help me, thank you !
package com.exemple.user.modele;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class Categorie extends AppCompatActivity {
Spinner spinner1;
String result = null;
String line = null;
InputStream is = null;
String cat_url = "http://10.0.2.2/webapp/categories_spinner.php";
ArrayList<String> list1=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorie);
spinner1 = (Spinner) findViewById(R.id.sSelect);
try {
URL url=new URL(cat_url);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
if(br != null) {
while ((line=br.readLine()) != null) {
sb.append(line+"\n");
}
}
result = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(result);
//CREATE JO OBJ TO HOLD A SINGLE ITEM
JSONObject jo = null;
list1.clear();
//LOOP THRU ARRAY
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
//RETRIOEVE NAME
String name = jo.getString("name");
//ADD IT TO OUR ARRAYLIST
list1.add(name);
}
spinner_fn();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void spinner_fn() {
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(Categorie.this,
android.R.layout.simple_spinner_item, list1);
spinner1.setAdapter(dataAdapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner1.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}

Related

AndroidStudio Login using REST servlet and oracle

I want to make Login Activity using eclipse servlet(REST file) and oracle.
I want to compare column value of EMAIL, PASS of table EMPLOYEES to EditText(user input email and password).
How can I compare two input Strings to column of database table?
This is LoginActivity file(MainActivity)
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity{
EditText email_txt, pw_txt;
Button login_btn;
String REST_URL = "http://localhost:8080/url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email_txt = (EditText)findViewById(R.id.email_txt);
pw_txt = (EditText)findViewById(R.id.pw_txt);
login_btn = (Button)findViewById(R.id.login_btn);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String useremail = email_txt.getText().toString();
String userpass = pw_txt.getText().toString();
//I want to fill this below
//
}
});
}
#Override
public void onResume() {
super.onResume();
JSONClient toServer;
toServer = new JSONClient((JSONClient.MyCallbackInterface) this);
toServer.execute(REST_URL, "GET", "");
}
}
This is JSONClient(Activity)
public class JSONClient extends AsyncTask<String, Void, JSONObject> {
private MyCallbackInterface mCallback;
public JSONClient(MyCallbackInterface callback) {
mCallback = callback;
}
#Override
protected JSONObject doInBackground(String... params) {
String url = params[0];
String method = params[1];
String content = params[2];
return getJSONFromUrl(url, method, content);
}
#Override
protected void onPostExecute(JSONObject result) {
mCallback.onRequestComplete(result);
}
public interface MyCallbackInterface {
public void onRequestComplete(JSONObject result);
}
public JSONObject getJSONFromUrl(String urlStr, String method, String content) {
JSONObject jObj = new JSONObject();
try {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setConnectTimeout(3000);
if (content != null && content.length() > 0) {
urlConnection.getOutputStream().write(content.getBytes(StandardCharsets.UTF_8));
}
String respStr = getStringFromInputStream(urlConnection.getInputStream());
Log.d("JSON Parser1", "Response from server: " + respStr);
jObj = new JSONObject(respStr);
} catch (Exception e) {
Log.e("JSON Parser Exception", e.getLocalizedMessage());
}
return jObj;
}
private String getStringFromInputStream(InputStream is) {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
Log.e("JSON Client", "Error while reading response from server");
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
Log.e("JSON Client", "Error while making string from HTTP response");
return null;
}
}
}
return sb.toString();
}
}

Listview not getting populated and is empty. Arrayadapter seems to be working fine

I am new to Android so I am sorry if this is a mundane question. I am working on one of the exercises in a tutorial and I have a simple list which is supposed to display the data I got from a website. My listview is empty despite my adapter being populated correctly. I tried printing the adapter objects and it is working fine. Please help. Thanks in advance.
MainAcitvity.java
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
private static String USGS_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-12-01&minmagnitude=7";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
ArrayList<String> place = new ArrayList<>();
try {
place = task.execute(USGS_URL).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ArrayAdapter<String> placesAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,place);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(placesAdapter);
}
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>>
{
#Override
protected ArrayList<String> doInBackground(String... strings) {
ArrayList<String > place = QueryUtils.fetchData(strings[0]);
}return place;
}
}
}
QueryUtils.java
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
public final class QueryUtils {
private QueryUtils() {
}
protected static ArrayList<String> fetchData(String rawStream) {
URL newUrl = null;
try {
newUrl = createUrl(rawStream);
Log.i("QueryUtils.java", newUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
ArrayList<String> values = QueryUtils.makeHttpRequest(newUrl);
}return values;
}
private static URL createUrl(String rawStream) throws MalformedURLException {
URL url = new URL(rawStream);
return url;
}
public static ArrayList<String> makeHttpRequest(URL newUrl) {
HttpsURLConnection url = null;
InputStream in = null;
ArrayList<String> values = new ArrayList<>();
try {
url = (HttpsURLConnection) newUrl.openConnection();
in = url.getInputStream();
String data = fetchJsonData(in);
values = fetchOutput(data);
} }catch (IOException e) {
e.printStackTrace();
}
finally {
if(url !=null)
url.disconnect();
}
return values;
}
private static ArrayList<String> fetchOutput(String data) {
String place = null;
ArrayList<String> values = new ArrayList<>();
try {
JSONObject baseJsonObject = new JSONObject(data);
JSONArray featuresAray =baseJsonObject.getJSONArray("features");
for(int i=0;i<featuresAray.length();i++) {
JSONObject firstArray = featuresAray.getJSONObject(i);
JSONObject properties = firstArray.getJSONObject("properties");
place = properties.getString("place");
values.add(place);
}
} catch (JSONException e) {
e.printStackTrace();
}
return values;
}
private static String fetchJsonData(InputStream in) throws IOException {
StringBuilder output = new StringBuilder();
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
return output.toString();
}
}
So the solution was really really stupid. I cant believe I wasted so much time over this. Apparently the text was white and that's why my listView seemed empty :(:(

I have taken text from JSON format of an API now I want to add image to it from same API in my android app

I'm new to android and finding it tough to update realtime text and images from API's in JSON format. I've successfully added text to my listview. Now I want to add image beside it. Thanks in advance.
MainActivity.java file
package com.example.android.samplelayout;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.net.Uri;
import android.graphics.drawable.Drawable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
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();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://webhose.io/search?token=9c55cbb1-2f1c-4700-9c1e-67e685152506&format=json&q=Indian%20Startup";
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
//JSONObject responseObject = jsonObj.getJSONObject("response");
JSONArray responseArray = jsonObj.getJSONArray("posts");
// looping through All Contacts
for (int i = 0; i < responseArray.length(); i++) {
JSONObject firstObject = responseArray.getJSONObject(i);
//JSONObject titleObject = firstObject.getJSONObject("title");
// Extract out the title, time, and tsunami values
//String image = firstObject.getString("main_image");
String title = firstObject.getString("title");
// tmp hash map for single contact
HashMap<String , String> contact = new HashMap<>();
// adding each child node to HashMap key => value
//contact.put("pic", image);
contact.put("name", title);
// 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);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,R.layout.list_item, new String[]{"name"}, new int[]{ R.id.name});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java file
package com.example.android.samplelayout;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
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();
}
}
I would suggest using a library that automatically puts an Image into an ImageView only using the Url of the image you want to use. Picasso would be a good Library for your use. You have to fetch the Image URL off the Json object and load it into the ImageView using Picasso's load().into()

I cant use list view in android with json more than one result

Hi every one I have a problem
i want to get data from site with json and show it in my android list view
but in my program i can only see the first result of json and dont
show me the all result of the json.
please help me.
this is my code
mainactivity code:
package com.example.delta.travel;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity {
private ProgressDialog pd;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> P;
JSONArray s=null;
private final String url="http://192.168.1.3/upload/travel.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
P = new ArrayList<>();
new travel().execute();
}
class travel extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parms=new ArrayList<>();
JSONObject json=jParser.makeHTTPRequest(url,"GET");
try {
int t=json.getInt("t");
if(t==1){
s=json.getJSONArray("travel");
for(int i=0;i<s.length();i++){
JSONObject c=s.getJSONObject(i);
String companyname=c.getString("companyname");
String cod=c.getString("cod");
String bign=c.getString("bign");
String stop=c.getString("stop");
String date=c.getString("date");
String time=c.getString("time");
String price=c.getString("price");
HashMap<String,String>map=new HashMap<String,String>();
map.put("companyname",companyname);
map.put("cod",cod);
map.put("bign",bign);
map.put("stop",stop);
map.put("date",date);
map.put("time",time);
map.put("price",price);
P.add(map);
}
}else {
Toast.makeText(MainActivity.this,"No Data Found",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, P, R.layout.item_list,
new String[]{"companyname", "cod", "bign", "stop", "date", "time", "price"},
new int[]{R.id.companyname, R.id.cod, R.id.bign, R.id.stop, R.id.date, R.id.time1, R.id.price});
setListAdapter(adapter);
}
});
}
}
}
and my json parser code:
package com.example.delta.travel;
import android.net.http.HttpResponseCache;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Date;
import java.util.List;
/**
* Created by delta on 5/28/2016.
*/
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 method
public JSONObject makeHTTPRequest(String urlString, String method) {
if(method.equals("POST")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else if(method.equals("GET")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
}
and my php code:
<?php
$con=mysqli_connect("localhost","root","","travels");
mysqli_set_charset($con,"utf8");
$response=array();
$result=mysqli_query($con,"select * from travel");
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$temp=array();
$temp["companyname"]=$row["companyname"];
$temp["cod"]=$row["cod"];
$temp["bign"]=$row["bign"];
$temp["stop"]=$row["stop"];
$temp["date"]=$row["date"];
$temp["time"]=$row["time"];
$temp["price"]=$row["price"];
$response["travel"]=array();
array_push($response["travel"],$temp);
$response["t"]=1;
echo json_encode($response);
}
}
else{
$response["t"]=0;
$response["message"]="Not Found";
echo json_encode($response);
}
?>

local nodeJS database parsing using JSON library in android application

I have created local DAtabase, with MongoDB and NODEJS, and now i want to parse databse data with my android app, i think i write java code right , but it doesn not work, please help.
Thanks
Here is my Java code.
package com.example.hakobm.buttonparsing;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
protected TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://localhost:3000/api/people");
}
public class JSONTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
int statusCode = 0;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestMethod("GET");
connection.connect(); //connect to server
statusCode = connection.getResponseCode();
if (statusCode == 200) {
System.out.println("Server responded with code: " + statusCode);
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("people");
StringBuffer finalBufferdData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObj = parentArray.getJSONObject(i);
String peopleName = finalObj.getString("name");
Integer age = finalObj.getInt("age");
finalBufferdData.append(peopleName + "-->" + age + "\n");
}
return finalBufferdData.toString(); //pases result to PostExecute
}else{
Log.i("Hakob_log","Error");
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(JSONException e){
e.printStackTrace();
}
finally {
if(connection !=null) {
connection.disconnect();
}
try {
if(reader !=null) {
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}

Categories

Resources