반응형

 

< MainActivity.java >

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
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.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private String userName = "UserName";
    private String repositoryName = "RepositoryName";
    private final String textPrefix = "https://api.github.com/repos/";
    private final String textSuffix = "/issues";

    private final int SEND_REQUEST = 1;
    private final int SEND_REQUEST_DURATION = 3000;

    private EditText userNameEditText;
    private EditText repositoryNameEditText;
    private TextView resultUrlText;
    private TextView resultText;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            sendRequest(resultUrlText.getText().toString());
            return false;
        }
    });

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

        initializeView();
        initializeViewListener();

        // 리퀘스트 큐가 없으면 리퀘스트 생성
        if(AppHelper.requestQueue ==  null) {
            AppHelper.requestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        resultUrlText.setText(textPrefix + userName + "/" + repositoryName + textSuffix);
    }

    // url로 리퀘스트를 보내는 메서드 지금은 Get으로 보낸다.
    public void sendRequest(String url) {
        StringRequest request = new StringRequest(
            Request.Method.GET,
            url,
            // Response가 왔을 때 처리하는 구문
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    resultText.setText(response);
                    System.out.println(response);
                }
            },
            // Error일때 처리하는 구문
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    resultText.setText(error.getMessage());
                }
            }
        ) { // 해당 내용을 통해 파라미터를 넘겨줄 수 있다.
            @Override
            protected Map<String, String> getParams() {
                return new HashMap<>();
            }
        };

        // 캐싱하지 않도록 설정
        request.setShouldCache(false);

        AppHelper.requestQueue.add(request);
    }

    private void initializeView() {
        userNameEditText = findViewById(R.id.user_name_edit_text);
        repositoryNameEditText = findViewById(R.id.repository_name_edit_text);
        resultUrlText = findViewById(R.id.result_url_text);
        resultText = findViewById(R.id.result_text);
    }

    private void initializeViewListener() {
        userNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                userName = charSequence.toString();
                resultUrlText.setText(textPrefix + userName + "/" + repositoryName + textSuffix);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        repositoryNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                repositoryName = charSequence.toString();
                resultUrlText.setText(textPrefix + userName + "/" + repositoryName + textSuffix);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        resultUrlText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            // 3초가 지나야 입력한 데이터로 리퀘스트 요청을 실행
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(handler.hasMessages(SEND_REQUEST)) {
                    handler.removeMessages(SEND_REQUEST);
                }
                handler.sendEmptyMessageDelayed(SEND_REQUEST, SEND_REQUEST_DURATION);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
}

 

< AppHelper.java>

package com.example.myapplication;

import com.android.volley.RequestQueue;

public class AppHelper {
    public static RequestQueue requestQueue;
}

 

 

< activity_main.xml >

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <LinearLayout
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center">
        <TextView
            android:id="@+id/result_url_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:textSize="23dp"/>
        <EditText
            android:id="@+id/user_name_edit_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="User Name"
            android:textSize="20dp"/>
        <EditText
            android:id="@+id/repository_name_edit_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="Repository Name"
            android:textSize="20dp"/>

        <TextView
            android:id="@+id/result_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:scrollbars="vertical"
            android:textSize="23dp"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 

반응형