Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainActivity extends AppCompatActivity {
- private TextView tv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button button = (Button) findViewById(R.id.btnhit);
- tv = (TextView) findViewById(R.id.tv);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v){
- new JSONtask().execute("http://api.nbp.pl/api/exchangerates/tables/A?format=json");
- }
- });
- }
- public class JSONtask extends AsyncTask<String, String, String>{
- @Override
- protected String 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);
- }
- String jsonData = buffer.toString();
- JSONObject object = new JSONObject(jsonData);
- StringBuffer newBuffer = new StringBuffer();
- JSONArray currencyArray = object.getJSONArray("rates");
- for(int i = 0; i<currencyArray.length(); i++) {
- JSONObject currencyObject = currencyArray.getJSONObject(i);
- String code = currencyObject.getString("code");
- newBuffer.append(code + "\n");
- }
- return newBuffer.toString();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- } finally {
- if (connection != null) {
- connection.disconnect();
- }
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- @Override
- protected void onPostExecute(String result) {
- super.onPostExecute(result);
- tv.setText(result);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment