Skip to content

Instantly share code, notes, and snippets.

@nuriyevn
Created April 5, 2021 19:22
Show Gist options
  • Save nuriyevn/deb805eede2e78b2509eccf14b317a1e to your computer and use it in GitHub Desktop.
Save nuriyevn/deb805eede2e78b2509eccf14b317a1e to your computer and use it in GitHub Desktop.
JSON weather in some straing Hungary city :)
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) { //var args
String result = "";
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) // кінець. 'e' // ASCII UTF-8
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("Website content", result);
try {
JSONObject root = new JSONObject(result);
String weatherStr = root.getString("weather");
JSONArray weatherArray = new JSONArray(weatherStr);
for (int i = 0; i < weatherArray.length(); i++) // clouds, rain,
{
JSONObject weatherFeature = weatherArray.getJSONObject(i);
String weatherMain = weatherFeature.getString("main");
Log.i("Main", weatherMain );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
// https://samples.openweathermap.org/data/2.5/forecast?id=7350&appid=05dced0947a702f8a950e8146cca353a
//Szombathely - сомбатхей
task.execute("https://api.openweathermap.org/data/2.5/weather?q=7350&appid=05dced0947a702f8a950e8146cca353a");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment