여러 앱에서 필수적인 기능인 로그인 기능을 구현하겠습니다. 버터나이프라는 좋은 모듈을 사용할 것입니다. 버터나이프는 안드로이드에서 view에 쉽게 접근할 수 있게 해 줍니다. 

butterknife : http://jakewharton.github.io/butterknife/


1. 레이아웃 불러오기

먼저 레이아웃에서 로그인 아이디값, 비밀번호값 등을 가져오기 전에 그 값들을 저장할 데이터 모델과 그 모델을 처리할 apiService를 불러오겠습니다.


import com.example.keepair.myapplication.apiservice.LoginApiService;
import com.example.keepair.myapplication.helper.Constants;
import com.example.keepair.myapplication.loginhelper.ReferSharedPreference;
import com.example.keepair.myapplication.model.LoginData;
import com.example.keepair.myapplication.model.MyKey;
cs

여기서 ReferSharedPreference는 나중에 살펴볼 것입니다. 지금은 자동 로그인을 위한 SharedPreference 라고 알고 넘어가면 될 것 같습니다. SharedPreference는 안드로이드에서 유용하게 사용되는 저장 도구입니다. 앞서 말한대로 버터나이프 모듈을 쓸 것이니 그것도 가져와줍니다.


import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
cs

그 다음 값을 담을 변수들을 정합니다.


    MyKey keygiven;
    LoginApiService loginApiService;
    @Bind(R.id.usernameTextField)
    EditText mUsernameTextField;
    @Bind(R.id.passwordTextField)
    EditText mPasswordTextField;
    @Bind(R.id.loginButton)
    ImageView mLoginButton;
    @Bind(R.id.btn_start_RegistrationActivity)
    ImageView mStartRegistrationButton;
    @Bind(R.id.layout_Login)
    RelativeLayout mLayoutLogin;
    ReferSharedPreference mSavedUserInfo;
cs

@Bind가 butterknife의 역할입니다. @Bind를 통해 길던 코드가 매우 짧아졌습니다. butterknife를 쓰는 사람들은 이 간결함을 선호합니다.


2. 함수 지정

onCreate를 설정하겠습니다. onCreate는 생성될 때의 옵션을 의미합니다. 화면이 만들어질 때부터 기능할 수 있는 부분을 정하게 됩니다.


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
 
        mSavedUserInfo = new ReferSharedPreference(getApplicationContext());
 
        mUsernameTextField.setText(mSavedUserInfo.getValue("SavedUserName"""));
        mPasswordTextField.setText(mSavedUserInfo.getValue("SavedPassword"""));
    }
cs

mSavedUserInfo가 없다면 새로운 값을 가져오게 되는 것입니다. 새로운 값을 가져올 때는 레이아웃에서 값을 가져와보고, 레이아웃에서 값이 존재하지 않는다면 "" 값을 가져옵니다. 빈 텍스트를 가져오게 됩니다. 저장된 값들은 SharedPreference에서 존재합니다.

 

등록 버튼을 눌렀을 때 새로운 RegisterActivity가 생성되도록 intent를 만들겠습니다.

로그인 화면이 있고 로그인 화면에서 등록 버튼을 눌러 사용자 등록을 위한 화면을 생성하는 구조입니다.


    @OnClick(R.id.btn_start_RegistrationActivity)
    public void onClickToStartRegistration(View view){
        Intent intent = new Intent(LoginActivity.this, RegistrationActivity.class);
        startActivity(intent);
    }
cs

로그인 버튼을 구현합니다. @onClick을 butterknife를 이용해 만듭니다. @onClick도 butterknife에서 제공되는 유용한 도구입니다.


    @OnClick(R.id.loginButton)
    public void onClick(View view) {
    }
cs

이제 여기 안에 내용을 채우면 됩니다.

우선 사용자가 작성한 값들을 레이아웃으로부터 가져옵니다.


        final String givenUserName = mUsernameTextField.getText().toString();
        String givenEmail = "";
        final String givenPassword = mPasswordTextField.getText().toString();
        LoginData loginData = new LoginData(givenUserName, givenPassword, givenEmail);
cs


Okhttp3를 이용해서 로깅을 조절합니다. header랑 body를 지정합니다. 이걸 통해 http가 어떻게 통신되는지 확인할 수 있습니다.


        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
 
cs

로그인에 이용할 Retrofit을 불러올 것입니다.  Retrofit는 나중에 살펴볼 비동기 통신 도구입니다. 사전작업을 하겠습니다.

client라는 변수에 okHttpClient() 값을 넣어줍니다.


        OkHttpClient client = new OkHttpClient();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.interceptors().add(logging);
 
        client = builder.build();
 
        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constants.BASE_URL)
                .build();
cs


이제 직접적으로 서버와 통신할 Call부분을 만듭니다.

Call부분은 이렇게 성공한 경우와 실패한 경우를 나눠서 대응할 수 있습니다. 서버와의 통신에 성공하면 response.isSuccessful()이 호출되고 그렇지 않다면 onFailure()가 호출될 것입니다.

 
        loginApiService = retrofit.create(LoginApiService.class);
        Call<MyKey> getget = loginApiService.getget(loginData);
        getget.enqueue(new Callback<MyKey>() {
            @Override
            public void onResponse(Call<MyKey> call, Response<MyKey> response) {
                if (response.isSuccessful()) {
                }
                else {
                    Toast.makeText(getApplicationContext(),"Failed", Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onFailure(Call<MyKey> call, Throwable t) {
            }
        });
cs

실패한다면 별 반응이 없어도 되지만 성공한다면 로그인 이후의 반응을 작성해야합니다.


                    keygiven = response.body();
 
                    Toast.makeText(getApplicationContext(),"We waited you, " + givenUserName, Toast.LENGTH_LONG).show();
 
                    mSavedUserInfo.put("SavedUserName", givenUserName);
                    mSavedUserInfo.put("SavedPassword", givenPassword);
 
                    ReferSharedPreference givenToken = new ReferSharedPreference(getApplicationContext());
                    givenToken.put("Token""Token "+ keygiven.getKey());
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
cs


이렇게 하면 통신에 성공했을 때 로그인을 하여 startActivity를 실행하게 됩니다.

실패하게 되면 간단히 Toast만 띄워줍니다.


                    Toast.makeText(getApplicationContext(),"Failed", Toast.LENGTH_LONG).show();
cs


LoginActivity를 간단하게 만들어 보았습니다.

+ Recent posts