Я работаю над приложением для Android, которое использует службу погоды. В настоящее время я использую API от openweathermap.org и заметил, что в ответе также есть тег значка, и мне было интересно, как на самом деле отобразить это изображение. Я пытался с этим поиграться, но, похоже, не могу в этом разобраться.
Это моя основная деятельность:
public class MainActivity extends Activity {
String description;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
Double lat = 55.676098;
Double lon = 12.568337;
String apiKey = "70c5bf4e84a725a8aeb3dd8c7df4c254";
String urlAPI = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=" + apiKey;
String imgURL = "http://openweathermap.org/img/w/" + description + ".png";
Weather weatherApi = new Weather();
weatherApi.execute(urlAPI);
weatherApi.execute(imgURL);
}
public void goToShowFishActivity(View view) {
Intent intent = new Intent(this, ShowFishiesActivity.class);
startActivity(intent);
}
public void goToAddNewCatchActivity(View view) {
Intent intent = new Intent(this, AddCatch.class);
startActivity(intent);
}
public void goToLogin(View view) {
Intent intent = new Intent(this, CreateUserActivity.class);
startActivity(intent);
}
private class Weather extends ReadHttpTask{
@Override
protected void onPostExecute(CharSequence charSequence){
String text = charSequence.toString();
Integer start = text.indexOf("icon\":\"" ) + "icon\":\"".length();
Integer end = text.indexOf("\"}",start);
description = text.substring(start, end);
TextView weatherTry = (TextView) findViewById(R.id.weatherTry);
weatherTry.setText(description);
}
}
}
Мой класс ReadHttpTask:
public class ReadHttpTask extends AsyncTask {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected CharSequence doInBackground(String...urls) {
String urlString = urls[0];
try{
CharSequence result = HttpHelper.GetHttpResponse(urlString);
return result;
}
catch (IOException ex){
cancel(true);
String errorMessage = ex.getMessage() + "\n" + urlString;
Log.e("Something went wrong", errorMessage);
return errorMessage;
}
}
}
И мой класс HttpHelper:
public class HttpHelper {
@RequiresApi(api = Build.VERSION_CODES.N)
public static CharSequence GetHttpResponse(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
throw new IOException("Not an HTTP connection");
}
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
String responseMessage = httpConnection.getResponseMessage();
throw new IOException("HTTP response code: " + responseCode + " " + responseMessage);
}
InputStream inputStream = httpConnection.getInputStream();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder sb = new StringBuilder();
while (true) {
line = reader.readLine();
if (line == null) break;
sb.append(line);
}
return sb;
} finally {
if (reader != null) reader.close();
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/404 ... ad-android
Иконка OpenWeatherMap скачать на андроид ⇐ Android
Форум для тех, кто программирует под Android
1737991234
Anonymous
Я работаю над приложением для Android, которое использует службу погоды. В настоящее время я использую API от openweathermap.org и заметил, что в ответе также есть тег значка, и мне было интересно, как на самом деле отобразить это изображение. Я пытался с этим поиграться, но, похоже, не могу в этом разобраться.
Это моя основная деятельность:
public class MainActivity extends Activity {
String description;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
Double lat = 55.676098;
Double lon = 12.568337;
String apiKey = "70c5bf4e84a725a8aeb3dd8c7df4c254";
String urlAPI = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=" + apiKey;
String imgURL = "http://openweathermap.org/img/w/" + description + ".png";
Weather weatherApi = new Weather();
weatherApi.execute(urlAPI);
weatherApi.execute(imgURL);
}
public void goToShowFishActivity(View view) {
Intent intent = new Intent(this, ShowFishiesActivity.class);
startActivity(intent);
}
public void goToAddNewCatchActivity(View view) {
Intent intent = new Intent(this, AddCatch.class);
startActivity(intent);
}
public void goToLogin(View view) {
Intent intent = new Intent(this, CreateUserActivity.class);
startActivity(intent);
}
private class Weather extends ReadHttpTask{
@Override
protected void onPostExecute(CharSequence charSequence){
String text = charSequence.toString();
Integer start = text.indexOf("icon\":\"" ) + "icon\":\"".length();
Integer end = text.indexOf("\"}",start);
description = text.substring(start, end);
TextView weatherTry = (TextView) findViewById(R.id.weatherTry);
weatherTry.setText(description);
}
}
}
Мой класс ReadHttpTask:
public class ReadHttpTask extends AsyncTask {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected CharSequence doInBackground(String...urls) {
String urlString = urls[0];
try{
CharSequence result = HttpHelper.GetHttpResponse(urlString);
return result;
}
catch (IOException ex){
cancel(true);
String errorMessage = ex.getMessage() + "\n" + urlString;
Log.e("Something went wrong", errorMessage);
return errorMessage;
}
}
}
И мой класс HttpHelper:
public class HttpHelper {
@RequiresApi(api = Build.VERSION_CODES.N)
public static CharSequence GetHttpResponse(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
throw new IOException("Not an HTTP connection");
}
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
String responseMessage = httpConnection.getResponseMessage();
throw new IOException("HTTP response code: " + responseCode + " " + responseMessage);
}
InputStream inputStream = httpConnection.getInputStream();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder sb = new StringBuilder();
while (true) {
line = reader.readLine();
if (line == null) break;
sb.append(line);
}
return sb;
} finally {
if (reader != null) reader.close();
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/40423819/openweathermap-icon-download-android[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия