상세 컨텐츠

본문 제목

[안드로이드]빗썸 api 사용해서 해당 코인 체결내역 가져오기

안드로이드

by aries574 2020. 11. 6. 21:34

본문


2020/11/03 - [안드로이드] - [안드로이드]빗썸 api를 사용해서 현재가 정보 가져오기

2020/11/04 - [안드로이드] - [안드로이드]빗썸 api를 사용해서 현재 매도/매수 정보 가져오기

 

이번시간에는 해당 코인 체결내역을 가져오는걸 만들겠습니다. 아래는 빗썸 거래소에서 보여주는 체결내역입니다.

 

 

1. 환경설정app -> 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. 라이브러리 추가

Gradle Scripts -> build.gradle(Module:app)

implementation 'com.android.volley:dc-volley:1.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'


3. 클래스 추가(Java -> 마우스 오른쪽 -> New -> Java Class)

 

TransactionList.java

import java.util.ArrayList;

public class TransactionList {

    String status;
    ArrayList<TransactionVo> data = new ArrayList<TransactionVo>();

}

 

TransactionVo.java

public class TransactionVo {
    
    private String transaction_date; //체결시간
    private String type; //거래유형 bid:매수, ask:매도
    private String units_traded; //거래량
    private String price; //거래가
    private String total; //총거래금액

    public String getTransaction_date() {
        return transaction_date;
    }

    public void setTransaction_date(String transaction_date) {
        this.transaction_date = transaction_date;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUnits_traded() {
        return units_traded;
    }

    public void setUnits_traded(String units_traded) {
        this.units_traded = units_traded;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }
}

 

TransactionAdapter.java

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class TransactionAdapter extends RecyclerView.Adapter<TransactionAdapter.Viewholder>{

    ArrayList<TransactionVo> items = new ArrayList<TransactionVo>();

    @NonNull
    @Override
    public Viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View itemView = inflater.inflate(R.layout.transaction_item, viewGroup, false);

        return new Viewholder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull Viewholder viewHolder, int position) {

        TransactionVo item = items.get(position);
        viewHolder.setItem(item);
    }


    @Override
    public int getItemViewType(int position) {

        return super.getItemViewType(position);
    }

    //아이템 건수
    @Override
    public int getItemCount() {

        return items.size();
    }

    //아이템 등록
    public void addItem(TransactionVo coin){

        items.add(coin);
    }


    public void removeItem(int count){

        for(int i=0; i< count-1; i++){
            items.remove(i);
        }
    }

    /**
     * 아이템 전체삭제
     */
    public void removeAllItem(){
        items.clear();
    }


    //아이템 저장
    public void setItems(ArrayList<TransactionVo> items){

        this.items = items;
    }

    //아이템 조회
    public TransactionVo getItem(int position){

        return items.get(position);
    }


    static class Viewholder extends RecyclerView.ViewHolder{

        CardView cardView;
        TextView transaction_date;
        TextView price;
        TextView units_traded;
        TextView total;

        public Viewholder(@NonNull View itemView) {
            super(itemView);
            transaction_date    = itemView.findViewById(R.id.transaction_date);
            price                = itemView.findViewById(R.id.price);
            units_traded        = itemView.findViewById(R.id.units_traded);
            total               = itemView.findViewById(R.id.total);
            cardView            = itemView.findViewById(R.id.cardView);
        }

        public void setItem(TransactionVo orderBook){

            int position = getAdapterPosition();

            if(orderBook.getType().equals("bid")){ //매수 빨강
                cardView.setBackgroundColor(Color.rgb(255,162,162)); //옅은 빨강 아래랑

            }else{ //매도
                cardView.setBackgroundColor(Color.rgb(144,246,255)); // 옅은 파랑
            }

            transaction_date.setText(orderBook.getTransaction_date().substring(11,19));

            units_traded.setText(orderBook.getUnits_traded()+"개");
            price.setText(toDoubleFormat(Double.parseDouble(orderBook.getPrice()))+"원");
            total.setText(toDoubleFormat(Double.parseDouble(orderBook.getTotal()))+"원");
        }

        /**
         * 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);
        }
    }
}

 

4. 화면추가 ( res -> layout -> 마우스오른쪽 -> New -> Layout Resource File)

 

transaction_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="2dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="2dp"
        app:cardElevation="5dp"
        app:cardBackgroundColor="@android:color/darker_gray">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/transaction_date"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="거래시간"
                android:gravity="left"
                android:textColor="#0E0505"
                android:textStyle="bold"
                android:textSize="13sp" />

            <TextView
                android:id="@+id/price"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="right"
                android:text="가격"
                android:textStyle="bold"
                android:textColor="#0E0505"
                android:textSize="13sp" />

        </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/units_traded"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="right"
                    android:text="거래갯수"
                    android:textStyle="bold"
                    android:textColor="#0E0505"
                    android:textSize="13sp" />
                <TextView
                    android:id="@+id/total"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="총가격"
                    android:gravity="right"
                    android:textColor="#0E0505"
                    android:textStyle="bold"
                    android:textSize="13sp" />
            </LinearLayout>

        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

 

5. 화면구성(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>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

 

6. 기능구현(MainActivity.java)

 

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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.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.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private RequestQueue requestQueue; //호가
    private EditText coinNm;//입력창

    private RecyclerView recycleView;
    private TransactionAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //recycleView 객체참조
        recycleView = findViewById(R.id.recycleView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);

        //recycleView 레이아웃 설정
        recycleView.setLayoutManager(layoutManager);

        //recycleView 어뎁터 설정
        adapter = new TransactionAdapter();
        recycleView.setAdapter(adapter);

        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();
                }else{
                    //코인값 대문자처리
                    transactionHistorySelect(nm.toUpperCase());
                }
            }
        });


        if (requestQueue == null) { //호가
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }


    /**
     * 매수/매도 api호출
     * @param coinNm 코인명
     */
    private void transactionHistorySelect(String coinNm)
    {
        final String coinName = coinNm;

        String url = "https://api.bithumb.com/public/transaction_history/"+coinNm;
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        transactionResponse(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 transactionResponse(String response) {

        Gson gson = new Gson();
        TransactionList transactionList = gson.fromJson(response, TransactionList.class);

        //상태값이 성공일때만 데이터 뿌려주기
        if(transactionList.status.equals("0000"))
        {

            //조회 전 화면 클리어
            adapter.removeAllItem();
            
            for(int i = 0; i < transactionList.data.size(); i++){

                TransactionVo vo = transactionList.data.get(i);
                adapter.addItem(vo);
            }
            
            adapter.notifyDataSetChanged(); //변경사항 적용
        }
    }

    /**
     * 로그 표시
     * @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();
    }

}

7. 구동화면

코인명을 입력하고 조회버튼을 누르면 해당코인 현재 체결내역을 가져옵니다.

매도는 파란색, 매수는 빨간색으로 표시했습니다.



반응형

관련글 더보기

댓글 영역