Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.thibaut.tp1;
- import android.app.Activity;
- import android.os.AsyncTask;
- import android.util.Log;
- import android.widget.EditText;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- /**
- * Created by thibaut on 08/10/2015.
- */
- class JSONAsyncTask extends AsyncTask<String, String, String> {
- Activity mActivity;
- EditText out;
- public JSONAsyncTask(Activity a) {
- this.mActivity = a;
- }
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
- @Override
- protected String doInBackground(String... args) {
- StringBuilder result = new StringBuilder();
- HttpURLConnection urlConnection = null;
- try {
- URL url = new URL("http://api.fixer.io/latest?base=USD&symbols=EUR");
- urlConnection = (HttpURLConnection) url.openConnection();
- InputStream in = new BufferedInputStream(urlConnection.getInputStream());
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- String line;
- while ((line = reader.readLine()) != null) {
- result.append(line);
- }
- }catch( Exception e) {
- e.printStackTrace();
- }
- finally {
- assert urlConnection != null;
- urlConnection.disconnect();
- }
- return result.toString();
- }
- protected void onPostExecute(String result) {
- try {
- JSONObject data = new JSONObject(result);
- String tx = data.getString("rates");
- JSONObject currency = new JSONObject(tx);
- double value = currency.getDouble("EUR");
- out = (EditText)
- mActivity.findViewById(R.id.output_value);
- out.setText( Double.toString(value) );
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement