Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.jessica.iair;
- import android.content.Context;
- import android.os.AsyncTask;
- import android.util.Log;
- import android.widget.Toast;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.lang.ref.WeakReference;
- import javax.net.ssl.HttpsURLConnection;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.concurrent.ExecutionException;
- import static android.provider.Settings.Global.getString;
- /**
- * Created by luisvf7 on 04/11/2017.
- */
- public class API {
- private Context myContext; //context para conseguir fazer mensagem Toast
- public API(Context context) {
- myContext= context;
- }
- public Integer getPublicChannel(String location) throws ExecutionException, InterruptedException, JSONException {
- AsyncTask<String, Void, JSONArray> task = new GetPublicChannels(myContext); //instanciar async task
- String url = Constants.PUBLIC_CHANNEL_URL_PORTUGAL+location.toLowerCase().replace(" ","%20"); //construção do url para api *fazer parse
- JSONArray publicChannels= task.execute(url).get(); //execução da task para obter canais publicos da location
- Log.d("PublicChannel: "+ location, publicChannels.toString());
- for (int i = 0; i < publicChannels.length(); i++) { //percorrer canais
- JSONObject channel = publicChannels.getJSONObject(i); //obter canal
- JSONArray tags = channel.getJSONArray("tags"); //obter array de tags do canal
- for (int j = 0; j < tags.length(); j++) { //percorrer tags
- JSONObject tag = tags.getJSONObject(j);//obter tag
- if(tag.get("name").toString().equalsIgnoreCase(location)) //verificar se coincide com string location
- return channel.getInt("id"); //retornar id do canal
- }
- }
- return -1;
- }
- public ArrayList<FeedInfoAirQuality> getAllAirQualityValues(String location, String params) throws JSONException {
- String channelID;
- String apiKey;
- ArrayList<FeedInfoAirQuality> feedsReturnList = new ArrayList<>();
- JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
- if (cidadeJson == null)
- return null;
- try {
- channelID = cidadeJson.getString("qualidade-api-id");
- apiKey = cidadeJson.getString("qualidade-api-key");
- } catch (JSONException e) {
- e.printStackTrace();
- return null;
- }
- String url = "https://api.thingspeak.com/channels/" + channelID + "/feeds.json?api_key=" + apiKey; //construção de url para obter channel
- if (params != null) { //parametros opcionais existem
- url += "&"+params;
- }
- FeedInfoAirQuality feedInfo = new FeedInfoAirQuality(); //instanciar feedInfoTempHum
- GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
- JSONObject channelJSON = null; //executar task de GetChannelInfo
- try {
- channelJSON = task.execute(url).get();
- if (channelJSON == null) { //task é null se não conseguir obter informação do canal
- Toast.makeText(myContext, "Error ao obter informação do canal " + channelID, Toast.LENGTH_SHORT).show();
- return null;
- }
- JSONObject channelMeta = channelJSON.getJSONObject("channel");
- ArrayList<String> fields = new ArrayList<>();
- for (int i = 1; i < channelMeta.length(); i++) {
- //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
- try {
- String field = channelMeta.getString("field" + i);
- if (field != null)
- fields.add(field);
- } catch (JSONException e) {
- }
- }
- Log.d("FIELDS", fields.toString());
- JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
- if (arrayFeeds.length() == 0) {
- return null;
- }
- for (int i = 0; i < arrayFeeds.length(); i++) {
- JSONObject feed = arrayFeeds.getJSONObject(i);
- if(feed!=null)
- feedsReturnList.add(getFeedInfoAirQualityFromJSONObj(feed,fields));
- }
- Collections.reverse(feedsReturnList);
- return feedsReturnList;
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return null;
- }
- public ArrayList<FeedInfoTempHum> getAllSensorValues(String location, String params) {
- String channelID;
- String apiKey;
- ArrayList<FeedInfoTempHum> feedsReturnList = new ArrayList<>();
- JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
- if (cidadeJson == null)
- return null;
- try {
- channelID = cidadeJson.getString("temp-hum-api-id");
- apiKey = cidadeJson.getString("temp-hum-api-key");
- } catch (JSONException e) {
- e.printStackTrace();
- return null;
- }
- String url = "https://api.thingspeak.com/channels/" + channelID + "/feeds.json?api_key=" + apiKey; //construção de url para obter channel
- if (params != null) { //parametros opcionais existem
- url += "&"+params;
- }
- FeedInfoTempHum feedInfoTempHum = new FeedInfoTempHum(); //instanciar feedInfoTempHum
- GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
- JSONObject channelJSON = null; //executar task de GetChannelInfo
- try {
- channelJSON = task.execute(url).get();
- if (channelJSON == null) { //task é null se não conseguir obter informação do canal
- Toast.makeText(myContext, "Error ao obter informação do canal " + channelID, Toast.LENGTH_SHORT).show();
- return null;
- }
- JSONObject channelMeta = channelJSON.getJSONObject("channel");
- ArrayList<String> fields = new ArrayList<>();
- for (int i = 1; i < channelMeta.length(); i++) {
- //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
- try {
- String field = channelMeta.getString("field" + i);
- if (field != null)
- fields.add(field);
- } catch (JSONException e) {
- }
- }
- Log.d("FIELDS", fields.toString());
- JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
- if (arrayFeeds.length() == 0) {
- return null;
- }
- for (int i = 0; i < arrayFeeds.length(); i++) {
- JSONObject feed = arrayFeeds.getJSONObject(i);
- if(feed!=null)
- feedsReturnList.add(getFeedInfoTempHumFromJSONObj(feed,fields));
- }
- Collections.reverse(feedsReturnList);
- return feedsReturnList;
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return null;
- }
- public FeedInfoTempHum getLastFeedInfoTempHumCity(String location, String params) throws ExecutionException, InterruptedException, JSONException {
- JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
- if(cidadeJson == null)
- return null;
- String channelID = cidadeJson.getString("temp-hum-api-id");
- String apiKey = cidadeJson.getString("temp-hum-api-key");
- String url = "https://api.thingspeak.com/channels/"+channelID+"/feeds.json?api_key="+apiKey; //construção de url para obter channel
- if(params!=null){ //parametros opcionais existem
- url+="?"+params;
- }
- FeedInfoTempHum feedInfoTempHum = new FeedInfoTempHum(); //instanciar feedInfoTempHum
- GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
- JSONObject channelJSON = task.execute(url).get(); //executar task de GetChannelInfo
- if(channelJSON == null){ //task é null se não conseguir obter informação do canal
- Toast.makeText(myContext,"Error ao obter informação do canal "+channelID,Toast.LENGTH_SHORT).show();
- return null;
- }
- JSONObject channelMeta = channelJSON.getJSONObject("channel");
- ArrayList<String> fields = new ArrayList<>();
- for (int i = 1; i < channelMeta.length(); i++) {
- //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
- try {
- String field = channelMeta.getString("field"+i);
- if(field!=null)
- fields.add(field);
- }catch (JSONException e){
- }
- }
- Log.d("FIELDS", fields.toString());
- JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
- if (arrayFeeds.length() == 0) {
- return null;
- }
- JSONObject lastFeedInfo = arrayFeeds.getJSONObject(arrayFeeds.length()-1); //obter o ultimo feed
- Log.d("LASTFEEDINFO", lastFeedInfo.toString());
- return getFeedInfoTempHumFromJSONObj(lastFeedInfo,fields);
- }
- public FeedInfoAirQuality getLastFeedInfoAirQualityCity(String location, String params) throws ExecutionException, InterruptedException, JSONException {
- JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
- if(cidadeJson == null)
- return null;
- String channelID = cidadeJson.getString("qualidade-api-id");
- String apiKey = cidadeJson.getString("qualidade-api-key");
- String url = "https://api.thingspeak.com/channels/"+channelID+"/feeds.json?api_key="+apiKey; //construção de url para obter channel
- if(params!=null){ //parametros opcionais existem
- url+="?"+params;
- }
- FeedInfoAirQuality feedInfoQualidadeAr = new FeedInfoAirQuality(); //instanciar feedInfoTempHum
- GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
- JSONObject channelJSON = task.execute(url).get(); //executar task de GetChannelInfo
- if(channelJSON == null){ //task é null se não conseguir obter informação do canal
- Toast.makeText(myContext,"Error ao obter informação do canal "+channelID,Toast.LENGTH_SHORT).show();
- return null;
- }
- JSONObject channelMeta = channelJSON.getJSONObject("channel");
- ArrayList<String> fields = new ArrayList<>();
- for (int i = 1; i < channelMeta.length(); i++) {
- //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
- try {
- String field = channelMeta.getString("field"+i);
- if(field!=null)
- fields.add(field);
- }catch (JSONException e){
- }
- }
- Log.d("FIELDS", fields.toString());
- JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
- if (arrayFeeds.length() == 0) {
- return null;
- }
- JSONObject lastFeedInfo = arrayFeeds.getJSONObject(arrayFeeds.length()-1); //obter o ultimo feed
- Log.d("LASTFEEDINFO", lastFeedInfo.toString());
- feedInfoQualidadeAr.setFeedInfoDate(lastFeedInfo.getString(Constants.LAST_UPDATED));
- feedInfoQualidadeAr.setCo(-1);
- feedInfoQualidadeAr.setNo2(-1);
- feedInfoQualidadeAr.setO3(-1);
- for (int i = 1; i <= fields.size(); i++) {
- Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
- if (lastFeedInfo.getString("field"+i) != "null" && !lastFeedInfo.getString("field"+i).isEmpty()) {
- if (Arrays.asList(Constants.O3).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
- feedInfoQualidadeAr.setO3(Float.parseFloat(lastFeedInfo.getString("field" + i)));
- }
- if (Arrays.asList(Constants.NO2).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
- feedInfoQualidadeAr.setNo2(Float.parseFloat(lastFeedInfo.getString("field" + i)));
- }
- if (Arrays.asList(Constants.CO).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
- feedInfoQualidadeAr.setCo(Float.parseFloat(lastFeedInfo.getString("field" + i)));
- }
- }
- }
- return feedInfoQualidadeAr;
- }
- public int postInfoEventoParaCidade(String location, CityEvent evt ) throws ExecutionException, InterruptedException {
- //Buscar API KEY para POST
- JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
- String api;
- if(cidadeJson == null)
- return -1;
- try {
- api = cidadeJson.getString("write-api-key");
- } catch (JSONException e) {
- e.printStackTrace();
- return -1;
- }
- //Construir body json do evento
- String json;
- JSONObject jsonObject = new JSONObject();
- try {
- jsonObject.accumulate("field1", evt.getAutor());
- jsonObject.accumulate("field2", evt.getAssunto());
- jsonObject.accumulate("field3", evt.getMensagem());
- jsonObject.accumulate("field4", evt.getUltima_localizacao());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- json = jsonObject.toString();
- PostChannelInfo pChannelInfo = new PostChannelInfo(myContext);
- Log.d("UPLOAD", "postInfoEventoParaCidade: "+evt.toString());
- return pChannelInfo.execute(api,json).get();
- }
- public int postInfoMedicaoSensoresParaCidade(String location, String autor, FeedInfoTempHum feed ) throws ExecutionException, InterruptedException {
- //Buscar API KEY para POST
- JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
- String api;
- if(cidadeJson == null)
- return -1;
- try {
- api = cidadeJson.getString("write-api-key-temphum");
- } catch (JSONException e) {
- e.printStackTrace();
- return -1;
- }
- //Construir body json do evento
- String json;
- JSONObject jsonObject = new JSONObject();
- try {
- //field1 - autor
- //field2 - humidade
- //field3 - temperatura
- jsonObject.accumulate("field1", autor);
- if(feed.getHumidity() != 0.0f){
- jsonObject.accumulate("field2", feed.getHumidity());
- }
- if(feed.getTemperature() != 0.0f){
- jsonObject.accumulate("field3", feed.getTemperature());
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- json = jsonObject.toString();
- PostChannelInfo pChannelInfo = new PostChannelInfo(myContext);
- Log.d("UPLOAD", "postInfoMedicaoSensoresParaCidade: "+feed.toString());
- return pChannelInfo.execute(api,json).get();
- }
- public ArrayList<CityEvent> getEventsCity(String location, String params) throws ExecutionException, InterruptedException, JSONException {
- Toast.makeText(myContext, "A carregar eventos..", Toast.LENGTH_SHORT).show();
- JSONObject cidadeJson = getCidadeJson(location); //obter id do canal para a location
- ArrayList<CityEvent> events = new ArrayList<>();
- if(cidadeJson == null)
- return null;
- String channelID = cidadeJson.getString("events-api-id");
- String apiKey = cidadeJson.getString("events-api-key");
- String url = "https://api.thingspeak.com/channels/"+channelID+"/feeds.json?api_key="+apiKey; //construção de url para obter channel
- if(params!=null){ //parametros opcionais existem
- url+="?"+params;
- }
- GetChannelInfo task = new GetChannelInfo(myContext); //instanciar class GetChannelInfo
- JSONObject channelJSON = task.execute(url).get(); //executar task de GetChannelInfo
- if(channelJSON == null){ //task é null se não conseguir obter informação do canal
- Toast.makeText(myContext,"Error ao obter informação do canal "+channelID,Toast.LENGTH_SHORT).show();
- return null;
- }
- JSONObject channelMeta = channelJSON.getJSONObject("channel");
- ArrayList<String> fields = new ArrayList<>();
- for (int i = 1; i < channelMeta.length(); i++) {
- //Log.d("CHANNEL FIELDS", channelMeta.getString(i));
- try {
- String field = channelMeta.getString("field"+i);
- if(field!=null)
- fields.add(field);
- }catch (JSONException e){
- }
- }
- Log.d("FIELDS", fields.toString());
- JSONArray arrayFeeds = channelJSON.getJSONArray("feeds");
- if (arrayFeeds.length() == 0) {
- return null;
- }
- for (int i = 0; i<=arrayFeeds.length()-1;i++){ //iterar todos os os objects
- CityEvent ctEvent = new CityEvent(null,null,null,null);
- JSONObject eventJson = arrayFeeds.getJSONObject(i);
- ctEvent.setData(eventJson.getString("created_at"));
- for (int j = 1; j <= fields.size(); j++) { //iterar todos os fields
- Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
- if (eventJson.getString("field"+j) != "null" && !eventJson.getString("field"+j).isEmpty()) {
- if ( fields.get(j-1).equalsIgnoreCase("autor")) {
- ctEvent.setAutor(eventJson.getString("field"+j));
- }
- if ( fields.get(j-1).equalsIgnoreCase("assunto")) {
- ctEvent.setAssunto(eventJson.getString("field"+j));
- }
- if ( fields.get(j-1).equalsIgnoreCase("mensagem")) {
- ctEvent.setMensagem(eventJson.getString("field"+j));
- }
- if ( fields.get(j-1).equalsIgnoreCase("ultima_localizacao")) {
- ctEvent.setUltima_localizacao(eventJson.getString("field"+j));
- }
- }
- }
- events.add(ctEvent);
- }
- return events;
- }
- private static class GetPublicChannels extends AsyncTask<String, Void, JSONArray> {
- private WeakReference<Context> activityReference;
- GetPublicChannels(Context context) {
- activityReference = new WeakReference<>(context);
- }
- @Override
- protected void onPreExecute() {
- //Toast.makeText(activityReference.get(), "Getting Info", Toast.LENGTH_SHORT).show();
- }
- @Override
- protected JSONArray doInBackground(String... params) {
- HttpURLConnection connection = null;
- BufferedReader reader = null;
- try {
- URL url = new URL(params[0].toString());
- 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);
- }//final de while temos a resposta (json)
- JSONObject obj = new JSONObject(buffer.toString()); //criar json object
- return obj.getJSONArray("channels"); //obter array de canais
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException | JSONException e ) {
- e.printStackTrace();
- } finally {
- if (connection != null) {
- connection.disconnect();
- }
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- }
- private static class GetChannelInfo extends AsyncTask<String, Void, JSONObject> {
- private WeakReference<Context> activityReference;
- GetChannelInfo(Context context) {
- activityReference = new WeakReference<>(context);
- }
- @Override
- protected void onPreExecute() {
- //Toast.makeText(activityReference.get(), "Getting Info", Toast.LENGTH_SHORT).show();
- }
- @Override
- protected JSONObject 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 new JSONObject(buffer.toString());
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException | JSONException e ) {
- e.printStackTrace();
- } finally {
- if (connection != null) {
- connection.disconnect();
- }
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- }
- private static class PostChannelInfo extends AsyncTask<String, Void, Integer> {
- private WeakReference<Context> activityReference;
- PostChannelInfo(Context context) {
- activityReference = new WeakReference<>(context);
- }
- @Override
- protected void onPreExecute() {
- //Toast.makeText(activityReference.get(), "Getting Info", Toast.LENGTH_SHORT).show();
- }
- @Override
- protected Integer doInBackground(String... params) {
- try {
- URL url = new URL("https://api.thingspeak.com/update.json"); //Enter URL here
- HttpsURLConnection httpURLConnection = (HttpsURLConnection)url.openConnection();
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setRequestProperty("THINGSPEAKAPIKEY",params[0]);
- httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
- httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
- httpURLConnection.connect();
- DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
- wr.write(params[1].getBytes("UTF-8"));
- wr.flush();
- wr.close();
- return httpURLConnection.getResponseCode();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return -1;
- }
- }
- private FeedInfoTempHum getFeedInfoTempHumFromJSONObj(JSONObject obj, ArrayList<String> fields){
- FeedInfoTempHum feedInfoTempHum = new FeedInfoTempHum();
- try {
- feedInfoTempHum.setFeedInfoDate(obj.getString(Constants.LAST_UPDATED));
- feedInfoTempHum.setTemperature(Float.MAX_VALUE);
- feedInfoTempHum.setHumidity(-1);
- for (int i = 1; i <= fields.size(); i++) {
- Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
- if (obj.getString("field"+i) != "null" && !obj.getString("field"+i).isEmpty()
- && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.TEMP_SENSOR_ND)) && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.HUM_SENSOR_ND))) {
- if (Arrays.asList(Constants.TEMPERATURE).contains(fields.get(i - 1).toLowerCase())) { //se for field de temperatura
- feedInfoTempHum.setTemperature(Float.parseFloat(obj.getString("field" + i)));
- }
- if (Arrays.asList(Constants.HUMIDITY).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
- feedInfoTempHum.setHumidity(Float.parseFloat(obj.getString("field" + i)));
- }
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return feedInfoTempHum;
- }
- private FeedInfoAirQuality getFeedInfoAirQualityFromJSONObj(JSONObject obj, ArrayList<String> fields){
- FeedInfoAirQuality feedInfoAirQuality = new FeedInfoAirQuality ();
- try {
- feedInfoAirQuality.setFeedInfoDate(obj.getString(Constants.LAST_UPDATED));
- feedInfoAirQuality.setCo(-1);
- feedInfoAirQuality.setNo2(-1);
- feedInfoAirQuality.setO3(-1);
- for (int i = 1; i <= fields.size(); i++) {
- Log.d("FEEDINFO", "getLastFeedInfoIteration: "+i);
- if (obj.getString("field"+i) != "null" && !obj.getString("field"+i).isEmpty()
- && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.TEMP_SENSOR_ND)) && !obj.getString("field"+i).equalsIgnoreCase(String.valueOf(R.string.HUM_SENSOR_ND))) {
- if (Arrays.asList(Constants.CO).contains(fields.get(i - 1).toLowerCase())) { //se for field de temperatura
- feedInfoAirQuality.setCo(Float.parseFloat(obj.getString("field" + i)));
- }
- if (Arrays.asList(Constants.NO2).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
- feedInfoAirQuality.setNo2(Float.parseFloat(obj.getString("field" + i)));
- }
- if (Arrays.asList(Constants.O3).contains(fields.get(i - 1).toLowerCase())) { //se for field de humidade
- feedInfoAirQuality.setO3(Float.parseFloat(obj.getString("field" + i)));
- }
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return feedInfoAirQuality;
- }
- private JSONObject getCidadeJson(String local){
- try {
- JSONArray obj = new JSONArray(loadJSONFromAsset());
- for (int i = 0; i < obj.length(); i++) {
- JSONObject objetoJson = obj.getJSONObject(i);
- if(objetoJson.getString("nome_distrito").equalsIgnoreCase(local))
- return objetoJson;
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return null;
- }
- public String loadJSONFromAsset() {
- String json = null;
- try {
- InputStream is = myContext.getAssets().open("distritos.json");
- int size = is.available();
- byte[] buffer = new byte[size];
- is.read(buffer);
- is.close();
- json = new String(buffer, "UTF-8");
- } catch (IOException ex) {
- ex.printStackTrace();
- return null;
- }
- return json;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment