How do I get Json from this URL? - android

I'm trying to build an Android application where I show on a Map different bicycle stations with markers all around the city. I'm using the public API offered by the city goverment. (http://www.zaragoza.es/docs-api_sede/#!/Equipamientos_y_movilidad%3A_Estaciones_Bizi/get_servicio_urbanismo_infraestructuras_estacion_bicicleta).
My problem is that I don't know how to recieve this JSON into my application. I've tried different ways but I'm always getting an exception with InputStream saying that there is no file.
I'm using this URL for testing: (https://www.zaragoza.es/sede/servicio/urbanismo-infraestructuras/equipamiento/aparcamiento-bicicleta?rf=html&srsname=wgs84&rows=2&distance=5000) With this URL you get just 2 stations. If you try it on google, you can see the JSON I'm trying to recieve, which is something like this:
{"totalCount":1122,"start":0,"rows":2,"result":[{"id":293,"title":"CALLE SOBRARBE, 46","tipo":"Abierto","plazas":6,"anclajes":3,"lastUpdated":"2018-12-24T00:00:00Z","geometry":{"type":"Point","coordinates":[-0.873314510445586,41.66099094543581]},"icon":"//www.zaragoza.es/contenidos/iconos/aparcabici.png"},{"id":294,"title":"AVENIDA SAN JUAN DE LA PEÑA, 1","tipo":"Abierto","plazas":10,"anclajes":5,"lastUpdated":"2018-12-24T00:00:00Z","geometry":{"type":"Point","coordinates":[-0.8732431572812822,41.66172067640118]},"icon":"//www.zaragoza.es/contenidos/iconos/aparcabici.png"}]}
This is the fragment where I'm trying to recieve the JSON.
public class fMap extends Fragment implements OnMapReadyCallback {
String page= "https://www.zaragoza.es/sede/servicio/urbanismo-infraestructuras/equipamiento/aparcamiento-bicicleta?rf=html&srsname=wgs84&rows=2&distance=5000";
public fMap() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_f_map, container, false);
new JsonTask().execute("page");
return v;
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getContext());
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
}
My goal is getting this JSON so I can get the stations and show them on the Google Map.

Related

Parse Json data into a Json object

I have a problem with parsing a tag inside a Json object.
My json code is structured like that:
{"giocatori":[{"nome":"Giovanni","cognome":"Muchacha","numero":"1","ruolo":"F-G"},
{"nome":"Giorgio","cognome":"Rossi","numero":"2","ruolo":"AG"},
{"nome":"Andrea","cognome":"Suagoloso","numero":"3","ruolo":"P"},
{"nome":"Salvatore","cognome":"Aranzulla","numero":"4","ruolo":"G"},
{"nome":"Giulio","cognome":"Muchacha","numero":"5","ruolo":"F"}]}
I got the code that let me get the Json file from here: Get JSON Data from URL Using Android? and I'm trying to parse a tag (for example the "nome" tag) into a Json object.
This is the code I got:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://api.myjson.com/bins/177dpo");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
I've never worked with this type of file so I'll really appreciate your help!
You can use something like this:
try {
String servResponse = response.toString();
JSONObject parentObj = new JSONObject(servResponse);
JSONArray parentArray = parentObj.getJSONArray("giocatori");
if (parentArray.length() == 0) {
//if it's empty, do something (or not)
} else {
//Here, finalObj will have your jsonObject
JSONObject finalObj = parentArray.getJSONObject(0);
//if you decide to store some value of the object, you can do like this (i've created a nomeGiocatori for example)
nomeGiocatori = finalObj.getString("nome");
}
} catch (Exception e) {
Log.d("Exception: ", "UnknownException");
}
I use this kind of code all the time, works like a charm.

Screen freezes when downloading content from server in android

I am downloading JSON Content from server in the MainActivity and passing the JSON from MainActivity to ListActivity, the problem here is I have added a sleep time of 10s in the backend server i.e. Php from where the data is fetched. Since, the response will the delayed I would expect that screen opens and waits until the response comes and move to next screen.
But what is happening is the screen goes white/black completely untill the response is recieved and ListActivity is loaded, the problem here is the MainActivity is never visible. Below is code for the same:
MainActivity
JSONData jsonData = new JSONData();
String jsonList = jsonData.fetchList();
Intent intent = new Intent(getApplicationContext(),ListActivity.class);
intent.putExtra("jsonList",jsonList);
startActivity(intent);
finish();
JSON Data class
public String fetchList() {
try {
String list = new DownloadJSONData().execute(listURL).get().toString();
return list;
} catch (Exception e) {
return "";
}
}
private class DownloadJSONData extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
you are using get() method which accquires the main thread or ui thread untill the async task is completed
you should avoid using get() and also can use progress dialog in onPreExecute for displaying progression on network call to user

