0% found this document useful (0 votes)
64 views6 pages

PAM Lab 3 Rotaru Dan

The document is a lab report in Romanian for a mobile app development course. It details an app that emulates a currency conversion web service API. The app allows selecting two currencies from a list, entering an amount to convert, and displays the result. It retrieves live conversion rates by making an HTTP request to a public currency conversion API. The main activity code handles the UI, currency selection, API request, and display of the conversion result.

Uploaded by

Dan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views6 pages

PAM Lab 3 Rotaru Dan

The document is a lab report in Romanian for a mobile app development course. It details an app that emulates a currency conversion web service API. The app allows selecting two currencies from a list, entering an amount to convert, and displays the result. It retrieves live conversion rates by making an HTTP request to a public currency conversion API. The main activity code handles the UI, currency selection, API request, and display of the conversion result.

Uploaded by

Dan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Ministerul Educaţiei, Culturii și Cercetării al Republicii Moldova

Universitatea Tehnică a Moldovei


Departamentul Ingineria Software și Automatică

RAPORT
Lucrare de laborator Nr.3
Disciplina: Programarea
aplicațiilor mobile
Tema: Simple HTTP Client (Web Service Emulation)

A efectuat: st.gr. TI-195 Rotaru Dan

A verificat : asist. univ., Cristian Rusu

Chișinău 2021
Scopul lucrării de laborator

De realizat emularea programatica a unui serviciu web.


Am ales un API (din https://github.com/public-apis/public-apis) pentru a crea o aplicație de convertire
a valutei.
Github API page: https://github.com/fawazahmed0/currency-api#readme
MainActivity (în el am tot codul)

package com.danrotaru.pamlab3;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

public static String[] currencyList = {


"USD",
"EUR",
"MDL",
"RUB",
"UAH",
"RON",
"GBP",
"CNY",
"CAD",
"BTC",
"INR",
"ZAR",
"JPY",
};

// API: https://github.com/fawazahmed0/currency-api#readme
// Response example: https://cdn.jsdelivr.net/gh/fawazahmed0/currency-
api@1/latest/currencies/eur/mdl.json
final String API = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-
api@1/latest/currencies/";

public int c1 = 0;
public int c2 = 2;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

StrictMode.ThreadPolicy policy = new


StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Button currency1 = findViewById(R.id.currency1);


Button currency2 = findViewById(R.id.currency2);
Button reorder = findViewById(R.id.reorder);
Button convert = findViewById(R.id.convert);

currency1.setOnClickListener(v -> showAlertDialog(c1, true));


currency2.setOnClickListener(v -> showAlertDialog(c2, false));

reorder.setOnClickListener(v -> {
int temp;
temp = c1;
c1 = c2;
currency1.setText(currencyList[c2]);

c2 = temp;
currency2.setText(currencyList[temp]);

Convert(true);

});

convert.setOnClickListener(v -> Convert(false));


}
private void showAlertDialog(int checkedItem, boolean first) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(getString(R.string.ChooseCurrency));

alertDialog.setSingleChoiceItems(currencyList, checkedItem, (dialog, which) -> {


if(first){
c1 = which;
Button currency1 = findViewById(R.id.currency1);
currency1.setText(currencyList[which]);
}else{
c2 = which;
Button currency2 = findViewById(R.id.currency2);
currency2.setText(currencyList[which]);
}
//Toast.makeText(MainActivity.this, "Ai ales: " + currencyList[which] ,
Toast.LENGTH_LONG).show();
dialog.cancel();
});
AlertDialog alert = alertDialog.create();
alert.setCanceledOnTouchOutside(false);
alert.show();

public static String getRequest(String urlToRead) throws Exception {


StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
for (String line; (line = reader.readLine()) != null; ) {
result.append(line);
}
}
return result.toString();
}

@SuppressLint("SetTextI18n")
public void Convert(boolean type) {
String text;

if(!isNetworkAvailable()){
Toast.makeText(MainActivity.this, getString(R.string.CheckInternet),
Toast.LENGTH_LONG).show();
}
else{
try {
text =
getRequest(API+currencyList[c1].toLowerCase(Locale.ROOT)+"/"+currencyList[c2].toLowerCase(
Locale.ROOT)+".json");

JSONObject obj;
try {
obj = new JSONObject(text);
String val = obj.getString(currencyList[c2].toLowerCase(Locale.ROOT));
EditText am = findViewById(R.id.amount);
String Amount = am.getText().toString();
float res = 0;
if(!Amount.isEmpty()){
res = Float.parseFloat(Amount) * Float.parseFloat(val);
res = (float) (Math.round(res*100.0)/100.0);
}

if(type){
if(!Amount.isEmpty() && !currencyList[c1].equals(currencyList[c2])){
TextView resultText = findViewById(R.id.result);
resultText.setVisibility(View.VISIBLE);
resultText.setText(Amount + " " + currencyList[c1] + " = " + res + " " +
currencyList[c2]);
}
}
else if(Amount.isEmpty()){
Toast.makeText(MainActivity.this, getString(R.string.ValidSum),
Toast.LENGTH_LONG).show();
}
else if(currencyList[c1].equals(currencyList[c2])){
Toast.makeText(MainActivity.this, getString(R.string.SameCurrency),
Toast.LENGTH_LONG).show();
}
else{
TextView resultText = findViewById(R.id.result);
resultText.setVisibility(View.VISIBLE);
resultText.setText(Amount + " " + currencyList[c1] + " = " + res + " " +
currencyList[c2]);
}

} catch (JSONException e) {
e.printStackTrace();
}

} catch (Exception e) {
e.printStackTrace();
}
}

private boolean isNetworkAvailable() {


ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}

You might also like