Android
Data objects
Android SDK로 Parse 객체 CRUD 처리하기
13 분
안드로이드에서 crud parse 객체 사용하기 소개 이 섹션에서는 기본 crud 작업을 수행하는 안드로이드 애플리케이션을 구축할 것입니다 crud는 create read update delete의 약자입니다 parse에 데이터를 저장할 때는 parseobject를 기반으로 하며, 각 객체는 json 호환 데이터의 키 값 쌍을 포함합니다 back4app 데이터베이스에 저장할 수 있는 값은 string, number, bool, array, object, date, file, pointer, relation 및 null 유형일 수 있습니다 데이터 유형에 대한 자세한 정보는 https //docs parseplatform org/js/guide/#data types 를 클릭하여 확인할 수 있습니다 이 튜토리얼은 buildtoolsversion=30 0 2 buildtoolsversion=30 0 2 , compile sdk version = 30 0 2 compile sdk version = 30 0 2 및 targetsdkversion 30 targetsdkversion 30 언제든지 github 리포지토리를 통해 전체 프로젝트에 접근할 수 있습니다 https //github com/templates back4app/android crud operations kotlin https //github com/templates back4app/android crud operations java 목표 우리가 달성할 목표의 미리보기입니다 필수 조건 이 튜토리얼을 완료하기 위해 필요한 것은 https //developer android com/studio/index html back4app에서 생성된 앱 참고 https //www back4app com/docs/get started/new parse app 을 따라 back4app에서 parse 앱을 만드는 방법을 배우세요 back4app에 연결된 안드로이드 앱 참고 https //www back4app com/docs/android/parse android sdk 을 따라 back4app에 연결된 안드로이드 스튜디오 프로젝트를 만드세요 안드로이드 4 1 (젤리빈) 이상을 실행하는 장치 (또는 https //developer android com/studio/run/managing avds html )입니다 우리의 todo 앱 이해하기 안드로이드에서 parse를 더 잘 이해하기 위해, todo 앱에서 구현된 crud 작업을 볼 수 있습니다 이 애플리케이션은 작업을 등록하기 위한 제목 및 설명 텍스트 필드와 등록된 작업 목록이 있는 간단한 인터페이스를 가질 것입니다 각 작업의 제목이나 설명을 업데이트할 수 있습니다 참고 이 튜토리얼에서는 나만의 사용자 정의 경고 대화 상자를 만들 것입니다 따라서 코드는 템플릿을 따르도록 구성됩니다 자신의 디자인에 맞게 조정할 수 있습니다 문제가 발생하면, https //github com/templates back4app/android crud operations kotlin 및 https //github com/templates back4app/android crud operations java 에 대한 github 리포지토리를 확인하세요 시작해 봅시다! 다음 단계를 따르면 back4app 데이터베이스에 작업을 저장하는 todo 앱을 만들 수 있습니다 1 todo 앱 템플릿 만들기 안드로이드 스튜디오로 가서 activity main xml activity main xml 레이아웃 파일을 찾으세요 (project/app/res/layout/activity main xml) (project/app/res/layout/activity main xml) 그리고 아래 코드를 자신의 코드로 교체하세요 이 xml 코드는 우리의 mainactivity의 mainactivity의 디자인이 될 것이며, 우리는 이 뷰를 우리의 mainactivity java mainactivity java 클래스에 바인딩하고 사용할 것입니다 1 \<?xml version="1 0" encoding="utf 8"?> 2 \<androidx constraintlayout widget constraintlayout xmlns\ android="http //schemas android com/apk/res/android" 3 xmlns\ app="http //schemas android com/apk/res auto" 4 xmlns\ tools="http //schemas android com/tools" 5 android\ layout width="match parent" 6 android\ layout height="match parent" 7 tools\ context=" mainactivity"> 8 9 \<! title >> 10 \<textview 11 android\ id="@+id/textview" 12 android\ layout width="0dp" 13 android\ layout height="wrap content" 14 android\ background="@color/blue 700" 15 android\ gravity="center horizontal" 16 android\ padding="24dp" 17 android\ text="todo list" 18 android\ textcolor="@color/white" 19 app\ layout constraintend toendof="parent" 20 app\ layout constraintstart tostartof="parent" 21 app\ layout constrainttop totopof="parent" /> 22 23 \<! we will open a pop up view when clicked to this button >> 24 \<com google android material floatingactionbutton floatingactionbutton 25 android\ id="@+id/fab" 26 style="@style/widget materialcomponents floatingactionbutton" 27 android\ layout width="wrap content" 28 android\ layout height="wrap content" 29 android\ layout margin="16dp" 30 android\ scaletype="centerinside" 31 android\ src="@drawable/ic baseline add 24" 32 app\ backgroundtint="@color/blue 700" 33 app\ fabsize="normal" 34 app\ layout constraintbottom tobottomof="parent" 35 app\ layout constraintend toendof="parent" 36 app\ tint="@color/white" /> 37 38 \<! we will show this text view when data list is empty >> 39 \<textview 40 android\ id="@+id/empty text" 41 android\ layout width="wrap content" 42 android\ layout height="wrap content" 43 android\ text="list is empty" 44 android\ layout margintop="32dp" 45 android\ textsize="20sp" 46 android\ visibility="gone" 47 app\ layout constraintend toendof="parent" 48 app\ layout constraintstart tostartof="parent" 49 app\ layout constrainttop tobottomof="@+id/textview" /> 50 51 \<! we will adapt the data list to this recyclerview > 52 \<androidx recyclerview\ widget recyclerview 53 android\ id="@+id/recyclerview" 54 android\ layout width="0dp" 55 android\ layout height="0dp" 56 app\ layout constraintbottom tobottomof="parent" 57 app\ layout constraintend toendof="parent" 58 app\ layout constraintstart tostartof="parent" 59 app\ layout constrainttop tobottomof="@+id/textview"> 60 \</androidx recyclerview\ widget recyclerview> 61 \</androidx constraintlayout widget constraintlayout> 2 객체 생성 create 함수는 제목과 설명을 가진 새로운 작업을 생성합니다 todo를 추가하기 위해, 화면에 나타나는 팝업에 제목과 설명 값을 입력하고, 이를 parseobject에 설정한 후 이 객체를 저장합니다 우리는 parse가 제공한 함수를 사용하여 이 객체를 데이터베이스에 저장합니다 참고 이 프로젝트에서는 나만의 사용자 정의 알림 대화 상자를 만들 것입니다 원하는 대로 알림 대화 상자를 디자인하고 나중에 사용할 대화 상자의 뷰에 설정할 수 있습니다 1 openinputpopupdialogbutton setonclicklistener(fabbuttonview > { 2 alertdialog builder alertdialogbuilder = new alertdialog builder(mainactivity this); 3 alertdialogbuilder settitle("create a todo"); 4 alertdialogbuilder setcancelable(true); 5 initpopupviewcontrols(); 6 //we are setting our custom popup view by alertdialog builder 7 alertdialogbuilder setview(popupinputdialogview); 8 final alertdialog alertdialog = alertdialogbuilder create(); 9 alertdialog show(); 10 savetodobutton setonclicklistener(savebuttonview > savetodo(alertdialog)); 11 canceluserdatabutton setonclicklistener(cancelbuttonview > alertdialog cancel()); 12 }); 13 14 //this is our savetodo function 15 private void savetodo(alertdialog alertdialog) { 16 parseobject todo = new parseobject("todo"); 17 if (titleinput gettext() tostring() length() != 0 && descriptioninput gettext() tostring() length() != 0) { 18 alertdialog cancel(); 19 progressdialog show(); 20 todo put("title", titleinput gettext() tostring()); 21 todo put("description", descriptioninput gettext() tostring()); 22 todo saveinbackground(e > { 23 progressdialog dismiss(); 24 if (e == null) { 25 //we saved the object and fetching data again 26 gettodolist(); 27 } else { 28 //we have an error we are showing error message here 29 showalert("error", e getmessage()); 30 } 31 }); 32 } else { 33 showalert("error", "please enter a title and description"); 34 } 35 }1 openinputpopupdialogbutton? setonclicklistener { fabbuttonview > 2 val alertdialogbuilder = alertdialog builder(this\@mainactivity) 3 alertdialogbuilder settitle("create a todo") 4 alertdialogbuilder setcancelable(true) 5 initpopupviewcontrols() 6 //we are setting our custom popup view by alertdialog builder 7 alertdialogbuilder setview(popupinputdialogview) 8 val alertdialog = alertdialogbuilder create() 9 alertdialog show() 10 savetodobutton? setonclicklistener { savebuttonview > 11 savedata(alertdialog) 12 } 13 canceluserdatabutton? setonclicklistener { cancelbuttonview > 14 alertdialog cancel() 15 } 16 } 17 18 //this is our savetodo function 19 private fun savedata(alertdialog alertdialog) { 20 val todo = parseobject("todo") 21 if (titleinput? text tostring() isnotempty() && descriptioninput? text tostring() isnotempty()) { 22 alertdialog cancel() 23 progressdialog? show() 24 todo put("title", titleinput? text tostring()) 25 todo put("description", descriptioninput? text tostring()) 26 todo saveinbackground { e > 27 progressdialog? dismiss() 28 if (e == null) { 29 //we saved the object and fetching data again 30 gettodolist() 31 } else { 32 //we have an error we are showing error message here 33 showalert("error", e message!!) 34 } 35 } 36 } else { 37 showalert("error", "please enter a title and description") 38 } 39 } 3 객체 읽기 parse가 제공한 기능을 사용하여, 우리는 parseobject 목록으로 클래스의 모든 데이터를 가져올 수 있습니다 아래와 같은 쿼리를 생성하고 todo 클래스의 모든 데이터를 가져옵니다 1 private void gettodolist() { 2 progressdialog show(); 3 parsequery\<parseobject> query = parsequery getquery("todo"); 4 query orderbydescending("createdat"); 5 query findinbackground((objects, e) > { 6 progressdialog dismiss(); 7 if (e == null) { 8 //we are initializing todo object list to our adapter 9 inittodolist(objects); 10 } else { 11 showalert("error", e getmessage()); 12 } 13 }); 14 }1 private fun gettodolist() { 2 progressdialog? show() 3 val query = parsequery getquery\<parseobject>("todo") 4 query orderbydescending("createdat") 5 query findinbackground { objects, e > 6 progressdialog? dismiss() 7 if (e == null) { 8 //we are initializing todo object list to our adapter 9 inittodolist(objects) 10 } else { 11 showalert("error", e message!!) 12 } 13 } 14 } 이 함수에서는 반환된 목록을 매개변수로 사용하여 어댑터 어댑터 , 이 어댑터 어댑터 ,를 recyclerview recyclerview ,에 설정하고, 이 목록의 각 객체의 값을 자신의 뷰에 출력합니다 그리고 목록에 항목이 없으면, 우리는 empty text empty text , 뷰를 visible visible 로 설정합니다 1 private void inittodolist(list\<parseobject> list) { 2 if (list == null || list isempty()) { 3 empty text setvisibility(view\ visible); 4 return; 5 } 6 empty text setvisibility(view\ gone); 7 8 todoadapter adapter = new todoadapter(list, this); 9 10 recyclerview\ setlayoutmanager(new linearlayoutmanager(this)); 11 recyclerview\ setadapter(adapter); 12 }1 private fun inittodolist(list list\<parseobject>?) { 2 if (list == null || list isempty()) { 3 empty text!! visibility = view\ visible 4 return 5 } 6 empty text? visibility = view\ gone 7 8 val adapter = todoadapter(list as arraylist\<parseobject>, this) 9 10 recyclerview? layoutmanager = linearlayoutmanager(this) 11 recyclerview? adapter = adapter 12 } 4 객체 업데이트 어댑터의 뷰에서 편집 버튼을 사용하여 업데이트를 수행하고 있습니다 mutablelivedata mutablelivedata , android에서 제공하는 객체로, 우리는 홈페이지에서 편집 버튼의 클릭 이벤트를 수신할 수 있습니다 이 버튼이 클릭되면, 동일한 팝업을 열고 이번에는 클릭한 객체의 제목과 설명 값으로 이 팝업을 채웁니다 그런 다음 사용자가 이 설명과 제목을 변경하고 저장을 누르면, 먼저 이 객체의 id로 데이터베이스에서 가져온 후, 새로운 변수를 설정하고 객체를 다시 저장합니다 참고 mutablelivedata는 livedata의 하위 클래스이며, 일부 속성(setvalue/postvalue)에 사용됩니다 이러한 속성을 사용하여 ui에 쉽게 알릴 수 있습니다 1 adapter oneditlistener observe(this, parseobject > { 2 alertdialog builder alertdialogbuilder = new alertdialog builder(mainactivity this); 3 alertdialogbuilder settitle("update a todo"); 4 alertdialogbuilder setcancelable(true); 5 //we are initializing popup views with title and description parameters of parseobject 6 initpopupviewcontrols(parseobject getstring("title"), parseobject getstring("description")); 7 alertdialogbuilder setview(popupinputdialogview); 8 final alertdialog alertdialog = alertdialogbuilder create(); 9 alertdialog show(); 10 savetodobutton setonclicklistener(savetodobuttonview > { 11 if (titleinput gettext() tostring() length() != 0 && descriptioninput gettext() tostring() length() != 0) { 12 alertdialog cancel(); 13 progressdialog show(); 14 parseobject put("title", titleinput gettext() tostring()); 15 parseobject put("description", descriptioninput gettext() tostring()); 16 parseobject saveinbackground(e1 > { 17 progressdialog dismiss(); 18 if (e1 == null) { 19 gettodolist(); 20 } else { 21 showalert("error", e1 getmessage()); 22 } 23 }); 24 } else { 25 showalert("error", "please enter a title and description"); 26 } 27 }); 28 canceluserdatabutton setonclicklistener(cancelbuttonview > alertdialog cancel()); 29 });1 adapter clicklistenertoedit observe(this\@mainactivity, { parseobject > 2 val alertdialogbuilder = alertdialog builder(this\@mainactivity) 3 alertdialogbuilder settitle("update a todo") 4 alertdialogbuilder setcancelable(true) 5 6 //we are initializing popup views with title and description parameters of parseobject 7 8 initpopupviewcontrols( 9 parseobject getstring("title")!!, 10 parseobject getstring("description")!! 11 ) 12 13 alertdialogbuilder setview(popupinputdialogview) 14 val alertdialog = alertdialogbuilder create() 15 alertdialog show() 16 17 savetodobutton? setonclicklistener { savebuttonview > 18 if (titleinput? text tostring() isnotempty() && descriptioninput? text tostring() isnotempty()) { 19 alertdialog cancel() 20 progressdialog? show() 21 parseobject put("title", titleinput? text tostring()) 22 parseobject put("description", descriptioninput? text tostring()) 23 parseobject saveinbackground { e1 > 24 progressdialog? dismiss() 25 if (e1 == null) { 26 gettodolist() 27 } else { 28 showalert("error", e1 message!!) 29 } 30 } 31 } else { 32 showalert("error", "please enter a title and description") 33 } 34 } 35 }) 5 객체 삭제 우리는 어댑터의 뷰에서 삭제 버튼의 클릭 이벤트를 듣습니다 mutablelivedata mutablelivedata 홈 페이지의 객체와 마찬가지로 편집 버튼에서 삭제 버튼이 클릭되면, parseobject의 객체 id를 삭제 함수에 매개변수로 제공하고 이 객체를 데이터베이스에서 삭제합니다 1 adapter ondeletelistener observe(this, parseobject > { 2 progressdialog show(); 3 parseobject deleteinbackground(e > { 4 progressdialog dismiss(); 5 if (e == null) { 6 //we deleted the object and fetching data again 7 gettodolist(); 8 } else { 9 showalert("error",e getmessage()); 10 } 11 }); 12 });1 adapter ondeletelistener observe(this\@mainactivity, { parseobject > 2 progressdialog? show() 3 parseobject deleteinbackground { e > 4 progressdialog? dismiss() 5 if (e == null) { 6 //we deleted the object and fetching data again 7 gettodolist() 8 } else { 9 showalert("error", e message!!) 10 } 11 } 12 }) 완료되었습니다! 이 시점에서, 당신은 android에서 parse로 기본 crud 작업을 수행하는 방법을 배웠습니다