다음 게시물을 참고해, 메인액티비티와 회원가입과 로그인 화면과 Activity를 만들고, config, string을 작성해준다.
https://codebunny99.tistory.com/170
config의 도메인 주소는,
포스팅 API를 만든 vscode를 sls deploy 해준 후, 나온 endpoint 주소로 하였다
https://codebunny99.tistory.com/117
포스트맨에서도 도메인 주소로 잘 실행되는지 점검한 후 진행하였다.
API 만들기
NetworkClient
package com.~.postingapp.api;
import android.content.Context;
import com.~.postingapp.config.Config;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class NetworkClient {
public static Retrofit retrofit;
public static Retrofit getRetrofitClient(Context context){
if(retrofit == null){
// 통신 로그 확인할때 필요한 코드
HttpLoggingInterceptor loggingInterceptor =
new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// 네트워크 연결관련 코드
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.addInterceptor(loggingInterceptor)
.build();
// 네트워크로 데이터를 보내고 받는
// 레트로핏 라이브러리 관련 코드
retrofit = new Retrofit.Builder()
.baseUrl(Config.DOMAIN)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
UserApi
package com.~.postingapp.api;
import com.~.postingapp.model.User;
import com.~.postingapp.model.UserRes;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface UserApi {
// 회원가입 API
// 함수명을 작성해주고, 보낼 데이터는 파라미터에 작성, 받을 데이터는 리턴타입에 작성.
@POST("/user/register")
Call<UserRes> register(@Body User user);
// 로그인 API
@POST("/user/login")
Call<UserRes> login(@Body User user);
// 로그아웃 API
@DELETE("/user/logout")
Call<UserRes> logout(@Header("Authorization") String token);
}
model 패키지 User, UserRes 클래스 만들기
fileprovider.xml 파일 생성 후 작성
- 카메라와 앨범 처리를 위한 코드이다.
<?xml version="1.0" encoding="utf-8"?>
<paths>
<root-path
name="root"
path="." />
<cache-path
name="cache"
path="." /> <!--Context.getCacheDir() 내부 저장소-->
<files-path
name="files"
path="." /> <!--Context.getFilesDir() 내부 저장소-->
<external-path
name="external"
path="."/> <!-- Environment.getExternalStorageDirectory() 외부 저장소-->
<external-cache-path
name="external-cache"
path="."/> <!-- Context.getExternalCacheDir() 외부 저장소-->
<external-files-path
name="images"
path="Pictures" /> <!-- Context.getExternalFilesDir() 외부 저장소-->
</paths>
AndroidManifest.xml 설정
- 환경설정 하기
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.camera" android:required="true"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
검정색으로 지운 부분은, 자동완성 될 것이다.
<provider
android:authorities="com.~.cameraapp.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/fileprovider"/>
</provider>
라이브러리 설치
build.gradle.kts(:app) 에서, 맨 아랫줄 작성.
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.squareup.retrofit2:converter-gson:2.11.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("com.github.bumptech.glide:glide:4.16.0")
implementation("commons-io:commons-io:2.4")
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:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/button" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:text="포스팅 생성"
android:textSize="24sp" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Activity 만들어서, activity_add.xml, AddActivity.java 작성하기
화면 작성
<?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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddActivity">
<ImageView
android:id="@+id/imgPhoto"
android:layout_width="227dp"
android:layout_height="235dp"
android:layout_marginStart="80dp"
android:layout_marginTop="96dp"
android:layout_marginEnd="80dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/add_photo" />
<Button
android:id="@+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="10dp"
android:text="포스트 생성"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editContent" />
<EditText
android:id="@+id/editContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="36dp"
android:layout_marginEnd="10dp"
android:ems="10"
android:hint="내용 입력..."
android:inputType="text"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imgPhoto" />
</androidx.constraintlayout.widget.ConstraintLayout>
Addactivity.java
- 화면과 연결하고 로직을 작성하고 카메라, 앨범을 사용하기 위한 코드를 작성하였다.
package com.~.postingapp;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.google.android.material.snackbar.Snackbar;
import com.~.postingapp.api.NetworkClient;
import com.~.postingapp.api.PostingApi;
import com.~.postingapp.config.Config;
import com.~.postingapp.model.Res;
import android.Manifest;
import org.apache.commons.io.IOUtils;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class AddActivity extends AppCompatActivity {
ImageView imgPhoto;
EditText editContent;
Button btnSave;
File photoFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
imgPhoto = findViewById(R.id.imgPhoto);
editContent = findViewById(R.id.editContent);
btnSave = findViewById(R.id.btnSave);
// 버튼 누르면, 카메라로 찍을것인지, 앨범에서 고를것인지에 대한
// 알러트 다이얼로그 띄운다.
imgPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 파일이 있어야 하고 내용이 있어야 한다
String content = editContent.getText().toString().trim();
if(content.isEmpty() || photoFile == null){
Snackbar.make(btnSave, "사진과 내용은 필수항목입니다",Snackbar.LENGTH_SHORT).show();
return;
}
// 레트로핏 라이브러리 이용해서 네트워크로 호출한다.
showProgress();
Retrofit retrofit = NetworkClient.getRetrofitClient(AddActivity.this);
PostingApi api = retrofit.create(PostingApi.class);
SharedPreferences sp = getSharedPreferences(Config.SP_NAME, MODE_PRIVATE);
String token = sp.getString("token","");
// 보낼 이미지 파일 만들기
RequestBody fileBody = RequestBody.create(photoFile, MediaType.parse("image/jpeg"));
MultipartBody.Part image = MultipartBody.Part.createFormData("image", photoFile.getName(), fileBody);
// 보낼 텍스트(content) 만들기
RequestBody textBody = RequestBody.create(content, MediaType.parse("text/plain"));
Call<Res> call = api.addPosting("Bearer " + token, image, textBody);
call.enqueue(new Callback<Res>() {
@Override
public void onResponse(Call<Res> call, Response<Res> response) {
dismissProgress();
if(response.isSuccessful()){
Snackbar.make(btnSave, "잘 저장되었습니다.", Snackbar.LENGTH_SHORT).show();
finish();
} else {
}
}
@Override
public void onFailure(Call<Res> call, Throwable throwable) {
dismissProgress();
}
});
}
});
}
private void showDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(AddActivity.this);
builder.setTitle(R.string.alert_title);
builder.setItems(R.array.alert_photo, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
// 첫번째 항목 눌렀을때
// 카메라로 사진찍기
camera();
}else if(i == 1){
// 두번째 항목 눌렀을때
album();
}
}
});
builder.show();
}
private void camera(){
int permissionCheck = ContextCompat.checkSelfPermission(
AddActivity.this, Manifest.permission.CAMERA);
if(permissionCheck != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(AddActivity.this,
new String[]{android.Manifest.permission.CAMERA} ,
1000);
Toast.makeText(AddActivity.this, "카메라 권한 필요합니다.",
Toast.LENGTH_SHORT).show();
return;
} else {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(i.resolveActivity(AddActivity.this.getPackageManager()) != null ){
// 사진의 파일명을 만들기
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
photoFile = getPhotoFile(fileName);
Uri fileProvider = FileProvider.getUriForFile(AddActivity.this,Config.FILE_PROVIDER,photoFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider);
startActivityForResult(i, 100);
} else{
Toast.makeText(AddActivity.this, "이폰에는 카메라 앱이 없습니다.",
Toast.LENGTH_SHORT).show();
}
}
}
private void album(){
if(checkPermission()){
displayFileChoose();
}else{
requestPermission();
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(AddActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result == PackageManager.PERMISSION_DENIED){
return false;
}else{
return true;
}
}
private void requestPermission() {
if(ActivityCompat.shouldShowRequestPermissionRationale(AddActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Log.i("DEBUGGING5", "true");
Toast.makeText(AddActivity.this, "권한 수락이 필요합니다.",
Toast.LENGTH_SHORT).show();
}else{
Log.i("DEBUGGING6", "false");
ActivityCompat.requestPermissions(AddActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 500);
}
}
private void displayFileChoose() {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "SELECT IMAGE"), 300);
}
private File getPhotoFile(String fileName) {
File storageDirectory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try{
return File.createTempFile(fileName, ".jpg", storageDirectory);
}catch (IOException e){
e.printStackTrace();
return null;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AddActivity.this, "권한 허가 되었음",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddActivity.this, "아직 승인하지 않았음",
Toast.LENGTH_SHORT).show();
}
break;
}
case 500: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AddActivity.this, "권한 허가 되었음",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddActivity.this, "아직 승인하지 않았음",
Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 100 && resultCode == RESULT_OK){
Bitmap photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
ExifInterface exif = null;
try {
exif = new ExifInterface(photoFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
photo = rotateBitmap(photo, orientation);
// 압축시킨다. 해상도 낮춰서
OutputStream os;
try {
os = new FileOutputStream(photoFile);
photo.compress(Bitmap.CompressFormat.JPEG, 20, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
imgPhoto.setImageBitmap(photo);
imgPhoto.setScaleType(ImageView.ScaleType.CENTER_CROP);
// 네트워크로 데이터 보낸다.
}else if(requestCode == 300 && resultCode == RESULT_OK && data != null &&
data.getData() != null){
Uri albumUri = data.getData( );
String fileName = getFileName( albumUri );
try {
ParcelFileDescriptor parcelFileDescriptor = getContentResolver( ).openFileDescriptor( albumUri, "r" );
if ( parcelFileDescriptor == null ) return;
FileInputStream inputStream = new FileInputStream( parcelFileDescriptor.getFileDescriptor( ) );
photoFile = new File( this.getCacheDir( ), fileName );
FileOutputStream outputStream = new FileOutputStream( photoFile );
IOUtils.copy( inputStream, outputStream );
// //임시파일 생성
// File file = createImgCacheFile( );
// String cacheFilePath = file.getAbsolutePath( );
// 압축시킨다. 해상도 낮춰서
Bitmap photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
OutputStream os;
try {
os = new FileOutputStream(photoFile);
photo.compress(Bitmap.CompressFormat.JPEG, 20, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
imgPhoto.setImageBitmap(photo);
imgPhoto.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
// imageView.setImageBitmap( getBitmapAlbum( imageView, albumUri ) );
} catch ( Exception e ) {
e.printStackTrace( );
}
// 네트워크로 보낸다.
}
super.onActivityResult(requestCode, resultCode, data);
}
//앨범에서 선택한 사진이름 가져오기
public String getFileName( Uri uri ) {
Cursor cursor = getContentResolver( ).query( uri, null, null, null, null );
try {
if ( cursor == null ) return null;
cursor.moveToFirst( );
@SuppressLint("Range") String fileName = cursor.getString( cursor.getColumnIndex( OpenableColumns.DISPLAY_NAME ) );
cursor.close( );
return fileName;
} catch ( Exception e ) {
e.printStackTrace( );
cursor.close( );
return null;
}
}
public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
// 서버에 데이터를 저장하거나, 수정하거나, 삭제하는 경우에 사용한다!
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();
}
}
PostingApi 클래스 만들기
package com.~.postingapp.api;
import com.~.postingapp.model.Res;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface PostingApi {
@POST("/posting")
Call<Res> addPosting(@Header("Authorization") String token,
@Part MultipartBody.Part image, //파트로 나눠서 보내라 용량 크므로
@Part("content")RequestBody content);
}
@Part MultipartBody
- Retrofit 라이브러리를 사용하여 멀티파트 파일 업로드를 구현할 때 사용되는 애노테이션이다.
- 이를 통해 파일 및 데이터를 서버로 전송할 수 있다.
Res 클래스 만들기
activity_row 만들기
<?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"
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="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/imgPhoto"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="4"
app:srcCompat="@drawable/add_photo" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="5"
android:orientation="vertical">
<TextView
android:id="@+id/txtContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#000000"
android:textSize="23sp" />
<TextView
android:id="@+id/txtEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#000000"
android:textSize="23sp" />
<TextView
android:id="@+id/txtCreatedAt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#000000"
android:textSize="23sp" />
<ImageView
android:id="@+id/imgLike"
android:src="@drawable/like_24dp"
android:layout_width="35dp"
android:layout_height="35dp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
MainActivity. java 작성
package com.~.postingapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.~.postingapp.adapter.PostingAdapter;
import com.~.postingapp.api.NetworkClient;
import com.~.postingapp.api.PostingApi;
import com.~.postingapp.config.Config;
import com.~.postingapp.model.Posting;
import com.~.postingapp.model.PostingList;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
Button btnAdd;
RecyclerView recyclerView;
ArrayList<Posting> postingArrayList = new ArrayList<>();
PostingAdapter adapter;
String token;
// 페이징 처리에 필요한 멤버 변수들!!
int offset = 0;
int limit = 5;
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences(Config.SP_NAME, MODE_PRIVATE);
token = sp.getString("token", "");
if(token.isEmpty()){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
return;
}
progressBar = findViewById(R.id.progressBar);
btnAdd = findViewById(R.id.btnAdd);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int lastPosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
int totalCount = recyclerView.getAdapter().getItemCount();
if(lastPosition + 1 == totalCount){
if(count == limit){
// 데이터를 추가로 요청한다.
addNetworkData();
}
}
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
private void addNetworkData() {
progressBar.setVisibility(View.VISIBLE);
Retrofit retrofit = NetworkClient.getRetrofitClient(MainActivity.this);
PostingApi api = retrofit.create(PostingApi.class);
Call<PostingList> call = api.getPostingList("Bearer " + token, offset, limit );
call.enqueue(new Callback<PostingList>() {
@Override
public void onResponse(Call<PostingList> call, Response<PostingList> response) {
progressBar.setVisibility(View.GONE);
if(response.isSuccessful()){
PostingList postingList = response.body();
count = postingList.count;
offset = offset + count;
postingArrayList.addAll( postingList.items );
adapter.notifyDataSetChanged();
}else{
}
}
@Override
public void onFailure(Call<PostingList> call, Throwable throwable) {
progressBar.setVisibility(View.GONE);
}
});
}
@Override
protected void onResume() {
super.onResume();
// 네트워크를 통해서 데이터를 받아온다.
getNetworkData();
}
private void getNetworkData() {
progressBar.setVisibility(View.VISIBLE);
postingArrayList.clear();
offset = 0;
Retrofit retrofit = NetworkClient.getRetrofitClient(MainActivity.this);
PostingApi api = retrofit.create(PostingApi.class);
Call<PostingList> call = api.getPostingList("Bearer "+token, offset, limit);
call.enqueue(new Callback<PostingList>() {
@Override
public void onResponse(Call<PostingList> call, Response<PostingList> response) {
progressBar.setVisibility(View.GONE);
if(response.isSuccessful()){
PostingList postingList = response.body();
count = postingList.count;
offset = offset + count;
postingArrayList.addAll( postingList.items );
adapter = new PostingAdapter(MainActivity.this, postingArrayList);
recyclerView.setAdapter(adapter);
}else{
}
}
@Override
public void onFailure(Call<PostingList> call, Throwable throwable) {
progressBar.setVisibility(View.GONE);
}
});
}
}
Posting 클래스 만들기
package com.~.postingapp.model;
public class Posting {
public int id;
public int userId;
public String imageUrl;
public String content;
public String createdAt;
public String updatedAt;
public String email;
public int isLike;
}
PostingList 클래스 만들기
package com.~.postingapp.model;
import java.util.ArrayList;
public class PostingList {
public String result;
public ArrayList<Posting> items;
public int count;
}
PostingAdapter 만들기
- activity_row와 MainActivity의 화면을 연결해준다.
package com.~.postingapp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.~.postingapp.R;
import com.~.postingapp.model.Posting;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
public class PostingAdapter extends RecyclerView.Adapter<PostingAdapter.ViewHolder> {
Context context;
ArrayList<Posting> postingArrayList;
SimpleDateFormat sf;
SimpleDateFormat df;
public PostingAdapter(Context context, ArrayList<Posting> postingArrayList) {
this.context = context;
this.postingArrayList = postingArrayList;
//2024-05-30T07:23:52
sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
df.setTimeZone(TimeZone.getDefault());
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_row, parent, false);
return new PostingAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Posting posting = postingArrayList.get(position);
Glide.with(context).load( posting.imageUrl ).into( holder.imgPhoto );
holder.txtContent.setText( posting.content );
holder.txtEmail.setText( posting.email );
holder.txtCreatedAt.setText( posting.createdAt );
if( posting.isLike == 0 ){
holder.imgLike.setImageResource(R.drawable.like_24dp);
}else{
holder.imgLike.setImageResource(R.drawable.like2);
}
try {
Date date = sf.parse( posting.createdAt );
String localTime = df.format(date);
holder.txtCreatedAt.setText(localTime);
} catch (ParseException e) {
// 로그를 남겨서 디버깅한다.
}
}
@Override
public int getItemCount() {
return postingArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView imgPhoto;
TextView txtContent;
TextView txtEmail;
TextView txtCreatedAt;
ImageView imgLike;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.imgPhoto);
txtContent = itemView.findViewById(R.id.txtContent);
txtEmail = itemView.findViewById(R.id.txtEmail);
txtCreatedAt = itemView.findViewById(R.id.txtCreatedAt);
imgLike = itemView.findViewById(R.id.imgLike);
}
}
}
PostingApi 만들기
package com.~.postingapp.api;
import com.~.postingapp.model.PostingList;
import com.~.postingapp.model.Res;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Query;
public interface PostingApi {
// 포스팅 생성 API
@POST("/posting")
Call<Res> addPosting(@Header("Authorization") String token,
@Part MultipartBody.Part image,
@Part("content") RequestBody content);
// 친구들의 포스팅 리스트 가져오는 API
@GET("/posting")
Call<PostingList> getPostingList(@Header("Authorization") String token,
@Query("offset") int offset,
@Query("limit") int limit);
}
'Android' 카테고리의 다른 글
안드로이드 스튜디오 GPS 기능으로 지도에 마커 추가하기 (0) | 2024.06.18 |
---|---|
안드로이드 스튜디오 탭 바(Tab Bar) 구현하기 (0) | 2024.06.18 |
(안드로이드 스튜디오) 카메라 촬영 사진 업로드 권한 설정, 이미지 업로드하는 기능 만들기 (2) | 2024.06.14 |
(android studio 안드로이드 스튜디오) AlertDialog 팝업창 쉽게 만드는 방법 (0) | 2024.06.14 |
회원가입, 로그인, 로그아웃 기능 앱(app)을 Retrofit2 라이브러리로 만들기 (2) | 2024.06.13 |