---
title: 안드로이드 Parse에서 기본 데이터 쿼리 수행 가이드
slug: docs-kr/docs/android/data-objects/android-basic-query
description: 안드로이드 앱에서 Parse 사용 시 기본 데이터 쿼리 수행 방법을 배우세요.
image: https://www.back4app.com/images/logo-social.png
createdAt: 2024-03-13T14:02:54.879Z
---

# 안드로이드의 기본 쿼리

## 소개

이 가이드에서는 <font color="#2166ae">`Parse`</font>에서 기본 쿼리를 수행하고 <font color="#2166ae">`Android`</font> 앱을 이러한 쿼리를 사용하여 구현합니다. <font color="#2166ae">`Back4App`</font>을 사용하여 현실적인 데이터를 설정하고 쿼리하는 방법을 배웁니다. <font color="#2166ae">`Android`</font>.

이 튜토리얼은 <font color="#2166ae">`buildToolsVersion=30.0.2`</font> , <font color="#2166ae">`Compile SDK Version = 30.0.2`</font> 및 <font color="#2166ae">`targetSdkVersion=30`</font>

:::hint{type="success"}
언제든지 이 튜토리얼로 구축된 전체 안드로이드 프로젝트에 접근할 수 있습니다. 우리의 Github 저장소에서 확인하세요.

