Исключение указывает на эту строку StringuserJsonStroke=getJsonFromServer(String.format("%s/%d", urlPath), 0);
Вот весь класс
public class JsonPlaceholderApi {
private String urlPath;
public JsonPlaceholderApi(String urlPath) {
this.urlPath = urlPath;
}
public User getUser(JSONObject jsonObject) throws IOException, JSONException {
// JSONObject userRoot = new JSONObject(jsonObject);
JSONObject userAddress = jsonObject.getJSONObject("address");
JSONObject userCompany = jsonObject.getJSONObject("company");
JSONObject addressGeo = userAddress.getJSONObject("geo");
int userId = jsonObject.getInt("id");
String userName = jsonObject.getString("name");
String userNameName = jsonObject.getString("username");
String userEmail = jsonObject.getString("email");
String userPhone = jsonObject.getString("phone");
String userWebSite = jsonObject.getString("website");
String addressStreet = userAddress.getString("street");
String addressSuite = userAddress.getString("suite");
String addressCity = userAddress.getString("city");
String addressZipcode = userAddress.getString("zipcode");
double geoLat = addressGeo.getDouble("lat");
double getLon = addressGeo.getDouble("lng");
String companyName = userCompany.getString("name");
String companyCatchPhrase = userCompany.getString("catchPhrase");
String companyBs = userCompany.getString("bs");
Geo geo = new Geo(geoLat, getLon);
Address address = new Address(addressStreet, addressSuite, addressCity, addressZipcode, geo);
Company company = new Company(companyName, companyCatchPhrase, companyBs);
return new User(userId, userName, userNameName, userEmail, address, userPhone, userWebSite, company);
}
public ArrayList<User> getUserList() throws IOException, JSONException {
String userJsonStroke = getJsonFromServer(String.format("%s/%d", urlPath), 0);
JSONArray array = new JSONArray(userJsonStroke);
ArrayList<User> userArrayList = new ArrayList<>();
for(int i = 0; i<array.length(); i++){
JSONObject obj = array.getJSONObject(i);
User newUser = getUser(obj);
userArrayList.add(newUser);
}
return userArrayList;
}
private String getJsonFromServer(String urlPath, int timeout) throws IOException {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.connect();
int serverResponseCode = connection.getResponseCode();
switch (serverResponseCode) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String tmpLine;
while ((tmpLine = br.readLine()) != null) {
sb.append(tmpLine).append("\n");
}
br.close();
return sb.toString();
case 404:
Log.d(JsonPlaceholderApi.class.getName(), "page not found!");
break;
case 400:
Log.d(JsonPlaceholderApi.class.getName(), "Bad request!");
break;
case 500:
Log.d(JsonPlaceholderApi.class.getName(), "Internal server error");
break;
}
return null;
}
}
Сама строчка находится в методе, который парсит json'ы
UserTask class
public class UserTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
JsonPlaceholderApi api = new JsonPlaceholderApi("https://jsonplaceholder.typicode.com/users");
try {
// User user = api.getUser(1);
// User user2 = api.getUser(2);
// User user3 = api.getUser(3);
Log.d("Success",(api.getUserList().toString()));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Кофе для программистов: как напиток влияет на продуктивность кодеров?
Рекламные вывески: как привлечь внимание и увеличить продажи
В Java потоки ввода-вывода InputStream и OutputStream представляют собой концепцию работы с внешним миром, будь то файл на диске, экран монитора, сетевое...
Начал разбираться с JavaFx и появился вопросВозможно ли сделать так, что при нажатии на элементы TreeView появлялся текст, который привязан к этому...
Что будет с программным кодом, если объявить объект родительского класса с конструктором дочернего класса? Иначе говоря, какой конструктор...
Известный факт что массив в Java это объект, а значит он должен иметь класс из которого мы строим этот объектПо идее он должен быть финальным...