Android

서버에 데이터를 저장, 수정, 삭제하는 경우 사용하는 코드 (SharedPreferences에 저장하기)

567Rabbit 2024. 6. 13. 15:36

https://codebunny99.tistory.com/170

 

메모 앱 app (회원가입, 로그인 기능) Retrofit 라이브러리로 만들기

Restful API를 MySQL과 연동하여 Postman으로 개발한 후, 진행하였다.     액티비티 세 개 만들기   환경변수 설정하기Retrofit 라이브러리 설치하기 build.gradle.kts(:app)에서implementation("com.squareup.retrofi

codebunny99.tistory.com

 

 

------------------------------------------------------------------------------------------------------------------------------------------------

 

결론 요약하기

 

onCreate 함수 안에 서버에 데이터를 저장,수정, 삭제하는 경우 사용하는 코드를 작성해주고,

// 서버에 데이터를 저장하거나, 수정하거나, 삭제하는 경우에 사용하는 코드

Dialog dialog;

    void showProgress(){
        dialog = new Dialog(this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(new ProgressBar(this));
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
    
    void dismissProgress(){
        dialog.dismiss();
    }

 

 

Call call = api.register(user); 를 통해서, api 함수를 만들고,

 

api를 호출하는 과정에서 Call<UserRes> 의 accessToken(액세스 토큰)을 호출하고,

 

아래와 같이 서버로부터 받은 토큰을 저장하는 코드를 작성하는 과정을 거치면 된다.

 

SharedPreferences sp = getSharedPreferences(Config.SP_NAME,MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("token", userRes.accessToken);
editor.commit(); //앱을 삭제하기 전까지는 영구저장해준다

 

 

------------------------------------------------------------------------------------------------------------------------------------------------

 

 

RegisterActivity.java 클래스

 

onCreate 함수 안에 작성해준다

// 서버에 데이터를 저장하거나, 수정하거나, 삭제하는 경우에 사용하는 코드

Dialog dialog;

    void showProgress(){
        dialog = new Dialog(this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(new ProgressBar(this));
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
    
    void dismissProgress(){
        dialog.dismiss();
    }

 

 

 

서버로 부터 받은 토큰을 저장하는 코드이다.

    // 회원가입 API를 호출한다.

    // 0. 다이얼로그를 보여준다.
    showProgress();

    // 1. 레트로핏 변수 생성 : api 패키지에 NetworkClient.java 파일이 있어야 한다.
    Retrofit retrofit = NetworkClient.getRetrofitClient(RegisterActivity.this);

    // 2. api 패키지에 있는 인터페이스를 객체로 생성 : api 패키지에 인터페이스가 있어야 한다.
    UserApi api = retrofit.create(UserApi.class);

    // 3. 보낼 데이터를 만든다.
    User user = new User(email, password, nickname);

    // 4. api 함수를 만든다.
    Call<UserRes> call = api.register(user);

    // 5. api를 호출한다.
    call.enqueue(new Callback<UserRes>() {
        @Override
        public void onResponse(Call<UserRes> call, Response<UserRes> response) {
            Log.i("MEMO REGISTER", ""+response.code());

            //다이얼로그를 먼저 없앤다.
            dismissProgress();

            // 200 OK 일때,
            if(response.isSuccessful()){

                UserRes userRes = response.body();
                Log.i("MEMO REGISTER",userRes.accessToken);

                // 서버로부터 받은 토큰을 저장해야 한다.
                SharedPreferences sp = getSharedPreferences(Config.SP_NAME,MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("token", userRes.accessToken);
                editor.commit(); //앱을 삭제하기 전까지는 영구저장해준다

                // 회원가입 액티비티는 종료를 하고 메인액티비티띄운다.
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;


            }else if(response.code() == 500){
                Snackbar.make(btnRegister, "이미 회원가입한 이메일입니다. 로그인하세요.",
                        Snackbar.LENGTH_SHORT).show();
                return;
            }else {
                Snackbar.make(btnRegister, "서버에 문제가 있습니다. 잠시 후 다시 시도하세요.",
                        Snackbar.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<UserRes> call, Throwable throwable) {
            //다이얼로그를 먼저 없앤다.
            dismissProgress();

        }
    });

 

 

 

api

- api는 다음과 같이 작성하였다

 

- UserApi

package com.~.memo.api;

import com.~.memo.model.User;
import com.~.memo.model.UserRes;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface UserApi {  //인터페이스로 바꿔준다.

    // HTTP Method 써주고, 그 안에는 경로를 써준다.
    // 함수의 리턴 데이터 타입은, Call 안에 응답으로 받을 클래스를 넣어준다.
    // 함수명을 작성해주고, 보낼 데이터는 파라미터에 작성, 받을 데이터는 리턴에 작성.
    @POST("/dev/user/register")
    Call<UserRes> register(@Body User user);

 

 

- UserRes

package com.~.memo.model;

public class UserRes {

    public String result;
    public String accessToken;
}