Чтение JSON из API, возвращающее нулевое значение в Android Studio textview - PullRequest
0 голосов
/ 05 мая 2020

Я пытаюсь прочитать значения из API (пример JSON показан ниже) и распечатать их в текстовом виде в Android Studio. Когда я запускаю его, в текстовом окне ничего не отображается. Я следовал руководству и пробовал вызывать разные значения или использовать getString вместо get, но я не вижу, где я ошибаюсь. Любая помощь будет принята с благодарностью.

JSON пример:

[
  {
    "DataProvider": {
      "WebsiteURL": "http://openchargemap.org",
      "DataProviderStatusType": {
        "IsProviderEnabled": true,
        "ID": 1,
        "Title": "Manual Data Entry"
      },
      "IsRestrictedEdit": false,
      "IsOpenDataLicensed": true,
      "IsApprovedImport": true,
      "License": "Licensed under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)",
      "ID": 1,
      "Title": "Open Charge Map Contributors"
    },
    "OperatorInfo": {
      "WebsiteURL": "http://www.ecarni.com/",
      "ContactEmail": "ecar@drdni.gov.uk",
      "ID": 93,
      "Title": "E-Car"
    },
    "UsageType": {
      "IsPayAtLocation": false,
      "IsMembershipRequired": true,
      "IsAccessKeyRequired": true,
      "ID": 4,
      "Title": "Public - Membership Required"
    },
    "StatusType": {
      "IsOperational": true,
      "IsUserSelectable": true,
      "ID": 50,
      "Title": "Operational"
    },
    "SubmissionStatus": {
      "IsLive": true,
      "ID": 100,
      "Title": "Imported and Published"
    },
    "UserComments": [
      {
        "ID": 771,
        "ChargePointID": 13169,
        "CommentTypeID": 10,
        "CommentType": {
          "ID": 10,
          "Title": "General Comment"
        },
        "UserName": "rosemarylaw23",
        "Comment": "",
        "DateCreated": "2014-04-25T19:17:02.063Z",
        "User": {
          "ID": 1825,
          "Username": "rosemarylaw23",
          "ReputationPoints": 2
        },
        "CheckinStatusTypeID": 10,
        "CheckinStatusType": {
          "IsPositive": true,
          "IsAutomatedCheckin": false,
          "ID": 10,
          "Title": "Charged Successfully"
        }
      }
    ],
    "IsRecentlyVerified": false,
    "ID": 13169,
    "UUID": "14399FD9-9E84-4F9C-9730-23EC4062C53F",
    "DataProviderID": 1,
    "OperatorID": 93,
    "OperatorsReference": "SC23",
    "UsageTypeID": 4,
    "AddressInfo": {
      "ID": 13066,
      "Title": "On-street charging point on Little Donegall Street, usual parking restrictions and charges apply",
      "AddressLine1": "128 Little Donegall Street, Belfast BT1, UK",
      "Town": "Belfast",
      "Postcode": "BT1 2JD",
      "CountryID": 1,
      "Country": {
        "ISOCode": "GB",
        "ContinentCode": "EU",
        "ID": 1,
        "Title": "United Kingdom"
      },
      "Latitude": 54.604646,
      "Longitude": -5.931866,
      "AccessComments": "On-street charging point on Little Donegall Street, usual parking restrictions and charges apply (Socket 2)",
      "Distance": 0.31108305591304564,
      "DistanceUnit": 2
    },
    "Connections": [
      {
        "ID": 10588,
        "ConnectionTypeID": 25,
        "ConnectionType": {
          "FormalName": "IEC 62196-2 Type 2",
          "IsDiscontinued": false,
          "IsObsolete": false,
          "ID": 25,
          "Title": "Type 2 (Socket Only)"
        },
        "StatusTypeID": 50,
        "StatusType": {
          "IsOperational": true,
          "IsUserSelectable": true,
          "ID": 50,
          "Title": "Operational"
        },
        "LevelID": 2,
        "Level": {
          "Comments": "Over 2 kW, usually non-domestic socket type",
          "IsFastChargeCapable": false,
          "ID": 2,
          "Title": "Level 2 : Medium (Over 2kW)"
        },
        "Amps": 32,
        "Voltage": 400,
        "PowerKW": 22.0,
        "CurrentTypeID": 20,
        "CurrentType": {
          "Description": "Alternating Current - Three Phase",
          "ID": 20,
          "Title": "AC (Three-Phase)"
        },
        "Quantity": 2
      }
    ],
    "NumberOfPoints": 2,
    "StatusTypeID": 50,
    "DateLastStatusUpdate": "2019-06-23T05:37:00Z",
    "DataQualityLevel": 3,
    "DateCreated": "2012-09-08T22:19:00Z",
    "SubmissionStatusTypeID": 100
  }
]

класс fetchData:

import android.os.AsyncTask;

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 fetchData extends AsyncTask<String, Void, Void> {

    String createdUrl = "";
    String data = "";
    String dataParsed = "";
    String singleParsed = "";

    //Fetch data from API - creat URL using parameters found in other sections eg longitude, latitude, charger type and distance filters
    @Override
    protected Void doInBackground(String... link) {

        try {
            URL url = new URL(createdUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while (line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONArray JA = new JSONArray(data);
            for(int i =0; i <JA.length(); i++){
                JSONObject JO = (JSONObject) JA.get(i);
                singleParsed =  "ID: " + JO.get("UUID") + "\n" +
                                "Distance: " + JO.get("Distance") + "\n" +
                                "Address: " + JO.get("AddressLine1") + "\n" +
                                "Town: " + JO.get("Town") + "\n" +
                                "Postcode: " + JO.get("Postcode");

                dataParsed = dataParsed + singleParsed;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    //Put data in to scrollview
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        results.see.setText(this.dataParsed);
    }

    public void setLink(String senturl){
        createdUrl = senturl;
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...