Fragment1을 로그인으로 사용하겠습니다.
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="30sp"
android:gravity="center"
android:textColor="@android:color/holo_blue_dark"
android:layout_marginTop="10dp"
android:text="Login"/>
<ImageView android:layout_width="match_parent" android:layout_height="170dp"
android:src="@drawable/login_icon"/>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/user_id"/>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content"
android:hint="Password"
android:password="true"
android:id="@+id/user_pw"/>
<Button android:layout_width="match_parent" android:layout_height="50dp"
android:text="Log in"
android:layout_margin="5dp"
android:id="@+id/btn_login"/>
</LinearLayout>
<ImageView>에 이미지는 무료 이미지 다운받아서 사용했습니다.
7,875,000+ free and premium vector icons, illustrations and 3D illustrations
Iconfinder is the world's largest marketplace for icons, illustrations and 3D illustrations in SVG, AI, and PNG format.
www.iconfinder.com
login 검색하고 사이드바 설정에서 Free 와 For commercial use 선택하고 맘에 드는 사진 다운받아 씁니다.
ApiService
@POST("/user/valid")
Call<UserDTO> login(@Body RequestBody body);
로그인 요청을 보낼 메서드입니다.
UserDTO
package com.example.fragmenexample;
public class UserDTO {
String id;
String password;
String name;
String birth;
public UserDTO(String id, String password, String name, String birth) {
this.id = id;
this.password = password;
this.name = name;
this.birth = birth;
}
public UserDTO(String id, String password){
this.id = id;
this.password = password;
}
}
id와 password만 사용하는 생성자를 만듭니다.
Fragment1
package com.example.fragmenexample;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.google.gson.Gson;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.jetbrains.annotations.NotNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Fragment1 extends Fragment {
private EditText user_id, user_pw;
private Button btn_login;
private ApiService apiService;
public Fragment1(){
}
@Nullable
@org.jetbrains.annotations.Nullable
@Override
public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
user_id = view.findViewById(R.id.user_id);
user_pw = view.findViewById(R.id.user_pw);
btn_login = view.findViewById(R.id.btn_login);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080")
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String id = user_id.getText().toString();
String pw = user_pw.getText().toString();
UserDTO dto = new UserDTO(id, pw);
Gson gson = new Gson();
String json = gson.toJson(dto);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
Call<UserDTO> call = apiService.login(requestBody);
call.enqueue(new Callback<UserDTO>() {
@Override
public void onResponse(Call<UserDTO> call, Response<UserDTO> response) {
if(response.isSuccessful()){
Toast.makeText(getContext(), "로그인 성공", Toast.LENGTH_SHORT).show();
FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment3 fragment3 = new Fragment3();
transaction.replace(R.id.frame, fragment3);
transaction.commit();
}else{
Toast.makeText(getContext(), "로그인 실패", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UserDTO> call, Throwable t) {
Log.e("네트워크 에러", t.getMessage());
Toast.makeText(getContext(), "네트워크 에러", Toast.LENGTH_SHORT).show();
}
});
}
});
return view;
}
}
Call 제네릭에 UserDTO가 아닌 타입이 들어가면 서버에서는 문제없이 돌아가지만 app에서 자꾸 네트워크 오류라고 나오고 예상한 json 형식이 아니란 메세지가 나옵니다. 결국 서버에서도 ReponseEntity에 userDTO타입으로 설정하고 Call 제네릭도 UserDTO로 하니까 잘 실행이 되었습니다.
회원가입과 어느정도 비슷하지만 이번엔 로그인 성공하면 FragmentManager를 통해서 fragment3을 보여주도록 했습니다.
requireActivity().getSupportFragmentManager()를 통해서 FragmentManager를 가져오고 FragmentTransaction 객체 생성 후 fragment3으로 교체합니다.
이제 결과를 봅시다.
'Android Studio' 카테고리의 다른 글
[Android Studio] 첫 안드로이드 앱 개발 시작해보기 - Service (11) (2) | 2023.11.09 |
---|---|
[Android Studio] 첫 안드로이드 앱 개발 시작해보기 - Thread, Dialog (10) (1) | 2023.11.08 |
[Android Studio] Android Studio + Spring Boot + mariaDB ( 회원가입 ) (2) (0) | 2023.11.06 |
[Android Studio] Android Studio + Spring Boot + mariaDB ( REST API 서버 구현 ) (9) (0) | 2023.11.06 |
[Android Studio] 첫 안드로이드 앱 개발 시작해보기 - Fragment (9) (0) | 2023.11.05 |