HttpURLConnection doesn't working

Internet Connection is established but not URLconnection.URL is also correct. it sends a data when I visit URL in Web-Browser. Please someone tell me what is the problem? and how to solve it?
My Code::
public class MainActivity extends AppCompatActivity {
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("myinfo","start");
text = (TextView)findViewById(R.id.text);
}
public void btnClicked(View v) {
Log.i("myinfo","Btn clicked");
new JSONTask().execute("jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
Log.i("myinfo","Do in back");
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Log.i("myinfo","Connection done");
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
Log.i("myinfo","Connection not done");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
Log.i("myinfo","Connection disconnect");
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
text.setText(result);
}
}
}
Output flow ::
04-29 11:55:51.558 32585-32585/com.smartrix.httpconection I/myinfo: start
04-29 11:55:54.403 32585-32585/com.smartrix.httpconection I/myinfo: Btn clicked
04-29 11:55:54.509 32585-32699/com.smartrix.httpconection I/myinfo: Do in back
04-29 11:55:54.509 32585-32699/com.smartrix.httpconection I/myinfo: Connection not done
....execute("jsonparsingdemo-cec5b......
You forgot the protocol:
....execute("http://jsonparsingdemo-cec5b......
problem with your url,
URL url = new URL(params[0]);
make it to string like
url = new URL(urlString.toString());
hope so it will work.

Parsing Integer from JSON not working [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I am attempting to make an app in android studio that gets live currency rates, so I decided to use a JSON to do this. I am currently able to print out the entire JSON as a string, however I would like to be able to set the TextView to the USD conversion rate, however it doesn't work. The TextView does not change. Any help would be greatly appreciated.
public class Converter extends AppCompatActivity {
TextView txtJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
new JsonTask().execute("https://openexchangerates.org/api/latest.json?app_id=870447ebb4d94379972250a3bdaed73f");
}
private class JsonTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
public void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jObject = new JSONObject(result);
int USD = jObject.getInt("USD");
String strUSD = Integer.toString(USD);
txtJson.setText(strUSD);
} catch (JSONException e) {
e.printStackTrace();
}
}
}}
You need to get the "rates" object before you can access the "USD" value
Also, it's not an integer. It's a double
getJSONObject("rates").getDouble("USD")

Informationparsing from URL-Request not working / Didn't found TextView

i need your help. I want to send a URL Request, get response and create a JSON Object. My first try was totally wrong. Now I found a tutorial and made a new try.
My Activity looks like:
public class Patienten extends Activity {
//Beacon Elemente
private String UUID;
private String Major;
private String Minor;
private TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patienten);
output = (TextView) findViewById(R.id.output);
UpdateBeaconInformation();
Button cmdHit = (Button) findViewById(R.id.cmd_hit);
cmdHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
}
});
setTitle(Surname + ", " + FirstName);
// output.setText(output.getText().toString() + "Gefundener Patient:\n" + "Name: " + Surname + ", " + FirstName + "\nGeb.-Dat: " + Birthdate);
}
Then I created a new Java Class and built an asyncTask with it. But I can't access to the textview output in onPostExecute to update it.
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//http://kusber-web.de/JsonTest.txt
//http://nilsbenning.selfhost.me/PatientFinder.php?beacon_comID=5181f8a3-7354-46ac-b22d-952ec395ab06&beacon_major=12&beacon_minor=249
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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);
output.setText(result);
}
}
What is my mistake? Why I can't access to it? I saw it as a solution here but didn't get it to work:
https://stackoverflow.com/a/12252717/5743912
Hope you can help me now! :)
You probably want to fix this (remove leading slashes):
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
In your JSONTask you can reference members of Patienten by using Patienten.this. So in onPostExecute you should change this:
output.setText(result);
to:
Patienten.this.output.setText(result);

Categories

Resources