빗썸거래소에서는 외부 개발자 및 사용자들이 쉽게 이용하여
서비스 및 애플리케이션을 개발할 수 있도록 api를 제공합니다.
이번 시간에는 해당 코인을 조회해서 현재가 정보를 가져오는
어플리케이션을 만들어 보려고 합니다.
현재가 정보를 어떻게 가져오고 어떻게 화면에 보여주는지에 대해서 알아보려고 합니다.
1. 환경설정
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kwon.coin">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
</manifest>
2. 라이브러리 추가
build.gradle(Module:app)
implementation 'com.android.volley:dc-volley:1.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
3. 클래스 추가
import java.util.HashMap;
public class CoinList {
HashMap<String , String> data = new HashMap<String, String>();
String status;
}
4. 화면구성(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/coin_nm"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="text"
/>
<Button
android:id="@+id/btn_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="현재가 조회" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="시가:"
/>
<TextView
android:id="@+id/opening_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="종가:"
/>
<TextView
android:id="@+id/closing_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="저가:"
/>
<TextView
android:id="@+id/min_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="고가:"
/>
<TextView
android:id="@+id/max_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="거래량:"
/>
<TextView
android:id="@+id/units_traded"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="거래금액:"
/>
<TextView
android:id="@+id/acc_trade_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="전일종가:"
/>
<TextView
android:id="@+id/prev_closing_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="최근24시간 거래량:"
/>
<TextView
android:id="@+id/units_traded_24H"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="최근 24시간 거래금액:"
/>
<TextView
android:id="@+id/acc_trade_value_24H"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="최근24시간 변동가:"
/>
<TextView
android:id="@+id/fluctate_24H"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="최근24시간 변동율:"
/>
<TextView
android:id="@+id/fluctate_rate_24H"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
5. 기능구현(MainActivity.java)
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue; //호가
private TextView opening_price;
private TextView closing_price;
private TextView min_price;
private TextView max_price;
private TextView units_traded;
private TextView acc_trade_value;
private TextView prev_closing_price;
private TextView units_traded_24H;
private TextView acc_trade_value_24H;
private TextView fluctate_24H;
private TextView fluctate_rate_24H;
private EditText coinNm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
opening_price = findViewById(R.id.opening_price);
closing_price = findViewById(R.id.closing_price);
min_price = findViewById(R.id.min_price);
max_price = findViewById(R.id.max_price);
units_traded = findViewById(R.id.units_traded);
acc_trade_value = findViewById(R.id.acc_trade_value);
prev_closing_price = findViewById(R.id.prev_closing_price);
units_traded_24H = findViewById(R.id.units_traded_24H);
acc_trade_value_24H = findViewById(R.id.acc_trade_value_24H);
fluctate_24H = findViewById(R.id.fluctate_24H);
fluctate_rate_24H = findViewById(R.id.fluctate_rate_24H);
coinNm = findViewById(R.id.coin_nm);
Button btnSearch = findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//입력값 변수에 담기
String nm = coinNm.getText().toString();
//입력값 체크
if(nm.equals("") || nm == null){
Toast.makeText(getApplication(), "코인이름을 입력해주세요", Toast.LENGTH_SHORT).show();
// println("없다");
}else{
//코인값 대문자처리
orderbookSelect(nm.toUpperCase());
}
}
});
if (requestQueue == null) { //호가
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
}
/**
* 호가정보 api호출
* @param coinNm 코인명
*/
private void orderbookSelect(String coinNm)
{
final String coinName = coinNm;
String url = "https://api.bithumb.com/public/ticker/"+coinNm;
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// println("응답->" + response);
orderBookResponse(response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
println("에러->" + error.getMessage());
customToastView("에러!!!");
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
request.setShouldCache(false);
requestQueue.add(request);
}
/**
* 호가 데이터 정렬
* @param response 호가정보
*/
private void orderBookResponse(String response) {
Gson gson = new Gson();
CoinList coinInfo = gson.fromJson(response, CoinList.class);
//상태값이 성공일때만 데이터 뿌려주기
if(coinInfo.status.equals("0000"))
{
String openingPrice = coinInfo.data.get("opening_price");
String closingPrice = coinInfo.data.get("closing_price");
String minPrice = coinInfo.data.get("min_price");
String maxPrice = coinInfo.data.get("max_price");
String unitsTraded = coinInfo.data.get("units_traded");
String accTradeValue = coinInfo.data.get("acc_trade_value");
String prevClosingPrice = coinInfo.data.get("prev_closing_price");
String unitsTraded24h = coinInfo.data.get("units_traded_24H");
String accTradeValue24h = coinInfo.data.get("acc_trade_value_24H");
String fluctate24h = coinInfo.data.get("fluctate_24H");
String fluctateRate24h = coinInfo.data.get("fluctate_rate_24H");
//텍스트에 데이터 담기
opening_price.setText(toDoubleFormat(Double.parseDouble(openingPrice))+"원");
closing_price.setText(toDoubleFormat(Double.parseDouble(closingPrice))+"원");
min_price.setText(toDoubleFormat(Double.parseDouble(minPrice))+"원");
max_price.setText(toDoubleFormat(Double.parseDouble(maxPrice))+"원");
units_traded.setText(toDoubleFormat(Double.parseDouble(unitsTraded))+"개");
acc_trade_value.setText(toDoubleFormat(Double.parseDouble(accTradeValue))+"개");
prev_closing_price.setText(toDoubleFormat(Double.parseDouble(prevClosingPrice))+"원");
units_traded_24H.setText(toDoubleFormat(Double.parseDouble(unitsTraded24h))+"개");
acc_trade_value_24H.setText(toDoubleFormat(Double.parseDouble(accTradeValue24h))+"원");
fluctate_24H.setText(toDoubleFormat(Double.parseDouble(fluctate24h))+"원");
fluctate_rate_24H.setText(toDoubleFormat(Double.parseDouble(fluctateRate24h))+"%");
}
}
/**
* 로그 표시
* @param data 로그
*/
private void println( String data)
{
Log.d("MainActivity" , data);
}
/**
* 커스터마이징 메시지
* @param text
*/
private void customToastView(String text){
Toast toastView = Toast.makeText(getApplication(),text, Toast.LENGTH_SHORT);
toastView.setGravity(Gravity.CENTER,0,0);
toastView.show();
}
/**
* 1000자리 콤마
* @param num
* @return
*/
public String toDoubleFormat(Double num) {
DecimalFormat df = null;
if(num >= 100 && num <= 999.9){
df = new DecimalFormat("000.0");
}else if(num >= 10 && num <= 99.99){
df = new DecimalFormat("00.00");
}else if(num >= 1 && num <= 9.9999){
df = new DecimalFormat("0.000");
}else if(num < 1){
df = new DecimalFormat("0.0000");
}else{
df = new DecimalFormat("###,###,###");
}
return df.format(num);
}
}
6. 구동화면
코인명을 입력하고 현재가 조회버튼을 누르면 현재가 정보를 가져옵니다.
[안드로이드]빗썸 api 사용해서 해당 코인 체결내역 가져오기 (0) | 2020.11.06 |
---|---|
[안드로이드]빗썸 api를 사용해서 현재 매도/매수 정보 가져오기 (0) | 2020.11.04 |
[안드로이드] 밀어서 화면변경 뷰페이저(View Pager) (0) | 2020.10.30 |
[안드로이드]텍스트뷰(TextView) 동적생성 (0) | 2020.06.24 |
[안드로이드]포그라운드 서비스(Foreground Service) 죽지않는 서비스& 스레드(Thread) (4) | 2020.06.17 |
댓글 영역