- Как сделать android приложение курс валют?
- Boolkin blog
- Топ тем:
- воскресенье, 23 августа 2020 г.
- Как я сделал виджет курса обмена валют для Android
- How to Create a Simple Currency Converter App in Android Studio
- Learn to create your own currency converter as a means of learning the core concepts behind Android application development in Java.
- Simple Currency Converter Android App Example and How to Create It
- Activity_main.xml
- Relative Layout
- Plain Text (Text View)
- Edit Text View
- Button Widget
- Image View
- Activity_main.xml
- Add Java Code Implementations in the MainActivity.java File
- MainActivity.java
- Create real time currency converter app in Android Studio
- To create a new project in android studio: currency converter
- Start coding
- MainActivity.java
- Oncreate()
- KamalInterface
- KamalBuild
- XML Code
Как сделать android приложение курс валют?
Средний 1 комментарий
«ничего не выводит» — это не корректное описание проблемы, а издевательство. Принято рассказывать, что именно происходит не так.
Сходу видно, что вы обращаетесь к сети из ui потока. Запрос к сети необходимо производить в отдельном потоке.
если бы я знала что происходит не так обязательно бы написала) На данный момент я остановилась на таком коде. В лист корректно подгружаются данные из xml, но ListAdapter отказывается выводить их на экран и просто экстренно завершает работу эмулятора. Я пробовала выгружать данные из ArrayList в отдельные массивы name и value, и делать вывод через стандартные ArrayAdapter , но этот массив не передается в него.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.*;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity <
ProgressDialog progressDialog;
ArrayList list = new ArrayList<>();
private ListView lv;
Источник
Boolkin blog
Блог о том что мне интересно
Топ тем:
воскресенье, 23 августа 2020 г.
Как я сделал виджет курса обмена валют для Android
Иногда хочется запилить своими руками что-то интересное и немного даже полезное, но вот из-за того что я не программист (просто любитель), то приходится делать это своим странным способом с использованием некоторых костылей. Сегодня речь идет о том, как я сделал для себя виджет курса обмена валют на рабочий стол андроида.
Так как писать свой виджет это не просто так (в обычном блокноте это не сделать): нужна андроид студия, которая жрет ресурсов хренову кучу, да еще и нужно уметь в ней работать и программировать, то решено было поискать что-то готовое в плей маркете. Там удалось найти хорошую программу — Web Image Widget — программа просто выводит на рабочий стол картинку из интернета, по адресу задаваемому в настройках, и может масштабировать и менять размер виджета как душе угодно. Мне понравилось то, что нужная инфа может уместить лишь в одну ячейку:
Как видно на скрине, просто картинка с впечатанными в нее данными по курсам валют — удобно не так ли? Дважды щелкнул по картинке и данные обновились.
Теперь напишу как я это сделал. Как уже говорилось ранее, не обошлось без костылей, и обычным пользователям этот способ не совсем уж подходит, потому что для его реализации нужен хостинг с поддержкой PHP. У меня есть свой сайт, потому создать новый документ там не проблема, да и к тому же мне стало интересно можно ли с помощью PHP генерировать картинку с текстом. Оказалось что можно и делается это очень просто и легко.
За основу взял статью по функции https://www.php.net/manual/ru/function.imagettftext.php Первый пример в этой статье объясняет как пользоваться этой функцией, и что для чего нужно.
Первая строка у меня без изменения, а нужна для того чтобы страница возвращала именно картинку по запросу, а не непонятный набор байт:
Теперь чтобы добавить универсальности мы добавим поддержку распознавания запрашиваемых валют: нужные нам валюты мы будем вбивать в адрес через запятую, таким образом адрес нашей картинки будет иметь такой вид https://yoursite.com/kurs.php?show=usd,eur,kzt ,а чтобы это сделать мы просто создаем массив $currences, куда помещаем все аргументы строки GET запроса, разделенные запятыми (то бишь аргументы usd,eur,kzt)
$currences = explode(«,», $_GET[«show»]);
и сразу же посчитаем сколько строк нам нужно выводить
На основе полученного количества строк, вычисляем разрешение картинки по вертикали, и рисуем соответствующих размеров и цветов прямоугольники
Источник
How to Create a Simple Currency Converter App in Android Studio
Learn to create your own currency converter as a means of learning the core concepts behind Android application development in Java.
Join the DZone community and get the full member experience.
I have been working on a number of projects as of late and today I wanted to share with you some of them.
This tutorial will take you through a step-by-step process on how to create a simple currency converter app in Android studio.
We shall be using Java and at the same time to convert this application to Kotlin (if time allows).
Java and Kotlin are now the most popular Android development languages, with the latter being the official programming language for making apps in Android Studio.
We assume all factors EW constant, you have Android Studio installed on your PC, and the environment has been properly set up.
As such, in this tutorial, we are going to use Android Studio for our simple currency converter Android application.
Simple Currency Converter Android App Example and How to Create It
Open Android Studio from Start Menu > All Programs or simply tap the icon on the desktop to get started.
Wait for a few minutes as Android Studio launches. This may take a while depending on the computer speed processor or RAM. You may need to wait until Gradle Sync is finished.
Once Android Studio has been fully launched, go to File > New and Create a new Project and name it Currency Converter App or anything you want.
Click Next, then select the Form Factors and minimum SDK. Just tick Phone and Tablet and select at least API 15: Android 4.0.3 (IceCreamSandwich). We are targeting this API because it powers at least 90% of all Android devices in the world.
You should always try to make Android applications compatible with the majority of the Android devices in the market.
Click Next and Add an empty Activity to our Project.
In Create a new empty Activity, simply continue with defaults and click Finish.
It’s now time we make our simple currency converter application. You’ll have to wait until Gradle Sync is finished to continue with the tutorial.
So, in this case, we shall create two files (in fact, Android Studio has already created them for you) the MainActivity.java and Activity_main.xml.
We shall put all our Simple Currency Converter source code in activity_main.xml and the Java implementations in MainActivity.java.
Activity_main.xml
To create the interface below, you can simply copy and paste the source code below or follow some of these procedures to create this simple Currency Converter interface.
Go to res folder > Layout and select activity_main.xml. Click Text to add the following piece of XML code.
Relative Layout
In this tutorial, we shall use Relative Layout to align our currency converter app widgets. You can add Relative Layout to the activity_main.xml file by implementing the code snippet below.
Plain Text (Text View)
We need to add a Text View with the text «Enter Currency in dollars,» assuming we are doing a currency converter for converting dollars to euros.
You can implement this by adding the following code below to activity_main.xml file.
Edit Text View
This widget will allow a user to add a figure or currency that needs to be converted. You can also implement the Edit Text widget in activity_main.xml using the code snippet below.
Note: Text hint allows Edit Text widget to show sample information or give a hint; a user is required to add to this field or box.
Button Widget
You can now add the button widget that a user clicks and converts the figures in an Edit Text widget to another currency. Use the code snippet below to implement this.
Note: The on Click Method, convertToEuro , will be used in our Java code.
Image View
To make our application look nice, you may need to add some image widgets with an image placed below the button. Use the code snippet below to add this piece of code to your Simple Currency Converter App.
Note: You’ll have to download a sample image from Google. Copy and paste it in your drawable folder (drawable is also under res).
After that, everything is complete for our activity_main.xml file. We shall have something like the code below.
Activity_main.xml
Add Java Code Implementations in the MainActivity.java File
Head back to Java > com.example.currencyconverterApp and select MainActivity.
First, you’ll find the onCreate method already created for you in the Main Activity Java file. This is code snippet for the onCreate method.
We now need to implement our very own convertToEuro method that we added to the button in activity_main.xml, as shown below.
Note:
In the int euro = 2000; bit of code, 2000 is just a variable you can change to any currency rate depending on the Currency Converter App you want to make.
The result/output will be displayed as a toast. You can as well show it on the Activity_main.xml interface as TextView by adding the code snippet below.
MainActivity.java
Add this code implementation in the Java file, MainActivity.
I hope this was helpful to all those who want to create a simple app in Android Studio. You can leave a comment in the section below if you any issues with the implementations.
Published at DZone with permission of Martin Tumusiime . See the original article here.
Opinions expressed by DZone contributors are their own.
Источник
Create real time currency converter app in Android Studio
In this tutorial, we will learn to create a Currency converter app in android using java. We can develop an app in android either using java or kotlin. To develop an android project we can either use Eclipse IDE or we can directly use Android Studio (any version). We will use: exchangeratesapi.io API key here.
For Eclipse IDE we need to download and install Android SDK and ADT plugin and Android version which is a very lengthy process. So instead of Eclipse IDE, the Android studio is preferred by most of the developers.
In this tutorial, we will use Android Studio 3.6.3 (latest version).
To create a new project in android studio: currency converter
- Click on the file option on the upper right corner of our android studio screen.
- After that, we can select a project template.
Android Studio Screen
3. On clicking on the next option we will get the screen to configure the project. Here we can select the name of our project, package name, location to store our project, language, and minimum SDK.
4. Click on the finish button.
Android studio screen
Start coding
In the above figure, there are two options
In MainActivity.java we will write our java code and activity_main.xml we will design the view of our app.
To design the view of our app we will get two option
- We can directly drag and drop the required tool to our emulator.
- Write an XML code to design the view of our application.
MainActivity.java
The name of our package is com.example.myapplication.
We generally use Bundle to pass the data between various activities of Android. We can map the data from the string value to various data types with the help of parsing using Bundle.
The view is the rectangular piece of the area at the front end of our application.
Array Adapter converts the Array List of objects into view items that can be loaded into a listview container.
AppCompat is the set of libraries that are used to develop the app with various versions. This means when a new version of the android studio gets released the appcompat helps us to work with old libraries from the new version.
Gson is called google JSON and JSON stands for javascript object notation. It is used to convert data to JSON or XML code. This means when we pass any data to gson it takes the java object and returns a corresponding JSON.
Retrofit is the HTTP client it helps to retrieve and upload JSON via web services.
Oncreate()
In the onCreate method of our project, we created objects of TextView, EditText, spinner, and button.
Then we created a drop-down list in which we passed the currencies of several countries.
Then in the onClick method of our project, we are converting the values from the currency of one country to the currency of any other country depending on the choice of the user. We are using the package that we created to implement the libraries and function of google JSON and Retrofit to convert our currency. We just passing the values and with the help of functionalities of retrofit and GSON that we created in the package, we are converting the currency.
The res.getAsJsonObject(“conversion_rates”) method helps us to get the rates to which we need to multiply the currency to get the required currency.
Further SetText is used to display the result obtained by multiplying the currency entered and the rate generated on the front end of the app.
KamalInterface
Retrofit makes downloading XML or JSON data from web API easier.
In the package kamal, we are creating an instance of retrofit in retrofitInterface.
We are using Exchange Rates-API
In the retrofit interface, 1929988978e7cd9733e5e654 is the key to our API used.V6 is the version of the API.
Just enter your email id to get the API key.
Method getExchangeCurrency(@Path(“currency”) String currency) is used to get the rate of exchange of the currency.
In the above method, the “currency” is used because we are selecting the currency from the drop-down menu. Instead of currency, we can also write “USD”, “EUR”, etc.
KamalBuild
In kamalBuild, we are creating the instance of Retrofit in which we are passing the base address of our API and addConvertFactory method.
To run our application we need to add these dependencies in the Gradle file of our project.
These dependencies are for version 29.
XML Code
We can modify the front end of our app according to our needs. We can add images, background colors, etc.
To add an image we need to download an image and save it in the drawable folder. From there we can add it to our ImageView from the src option.
We can even add audio to our app. For adding any audio file we need to create a raw folder in our app and then we can add the audio file to our app.
In the above XML code, first of all, we set Layout to LinearLayout.
ImageView helps us to display images.
EdiText helps us to take input from the user.
The button helps us to perform any operation with the help of any method mentioned in the onClick function.
Spinner helps us to display a drop-down menu.
Spinner is used for creating a drop-down menu. We can modify our spinner, Button, EditText TextView, etc in our XML code.
Modifying spinner, Button, EditText, TextView, etc means adding curves, changing color, and much more to give an impressive and attractive look to the app.
In the above XML code, we are just creating id of our image views, button, spinner, text view, and edit view. And adjusting them according to the view we want.
Источник