- [코틀린 예제 저장소](https://github.com/templates-back4app/Android-Parse-Sdk-Kotlin)
- [자바 예제 저장소](https://github.com/templates-back4app/Android-Parse-Sdk-Java)
:::

## 목표

우리의 목표는 <font color="#2166ae">`Back4App`</font>에서 데이터를 쿼리하는 것입니다. <font color="#2166ae">`Android`</font> 앱을 통해.

우리가 달성할 목표의 미리보기를 보여드립니다:

::Image[]{src="https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/2P-b0YNHro11-ifKLt8YQ_image.png" size="50" width="346" height="750" position="center" showCaption="false"}

## 전제 조건

:::hint{type="info"}
**이 튜토리얼을 완료하려면 다음이 필요합니다:**

- [안드로이드 스튜디오](https://developer.android.com/studio/index.html)
- Back4App에서 생성된 앱.
  - **참고:&#x20;**&#x20;[새 Parse 앱 튜토리얼](https://www.back4app.com/docs/get-started/new-parse-app)을 따라 Back4App에서 Parse 앱을 만드는 방법을 배우세요.
- Back4App에 연결된 안드로이드 앱.
  - **참고:&#x20;**&#x20;[Parse SDK 설치 튜토리얼](https://www.back4app.com/docs/android/parse-android-sdk)을 따라 Back4App에 연결된 안드로이드 스튜디오 프로젝트를 만드세요.
- 안드로이드 4.1 (젤리빈) 이상을 실행하는 장치 (또는[ 가상 장치](https://developer.android.com/studio/run/managing-avds.html))
:::

## 시작해봅시다!

:::hint{type="info"}
다음 단계에 앞서, <font color="#2166ae">`Back4App`</font>을(를) 우리 애플리케이션에 연결해야 합니다. <font color="#2166ae">`appId`</font>와 <font color="#2166ae">`clientKey`</font>를 <font color="#2166ae">`Back4App`</font>에서 <font color="#2166ae">`string.xml`</font> 파일에 저장한 후, <font color="#2166ae">`Parse`</font>를 우리 <font color="#2166ae">`App.java`</font> 또는 <font color="#2166ae">`App.kt`</font> 파일에서 초기화해야 합니다.
&#x20;[새 Parse 앱 튜토리얼](https://www.back4app.com/docs/android/parse-android-sdk)을(를) 따라 하세요. <font color="#2166ae">`Parse`</font>를(을) 앱에 초기화하는 방법을 모른다면.

또는 위에 공유한 깃허브 링크에서 프로젝트를 다운로드하고 <font color="#2166ae">`appId`</font>와 <font color="#2166ae">`clientKey`</font> 부분만 수정할 수 있습니다.
:::

## 1 - Parse.Query 클래스 이해하기

모든 Parse 쿼리 작업은 <font color="#2166ae">`ParseQuery`</font> 객체 유형을 사용하며, 이는 앱 전반에 걸쳐 데이터베이스에서 특정 데이터를 검색하는 데 도움이 됩니다. <font color="#2166ae">`ParseQuery`</font>는 retrieve 메서드(예: <font color="#2166ae">`query.findInBackground`</font> 호출 후에만 해결된다는 것을 아는 것이 중요합니다. 따라서 쿼리를 설정하고 여러 수정자를 실제로 호출하기 전에 연결할 수 있습니다.

새로운 <font color="#2166ae">`ParseQuery`</font>,를 생성하려면 원하는 ParseObject 하위 클래스를 매개변수로 전달해야 하며, 이 클래스가 쿼리 결과를 포함하게 됩니다. 아래에서 볼 수 있는 예제 쿼리에서는 가상의 Profile 하위 클래스가 쿼리되고 있습니다.

:::CodeblockTabs
```java
1   // This will create your query
2   ParseQuery<ParseObject> query = new ParseQuery<>("Profile");
3   // The query will resolve only after calling this method
4   query.findInBackground();
```

```kotlin
1   // This will create your query
2    val query = ParseQuery<ParseObject>("Profile")
3   // The query will resolve only after calling this method
4   query.findInBackground()
```
:::

다음에 대한 자세한 내용을 읽을 수 있습니다. <font color="#2166ae">`Parse.Query`</font> 클래스 [공식 문서에서 여기](https://www.back4app.com/docs/javascript/parse-javascript-sdk).&#x20;

## 2 - Back4App에 데이터를 저장하기

:::hint{type="info"}
이 단계에서는 JS 콘솔과 <font color="#2166ae">`Parse`</font>에서 제공하는 Javascript 코드를 사용하여 클래스를 생성하고 이 클래스에 대한 쿼리를 생성할 것입니다.
:::

프로필 <font color="#2166ae">`Profile`</font> 클래스를 생성합시다. 이 클래스는 이 가이드에서 우리의 쿼리 대상이 될 것입니다. <font color="#2166ae">`Parse`</font> 대시보드 자바스크립트 콘솔에서는 JavaScript 코드를 직접 실행하고, JS SDK 명령어를 사용하여 애플리케이션 데이터베이스 내용을 쿼리하고 업데이트할 수 있습니다. 아래 코드를 JS 콘솔에서 실행하고 Back4App에 데이터를 삽입하세요.

대시보드에서 JS 콘솔이 어떻게 보이는지 확인해보세요:



![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/Wlu7TX7N6ZuOhocNdNmrc_image.png)

사용자 <font color="#2166ae">`Profile`</font> 클래스를 다음 예제 내용을 사용하여 생성하세요:

```java
1   // Add Profile objects and create table
2   // Adam Sandler
3   let Profile = new Parse.Object('Profile');
4   Profile.set('name', 'Adam Sandler');
5   Profile.set('birthDay', new Date('09/09/1966'));
6   Profile.set('friendCount', 2);
7   Profile.set('favoriteFoods', ['Lobster', 'Bread']);
8   await Profile.save();
9
10  // Adam Levine
11  Profile = new Parse.Object('Profile');
12  Profile.set('name', 'Adam Levine');
13  Profile.set('birthDay', new Date('03/18/1979'));
14  Profile.set('friendCount', 52);
15  Profile.set('favoriteFoods', ['Cake', 'Bread']);
16  await Profile.save();
17
18  // Carson Kressley
19  Profile = new Parse.Object('Profile');
20  Profile.set('name', 'Carson Kressley');
21  Profile.set('birthDay', new Date('11/11/1969'));
22  Profile.set('friendCount', 12);
23  Profile.set('favoriteFoods', ['Fish', 'Cookies']);
24  await Profile.save();
25
26  // Dan Aykroyd
27  Profile = new Parse.Object('Profile');
28  Profile.set('name', 'Dan Aykroyd');
29  Profile.set('birthDay', new Date('07/01/1952'));
30  Profile.set('friendCount', 66);
31  Profile.set('favoriteFoods', ['Jam', 'Peanut Butter']);
32  await Profile.save();
33
34  // Eddie Murphy
35  Profile = new Parse.Object('Profile');
36  Profile.set('name', 'Eddie Murphy');
37  Profile.set('birthDay', new Date('04/03/1961'));
38  Profile.set('friendCount', 49);
39  Profile.set('favoriteFoods', ['Lettuce', 'Pepper']);
40  await Profile.save();
41
42  // Fergie
43  Profile = new Parse.Object('Profile');
44  Profile.set('name', 'Fergie');
45  Profile.set('birthDay', new Date('03/27/1975'));
46  Profile.set('friendCount', 55);
47  Profile.set('favoriteFoods', ['Lobster', 'Shrimp']);
48  await Profile.save();
49  
50  console.log('Success!');
```

### &#x20;3 - 데이터 쿼리하기

이제 클래스가 채워졌으므로, 기본 쿼리를 수행할 수 있습니다. 이름으로 결과를 필터링하는 것부터 시작하겠습니다. 이는 문자열 유형 필드로, <font color="#2166ae">`Profile`</font>이라는 이름을 포함하는 값을 검색합니다. <font color="#2166ae">`아담`</font>을 사용하여 <font color="#2166ae">`Parse.Query.contains`</font> 메서드를 사용합니다:

```java
1   // Create your query
2   let parseQuery = new Parse.Query('Profile');
3
4   // `contains` is a basic query method that checks if string field
5   // contains a specific substring
6   parseQuery.contains('name', 'Adam');
7
8   // The query will resolve only after calling this method, retrieving
9   // an array of `Parse.Objects`
10  let queryResults = await parseQuery.find();
11
12  // Let's show the results
13  for (let result of queryResults) {
14    // You access `Parse.Objects` attributes by using `.get`
15    console.log(result.get('name'));
16  };
```

이제 숫자 유형 필드로 쿼리해 보겠습니다 <font color="#2166ae">`friendCount`</font>을 사용하여 또 다른 일반 쿼리 메서드인 <font color="#2166ae">`Parse.Query.greaterThan`</font>. 이 경우, 친구 수가 20보다 큰 <font color="#2166ae">`Profiles`</font>를 원합니다.

```java
1   // Create your query
2   let parseQuery = new Parse.Query('Profile');
3
4   // `greaterThan` is a basic query method that does what it
5   // says on the tin
6   parseQuery.greaterThan('friendCount', 20);
7
8   // The query will resolve only after calling this method, retrieving
9   // an array of `Parse.Objects`
10  let queryResults = await parseQuery.find();
11
12  // Let's show the results
13  for (let result of queryResults) {
14    // You access `Parse.Objects` attributes by using `.get`
15    console.log(`name: ${result.get('name')}, friend count: ${result.get('friendCount')}`);
16  };
```

다른 반복 쿼리 메서드는 <font color="#2166ae">`Parse.Query.ascending`</font> 및 <font color="#2166ae">`Parse.Query.descending`</font>, 쿼리를 정렬하는 역할을 합니다. 이 정렬은 대부분의 데이터 유형에서 수행할 수 있으므로, 날짜 필드 <font color="#2166ae">`birthDay`</font>를 기준으로 쿼리를 가장 어린 사람으로 정렬해 보겠습니다.

```java
1   // Create your query
2   let parseQuery = new Parse.Query('Profile');
3
4   // `descending` and `ascending` can and should be chained
5   // with other query methods to improve your queries
6   parseQuery.descending('birthDay');
7
8   // The query will resolve only after calling this method, retrieving
9   // an array of `Parse.Objects`
10  let queryResults = await parseQuery.find();
11 
12  // Let's show the results
13  for (let result of queryResults) {
14    // You access `Parse.Objects` attributes by using `.get`
15    console.log(`name: ${result.get('name')}, birthday: ${result.get('birthDay')}`);
16  };
```

앞서 언급했듯이, 더 정교한 결과를 얻기 위해 쿼리 메서드를 연결할 수 있으며 연결해야 합니다. 그러면 이전 예제를 단일 쿼리 요청으로 결합해 보겠습니다:

```java
1   // Create your query
2   let parseQuery = new Parse.Query('Profile');
3
4   parseQuery.contains('name', 'Adam');
5   parseQuery.greaterThan('friendCount', 20);
6   parseQuery.descending('birthDay');
7
8   // The query will resolve only after calling this method, retrieving
9   // an array of `Parse.Objects`
10  let queryResults = await parseQuery.find();
11
12  // Let's show the results
13  for (let result of queryResults) {
14    // You access `Parse.Objects` attributes by using `.get`
15    console.log(`name: ${result.get('name')}, friend count: ${result.get('friendCount')}, birthday: ${result.get('birthDay')}`);
16  };
```

## 4 - 우리 Android 앱에서의 쿼리

이제 Android 애플리케이션에서 Java와 Kotlin을 사용하여 위에서 JS 콘솔로 수행한 작업을 수행하겠습니다. 4개의 서로 다른 쿼리를 만들어 프로필을 나열할 것입니다.

:::CodeblockTabs
```java
1   private void doQueryByName() {
2           ParseQuery<ParseObject> query = new ParseQuery<>("Profile");
3           query.whereContains("name", "Adam");
4           progressDialog.show();
5           query.findInBackground((objects, e) -> {
6               progressDialog.hide();
7               if (e == null) {
8                   adapter = new ResultAdapter(this, objects);
9                   resultList.setLayoutManager(new LinearLayoutManager(this));
10                  resultList.setAdapter(adapter);
11              } else {
12                  Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
13              }
14          });
15      }
16
17      private void doQueryByFriendCount() {
18          ParseQuery<ParseObject> query = new ParseQuery<>("Profile");
19          query.whereGreaterThan("friendCount", 20);
20          progressDialog.show();
21          query.findInBackground((objects, e) -> {
22              progressDialog.hide();
23              if (e == null) {
24                  adapter = new ResultAdapter(this, objects);
25                  resultList.setLayoutManager(new LinearLayoutManager(this));
26                  resultList.setAdapter(adapter);
27              } else {
28                  Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
29              }
30          });
31      }
32 
33      private void doQueryByOrdering() {
34          ParseQuery<ParseObject> query = new ParseQuery<>("Profile");
35          query.orderByDescending("birthDay");
36          progressDialog.show();
37          query.findInBackground((objects, e) -> {
38              progressDialog.hide();
39              if (e == null) {
40                  adapter = new ResultAdapter(this, objects);
41                  resultList.setLayoutManager(new LinearLayoutManager(this));
42                  resultList.setAdapter(adapter);
43              } else {
44                  Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
45              }
46          });
47      }
48  
49      private void doQueryByAll() {
50          ParseQuery<ParseObject> query = new ParseQuery<>("Profile");
51          query.whereContains("name", "Adam");
52          query.whereGreaterThan("friendCount", 20);
53          query.orderByDescending("birthDay");
54          progressDialog.show();
55
56          query.findInBackground((objects, e) -> {
57              progressDialog.hide();
58
59              if (e == null) {
60                  adapter = new ResultAdapter(this, objects);
61                  resultList.setLayoutManager(new LinearLayoutManager(this));
62                  resultList.setAdapter(adapter);
63                  resultList.setNestedScrollingEnabled(false);
64              } else {
65                  Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
66              }
67          });
68      }
```

```kotlin
1   private fun doQueryByName() {
2           val query = ParseQuery<ParseObject>("Profile")
3           query.whereContains("name", "Adam")
4           progressDialog!!.show()
5           query.findInBackground { objects: List<ParseObject>?, e: ParseException? ->
6               progressDialog!!.hide()
7               if (e == null) {
8                   adapter = ResultAdapter(this, objects)
9                   resultList!!.layoutManager = LinearLayoutManager(this)
10                  resultList!!.adapter = adapter
11              } else {
12                  Toast.makeText(this, e.localizedMessage, Toast.LENGTH_SHORT).show()
13              }
14          }
15      }
16
17      private fun doQueryByFriendCount() {
18          val query = ParseQuery<ParseObject>("Profile")
19          query.whereGreaterThan("friendCount", 20)
20          progressDialog!!.show()
21          query.findInBackground { objects: List<ParseObject>?, e: ParseException? ->
22              progressDialog!!.hide()
23              if (e == null) {
24                  adapter = ResultAdapter(this, objects)
25                  resultList!!.layoutManager = LinearLayoutManager(this)
26                  resultList!!.adapter = adapter
27              } else {
28                  Toast.makeText(this, e.localizedMessage, Toast.LENGTH_SHORT).show()
29              }
30          }
31      }
32
33      private fun doQueryByOrdering() {
34          val query = ParseQuery<ParseObject>("Profile")
35          query.orderByDescending("birthDay")
36          progressDialog!!.show()
37          query.findInBackground { objects: List<ParseObject>?, e: ParseException? ->
38              progressDialog!!.hide()
39              if (e == null) {
40                  adapter = ResultAdapter(this, objects)
41                  resultList!!.layoutManager = LinearLayoutManager(this)
42                  resultList!!.adapter = adapter
43              } else {
44                  Toast.makeText(this, e.localizedMessage, Toast.LENGTH_SHORT).show()
45              }
46          }
47      }
48  
49      private fun doQueryByAll() {
50          val query = ParseQuery<ParseObject>("Profile")
51          query.whereContains("name", "Adam")
52          query.whereGreaterThan("friendCount", 20)
53          query.orderByDescending("birthDay")
54          progressDialog!!.show()
55          query.findInBackground { objects: List<ParseObject>?, e: ParseException? ->
56              progressDialog!!.hide()
57              if (e == null) {
58                  adapter = ResultAdapter(this, objects)
59                  resultList!!.layoutManager = LinearLayoutManager(this)
60                  resultList!!.adapter = adapter
61                  resultList!!.isNestedScrollingEnabled = false
62              } else {
63                  Toast.makeText(this, e.localizedMessage, Toast.LENGTH_SHORT).show()
64              }
65          }
66      }
```
:::

## 완료되었습니다!

이 가이드를 끝내면서, Parse에서 기본 데이터 쿼리가 어떻게 작동하는지와 Android 앱에서 Back4App에서 이를 수행하는 방법을 배웠습니다.
