{"id":10262,"date":"2023-06-23T01:43:43","date_gmt":"2023-06-23T08:43:43","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/quickstart-android-java-query\/"},"modified":"2023-06-23T01:43:43","modified_gmt":"2023-06-23T08:43:43","slug":"quickstart-android-java-query","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/","title":{"rendered":"Quickstart in Couchbase Lite Query with Android and Java"},"content":{"rendered":"\n<h3 id=\"h-introduction\" class=\"wp-block-heading\">Introduction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase Lite brings powerful querying and Full-Text-Search(FTS) capabilties to the edge. The new query interface is based on <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/www.couchbase.com\/products\/n1ql\">N1QL<\/a>, Couchbase\u2019s declarative query language that extends <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/www.sqlite.org\/index.html\">SQL<\/a> for JSON. If you are familiar with SQL, you will feel right at home with the semantics of the new API.  The query API is designed using the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/en.wikipedia.org\/wiki\/Fluent_interface\">Fluent API Design Pattern<\/a>, and it uses method cascading to read to like a Domain Specific Language (DSL). This makes the interface very intuitive and easy to understand.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase Lite can be used as a standalone embedded database within your mobile app.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial will walk through a simple Android app that will<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Demonstrate how you can bundle, load, and use a  <strong><em>prebuilt<\/em><\/strong> instance of Couchbase Lite<\/li>\n\n\n<li>Introduce you to the basics of the <code>QueryBuilder<\/code> interface<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You can learn more about Couchbase Mobile <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/mobile\">here<\/a>.<\/p>\n\n\n\n<h3 id=\"h-prerequisites\" class=\"wp-block-heading\">Prerequisites<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial assumes familiarity with building <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/www.android.com\/\">Android<\/a> apps using <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/openjdk.java.net\/\">Java<\/a> and with the basics of Couchbase Lite.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>If you are unfamiliar with the basics of Couchbase Lite, it is recommended that you walk through the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-android-java-basic\/\">Quickstart in Couchbase Lite with Android and Java Tutorial<\/a> on using Couchbase Lite as a standalone database.<\/p>\n<\/li>\n\n\n<li>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.android.com\/studio\">Android Studio Artic Fox (2020.3.1) or above<\/a><\/p>\n<\/li>\n\n\n<li>\n<p>Android SDK installed and setup (v.31)<\/p>\n<\/li>\n\n\n<li>\n<p>Android Build Tools (&gt; v.31)<\/p>\n<\/li>\n\n\n<li>\n<p>Android device or emulator running API level 22 or above<\/p>\n<\/li>\n\n\n<li>\n<p>JDK 8 (now embedded into Android Studio Artic Fox)<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-app-overview\" class=\"wp-block-heading\">App Overview<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We will be working with a very simple &#8220;User Profile&#8221; app. If you had walked through the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-android-java-basic\/\">Quickstart in Couchbase Lite with Android and Java Tutorial<\/a>, you would quickly realize that this version extends the functionality introduced in the version introduced in that tutorial.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This app does the following<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>Allows users to log in and create or update his\/her user profile information. You could do that in the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-android-java-basic\/\">Quickstart in Couchbase Lite with Android and Java Tutorial<\/a>.<\/p>\n<\/li>\n\n\n<li>\n<p>As part of profile information, users can now selecting a <code>University<\/code> from a list of possible options.<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The list of matching universities is queried (using the new Query API) from a local <em>prebuilt<\/em> &#8220;University&#8221; Couchbase Lite database that is bundled in the app. The user profile information is persisted as a <code>Document<\/code> in the local Couchbase Lite database. So subsequently, when the user logs out and logs back in again, the profile information is loaded from the <code>Database<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/university_app_overview.gif\" alt=\"App Overview\"><\/p>\n\n\n\n<h3 id=\"h-installation\" class=\"wp-block-heading\">Installation<\/h3>\n\n\n\n<h4 id=\"h-fetching-app-source-code\" class=\"wp-block-heading\">Fetching App Source Code<\/h4>\n\n\n\n<h5 id=\"h-clone-source-code\" class=\"wp-block-heading\">Clone Source Code<\/h5>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Clone the the <code>User Profile Query Demo<\/code> repository from GitHub.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>  git clone https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query.git\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-installing-couchbase-lite\" class=\"wp-block-heading\">Installing Couchbase Lite<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The User Profile Standalone Demo app already contains the appropriate additions for downloading and utilizing the Java Android Couchbase Lite dependency module.  However, in the future, to include Couchbase Lite support within an Andorid app add the following within <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query\/blob\/main\/src\/build.gradle\">src\/build.gradle<\/a><\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>allprojects {\n    repositories {\n        ...\n\n        maven {\n            url &quot;https:\/\/mobile.maven.couchbase.com\/maven2\/dev\/&quot;\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then add the following to the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query\/blob\/main\/src\/app\/build.gradle\">app\/build.gradle<\/a> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>dependencies {\n    ...\n\n    implementation &#039;com.couchbase.lite:couchbase-lite-android-ee:3.0.0&#039;\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-try-it-out\" class=\"wp-block-heading\">Try it out<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open build.gradle using Android Studio.<\/li>\n\n\n<li>Build and run the project.<\/li>\n\n\n<li>Verify that you see the login screen.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/user_profile_login.png\" alt=\"User Profile Login Screen Image\"><\/p>\n\n\n\n<h3 id=\"h-app-architecture\" class=\"wp-block-heading\">App Architecture<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The sample app follows the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/en.wikipedia.org\/wiki\/Model%E2%80%93view%E2%80%93presenter\">MVP pattern<\/a>, separating the internal data model, from a passive view through a presenter that handles the logic of our application and acts as the conduit between the model and the view.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/mvp_architecture.png\" alt=\"MVP Architecture\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the Android Studio project, the code is structured by feature. You can select the Android option in the left navigator to view the files by package.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/mvp_as.png\" alt=\"MVP Android Studio\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each package contains 3 different files:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p><strong>Activity<\/strong>: This is where all the view logic resides.<\/p>\n<\/li>\n\n\n<li>\n<p><strong>Presenter<\/strong>: This is where all the business logic resides to fetch and persist data to a web service or the embedded Couchbase Lite database.<\/p>\n<\/li>\n\n\n<li>\n<p><strong>Contract<\/strong>: An interface that the <code>Presenter<\/code> and <code>Activity<\/code> implement.<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/mvp_package.png\" alt=\"MVP Package\"><\/p>\n\n\n\n<h3 id=\"h-data-model\" class=\"wp-block-heading\">Data Model<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase Lite is a JSON Document Store. A <code>Document<\/code> is a logical collection of named fields and values. The values are any valid JSON types. In addition to the standard JSON types, Couchbase Lite supports <code>Date<\/code> and <code>Blob<\/code> data types. While it is not required or enforced, it is a recommended practice to include a <em>&#8220;type&#8221;<\/em> property that can serve as a namespace for related documents.<\/p>\n\n\n\n<h4 id=\"h-the-user-profile-document\" class=\"wp-block-heading\">The &#8220;User Profile&#8221; Document<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The app deals with a single <code>Document<\/code> with a <em>&#8220;type&#8221;<\/em> property of <em>&#8220;user&#8221;<\/em>.  The document ID is of the form <em>&#8220;user::&lt;email&gt;&#8221;<\/em>.\nAn example of a document would be<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\n    &quot;type&quot;:&quot;user&quot;,\n    &quot;name&quot;:&quot;Jane Doe&quot;,\n    &quot;email&quot;:&quot;jame.doe@earth.org&quot;,\n    &quot;address&quot;:&quot;101 Main Street&quot;,\n    &quot;image&quot;:CBLBlob (image\/jpg),\n    &quot;university&quot;:&quot;Missouri State University&quot;\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-userprofile\" class=\"wp-block-heading\">UserProfile<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query\/blob\/main\/src\/app\/src\/main\/java\/com\/couchbase\/userprofile\/profile\/UserProfilePresenter.java\"><em>UserProfilePresenter.java<\/em><\/a> file in the com.couchbase.userprofile.profile directory.  For the purpose of this tutorial the <em>&#8220;user&#8221;<\/em> <code>Document<\/code> is first stored within an <code>Object<\/code> of type <code>Map&lt;String, Object&gt;<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>Map&lt;String, Object&gt; profile = new HashMap&lt;&gt;();\nprofile.put(&quot;name&quot;, nameInput.getText().toString());\nprofile.put(&quot;email&quot;, emailInput.getText().toString());\nprofile.put(&quot;address&quot;, addressInput.getText().toString());\nprofile.put(&quot;university&quot;, universityText.getText().toString());\n\nbyte[] imageViewBytes = getImageViewBytes();\n\nif (imageViewBytes != null) {\n    profile.put(&quot;imageData&quot;, new com.couchbase.lite.Blob(&quot;image\/jpeg&quot;, imageViewBytes));\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>Map&lt;String, Object&gt;<\/code> object functions are used as a data storage mechanism between the app&#8217;s UI and the backing functionality of the Couchbase Lite <code>Document<\/code> object.<\/p>\n\n\n\n<h3 id=\"h-the-university-document\" class=\"wp-block-heading\">The &#8220;University&#8221; Document<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The app comes bundled with a collection of Documents of type <strong><em>&#8220;university&#8221;<\/em><\/strong>. Each Document represents a university.<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\n    &quot;type&quot;:&quot;university&quot;,&quot;web_pages&quot;: [\n      &quot;http:\/\/www.missouristate.edu\/&quot;\n    ],\n    &quot;name&quot;: &quot;Missouri State University&quot;,\n    &quot;alpha_two_code&quot;: &quot;US&quot;,\n    &quot;state-province&quot;: MO,\n    &quot;domains&quot;: [\n      &quot;missouristate.edu&quot;\n    ],\n    &quot;country&quot;: &quot;United States&quot;\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-the-university-record\" class=\"wp-block-heading\">The University Record<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">When <em>&#8220;university&#8221;<\/em> <code>Document<\/code> is retrieved from the database it is stored within an <code>Object<\/code> of type <code>Map&lt;String, Object&gt;<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>Map&lt;String, Object&gt; properties = new HashMap&lt;&gt;();\nproperties.put(&quot;name&quot;, row.getDictionary(&quot;universities&quot;).getString(&quot;name&quot;));\nproperties.put(&quot;country&quot;, row.getDictionary(&quot;universities&quot;).getString(&quot;country&quot;));\nproperties.put(&quot;web_pages&quot;, row.getDictionary(&quot;universities&quot;).getArray(&quot;web_pages&quot;));\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-using-a-prebuilt-database\" class=\"wp-block-heading\">Using a Prebuilt Database<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">There are several reasons why you may want to bundle your app with a prebuilt database. This would be suited for data that does not change or change that often, so you can avoid the bandwidth and latency involved in fetching\/syncing this data from a remote server. This also improves the overall user experience by reducing the start-up time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In our app, the instance of Couchbase Lite that holds the pre-loaded &#8220;university&#8221; data is separate from the Couchbase Lite instance that holds &#8220;user&#8221; data hold the pre-loaded data. A separate Couchbase Lite instance is not required. However, in our case, since there can be many users potentially using the app on a given device, it makes more sense to keep it separate. This is to avoid duplication of pre-loaded data for every user.<\/p>\n\n\n\n<h4 id=\"h-location-of-the-cblite-file\" class=\"wp-block-heading\">Location of the cblite file<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The pre-built database will be in the form of a <code>cblite<\/code> file. It should be in your app project bundle<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the <code>universities.zip<\/code> file within the <code>Assets<\/code> folder.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/cblite_location.png\" alt=\"Prebuilt Database Location\"><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The cblite folder will be extracted from the zip file.<\/p>\n<\/blockquote>\n\n\n\n<h4 id=\"h-loading-the-prebuilt-database\" class=\"wp-block-heading\">Loading the Prebuilt Database<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query\/blob\/main\/src\/app\/src\/main\/java\/com\/couchbase\/userprofile\/util\/DatabaseManager.java\"><strong>DatabaseManager.java<\/strong><\/a> file and locate the <code>openPrebuiltDatabase()<\/code> function. The prebuilt database is common to all users of the app (on the device). So it will be loaded once and shared by all users on the device.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public void openOrCreateDatabaseForUser(Context context, String username)]\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, we create an instance of the <code>DatabaseConfiguration<\/code> object and specify the path where the database would be located<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>DatabaseConfiguration config = new DatabaseConfiguration();\nconfig.setDirectory(context.getFilesDir().toString());\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Then we determine if the &#8220;universities&#8221; database already exists at the specified location. It would not be present if this is the first time we are using the app, in which case, we locate the <em>&#8220;universities.cblite&#8221;<\/em> resource in the App&#8217;s main bundle and we copy it over to the Database folder.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If the database is already present at the specified Database location, we simply open the database.<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>if (!dbFile.exists()) {\n  AssetManager assetManager = context.getAssets();\n  try {\n    File path = new File(context.getFilesDir().toString());\n    unzip(assetManager.open(&quot;universities.zip&quot;), path);\n    universityDatabase = new Database(&quot;universities&quot;, config);\n    createUniversityDatabaseIndexes();\n  } catch (IOException e) {\n    e.printStackTrace();\n  } catch (CouchbaseLiteException e) {\n    e.printStackTrace();\n  }\n} \nelse {\n  try {\n    universityDatabase = new Database(&quot;universities&quot;, config);\n  } catch (CouchbaseLiteException e) {\n    e.printStackTrace();\n  }\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-indexing-the-prebuilt-database\" class=\"wp-block-heading\">Indexing the Prebuilt Database<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>Creating indexes for non-FTS based queries is optional. However, to speed up queries, you can create indexes on the properties that you would query against. Indexing is handled eagerly.<\/p>\n<\/li>\n\n\n<li>\n<p>In the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query\/blob\/main\/src\/app\/src\/main\/java\/com\/couchbase\/userprofile\/util\/DatabaseManager.java\"><strong>DatabaseManager.java<\/strong><\/a> file, locate the <code>createUniversityDatabaseIndexes()<\/code> function. We create an index on the <code>name<\/code> and <code>location<\/code> properties of the documents in the <em>university<\/em> database.<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>private void createUniversityDatabaseIndexes() {\n  try {\n    universityDatabase.createIndex(&quot;nameLocationIndex&quot;, IndexBuilder.valueIndex(ValueIndexItem.expression(Expression.property(&quot;name&quot;)),\n      ValueIndexItem.expression(Expression.property(&quot;location&quot;))));\n  } catch (CouchbaseLiteException e) {\n      e.printStackTrace();\n  }\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-closing-the-database\" class=\"wp-block-heading\">Closing the Database<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">When a user logs out, we close the Prebuilt Database along with other user-specific databases<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query\/blob\/main\/src\/app\/src\/main\/java\/com\/couchbase\/userprofile\/util\/DatabaseManager.java\"><strong>DatabaseManager.java<\/strong><\/a> file, locate the <code>closePrebuiltDatabase()<\/code> function.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public void closePrebuiltDatabase()\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Closing the database is pretty straightforward<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>userprofileDatabase.close();\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-try-it-out\" class=\"wp-block-heading\">Try It Out<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The app should be running in the emulator.<\/li>\n\n\n<li>Log in to the app with any email Id and password. Let&#8217;s use the values <strong><em>&#8220;<a href=\"mailto:demo@example.com\">demo@example.com<\/a>&#8220;<\/em><\/strong> and <strong><em>&#8220;password&#8221;<\/em><\/strong> for user Id and password fields respectively. If this is the first time that <strong><em>any<\/em><\/strong> user is signing in to the app, the pre-built database will be loaded from the App Bundle. In addition, a new user-specific Database will be created \/ opened.<\/li>\n\n\n<li>Confirm that the console log output has a message similar to the one below. This output also indicates the location of the Prebuilt database as well as the Database for the user. In this example, we are logging in with a user email Id of <strong><em>&#8220;<a href=\"mailto:demo@example.com\">demo@example.com<\/a>&#8220;<\/em><\/strong>.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>2019-06-12 13:07:12.542 24206-24206\/com.couchbase.userprofile I\/CB-Update: Will open Prebuilt DB at path \/data\/user\/0\/com.couchbase.userprofile\/files\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>The above log message indicates the location of the Prebuilt database as well as the Database for the user. This would be within the <em>files<\/em> folder.<\/p>\n<\/li>\n\n\n<li>\n<p>Open the folder on your computer and verify that a Database with name <em>&#8220;univerities&#8221;<\/em> exists along with a user specific Database with name <em>&#8220;userprofile&#8221;<\/em><\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-exploring-the-query-api\" class=\"wp-block-heading\">Exploring the Query API<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Query API in Couchbase Lite is extensive. In our app, we will be using the <code>QueryBuilder<\/code> API to make a simple <em>pattern matching<\/em> query using the <code>like<\/code> operator.<\/p>\n\n\n\n<h4 id=\"h-fetching-university-document\" class=\"wp-block-heading\">Fetching University Document<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">From the &#8220;Your Profile&#8221; screen, when the user taps on the &#8220;Select University&#8221; button, a search screen is displayed where the user can enter the search criteria (name and optionally, the location) for the university.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the search criteria is entered, the local <em>&#8220;universities&#8221;<\/em> Database is queried for <a href=\"#the-university-document\">The &#8220;University&#8221; Document<\/a> documents that match the specified search criteria.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/android-java-cblite-userprofile-query\/blob\/main\/src\/app\/src\/main\/java\/com\/couchbase\/userprofile\/universities\/UniversitiesPresenter.java\"> <strong>UniversitiesPresenter.java<\/strong><\/a> file and locate the <code>fetchUniversities<\/code> function.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public void fetchUniversities(String name) {\n  fetchUniversities(name, null);\n}\n\npublic void fetchUniversities(String name, String country)  \n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We build the Query using the <code>QueryBuilder<\/code> API that will look for Documents that match the specified criteria.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>Expression whereQueryExpression = Function.lower(Expression.property(&quot;name&quot;)).like(Expression.string(&quot;%&quot; + name.toLowerCase() + &quot;%&quot;)); \/\/ &lt;1&gt;\n\nif (country != null &amp;&amp; !country.isEmpty()) {\n  Expression countryQueryExpression = Function.lower(Expression.property(&quot;country&quot;)).like(Expression.string(&quot;%&quot; + country.toLowerCase() + &quot;%&quot;)); \/\/ &lt;2&gt;\n\n  whereQueryExpression = whereQueryExpression.and(countryQueryExpression); \/\/ &lt;3&gt;\n}\n\nQuery query = QueryBuilder.select(SelectResult.all()) \/\/ &lt;4&gt;\n  .from(DataSource.database(database)) \/\/ &lt;5&gt;\n  .where(whereQueryExpression); \/\/ &lt;6&gt;\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Build a <code>QueryExpression<\/code> that uses the <code>like<\/code> operator to look for the specified <em>&#8220;name&#8221;<\/em> string in the <em>&#8220;name&#8221;<\/em> property. Notice a couple of things here:<\/li>\n\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The use of <strong>wildcard &#8220;%&#8221; operator<\/strong> to denote that we are looking for the presence of the string anywhere in the <em>&#8220;name&#8221;<\/em> property and<\/li>\n\n\n<li>The use of <code>Function.lower()<\/code> to convert the search string into lowercase equivalent. Since the <code>like<\/code> operator does <em>case-senstive matching<\/em>, we convert the search string and the property value to lowercase equivalents and compare the two.<\/li>\n\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\">\n<li>If the location criteria were specified in the search, then Build a <code>QueryExpression<\/code> that uses the <code>like<\/code> operator to look for the specified <em>&#8220;location&#8221;<\/em> string in the <em>&#8220;location&#8221;<\/em> property.<\/li>\n\n\n<li>The <code>SelectResult.all()<\/code> specifies that we are interested in all properties in Documents that match the specified criteria<\/li>\n\n\n<li>The <code>DataSource.database(db)<\/code> specified the Data Source<\/li>\n\n\n<li>We include the <code>where<\/code> clause that is the logical ANDing of the QueryExpression in &lt;1&gt; and &lt;2&gt;<\/li>\n\n\n<li>We run the Query by calling the <code>execute()<\/code> method on the Query that was constructed in the previous step<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>try {\n  rows = query.execute();\n} catch (CouchbaseLiteException e) {\n  e.printStackTrace();\n  return;\n}\n\nList&lt;Map&lt;String, Object&gt;&gt; data = new ArrayList&lt;&gt;();\nResult row;\n\nwhile((row = rows.next()) != null) {\n  Map&lt;String, Object&gt; properties = new HashMap&lt;&gt;(); \/\/ &lt;1&gt;\n  properties.put(&quot;name&quot;, row.getDictionary(&quot;universities&quot;).getString(&quot;name&quot;)); \/\/ &lt;2&gt;\n  properties.put(&quot;country&quot;, row.getDictionary(&quot;universities&quot;).getString(&quot;country&quot;)); \/\/ &lt;2&gt;\n  properties.put(&quot;web_pages&quot;, row.getDictionary(&quot;universities&quot;).getArray(&quot;web_pages&quot;)); \/\/ &lt;3&gt;\n  data.add(properties);\n}\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Create an instance of <a href=\"#university-record\">UniversityRecord<\/a> (via <code>HashMap<\/code>).<\/li>\n\n\n<li>Use specific type getters to fetch property values. These UniversityRecord instance is populated with these property values.<\/li>\n\n\n<li>Getters also available for <code>array<\/code> types. This returns a Couchbase Lite <code>ArrayObject<\/code> type.<\/li>\n\n<\/ul>\n\n\n\n<h4 id=\"h-try-it-out\" class=\"wp-block-heading\">Try It Out<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You should have followed the steps discussed in the &#8220;Try It Out&#8221; section under <a href=\"#loading-the-prebuilt-database\">Loading the Prebuilt Database<\/a><\/li>\n\n\n<li>Tap on &#8220;University&#8221; button<\/li>\n\n\n<li>You should see a screen show that allows you to enter the search criteria for the university<\/li>\n\n\n<li>Enter &#8220;Missouri State&#8221; for name. You can optionally enter &#8220;united states&#8221; for location<\/li>\n\n\n<li>Confirm that you see a list of universities that match the criteria<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/university_list.gif\" alt=\"University List\"><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Select a university<\/li>\n\n\n<li>Press the &#8220;Done&#8221; button<\/li>\n\n\n<li>Confirm that the university you selected shows up in the University label<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/university_selection.gif\" alt=\"University Selection\"><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You can optionally fill in other entries in the User Profile screen<\/li>\n\n\n<li>Tap the &#8220;Done&#8221; button<\/li>\n\n\n<li>Confirm that you see an alert message &#8220;Successfully Updated Profile&#8221;. The Document will be updated this time.<\/li>\n\n\n<li>Tap &#8220;Log Off&#8221; and log out of the app<\/li>\n\n\n<li>Log back into the app with the same user email Id and password that you used earlier. In my example, I used <strong><em>&#8220;<a href=\"mailto:demo@example.com\">demo@example.com<\/a>&#8220;<\/em><\/strong> and <strong><em>&#8220;password&#8221;<\/em><\/strong>. So I will log in with those credentials again.<\/li>\n\n\n<li>Confirm that you see the profile screen with the <em>university<\/em> value that you set earlier.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/profile_update.gif\" alt=\"Log Off and Log Back On\"><\/p>\n\n\n\n<h3 id=\"h-learn-more\" class=\"wp-block-heading\">Learn More<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Congratulations on completing this tutorial!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial walked you through an example of how to use a pre-built Couchbase Lite database. We looked at a simple Query example. Check out the following links for further details on the Query API.<\/p>\n\n\n\n<h4 id=\"h-further-reading\" class=\"wp-block-heading\">Further Reading<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/sql-for-json-query-interface-couchbase-mobile\/\">Fundamentals of the Couchbase Lite Query API<\/a><\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/querying-array-collections-couchbase-mobile\/\">Handling Arrays in Queries<\/a><\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/full-text-search-couchbase-mobile-2-0\/\">Couchbase Lite Full Text Search API<\/a><\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/join-queries-couchbase-mobile\/\">Couchbase Lite JOIN Query<\/a><\/li>\n\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Couchbase Lite brings powerful querying and Full-Text-Search(FTS) capabilties to the edge. The new query interface is based on N1QL, Couchbase\u2019s declarative query language that extends SQL for JSON. If you are familiar with SQL, you will feel right at home with the semantics of the new API. The query API is designed using the [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"inline_featured_image":false,"_acf":"","footnotes":""},"tutorial-languages":[595],"tutorial-tags":[587],"tutorial-technologies":[573,585,549],"tutorial-types":[550],"class_list":["post-10262","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-android-java","tutorial-tags-android","tutorial-technologies-fts","tutorial-technologies-mobile","tutorial-technologies-query","tutorial-types-quickstart"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.8 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Quickstart in Couchbase Lite Query with Android and Java - Couchbase<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/\" \/>\n<meta property=\"og:locale\" content=\"de_DE\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Quickstart in Couchbase Lite Query with Android and Java\" \/>\n<meta property=\"og:description\" content=\"Introduction Couchbase Lite brings powerful querying and Full-Text-Search(FTS) capabilties to the edge. The new query interface is based on N1QL, Couchbase\u2019s declarative query language that extends SQL for JSON. If you are familiar with SQL, you will feel right at home with the semantics of the new API. The query API is designed using the [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/\" \/>\n<meta property=\"og:site_name\" content=\"Couchbase\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Couchbase\/\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2548\" \/>\n\t<meta property=\"og:image:height\" content=\"1171\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@couchbase\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"13\u00a0Minuten\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/quickstart-android-java-query\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/quickstart-android-java-query\\\/\",\"name\":\"Quickstart in Couchbase Lite Query with Android and Java - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\"},\"datePublished\":\"2023-06-23T08:43:43+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/quickstart-android-java-query\\\/#breadcrumb\"},\"inLanguage\":\"de\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/quickstart-android-java-query\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/quickstart-android-java-query\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Quickstart in Couchbase Lite Query with Android and Java\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"de\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"de\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"width\":1129,\"height\":1129,\"caption\":\"Couchbase\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/Couchbase\\\/\",\"https:\\\/\\\/x.com\\\/couchbase\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/CouchbaseServer\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/couchbase\\\/\",\"https:\\\/\\\/github.com\\\/couchbase\\\/\",\"https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Couchbase,_Inc.\"],\"description\":\"Couchbase is a database software company headquartered in San Jose, California, providing an operational data platform for AI used by hundreds of global enterprises.\",\"legalName\":\"Couchbase, Inc.\",\"foundingDate\":\"2011-01-01\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Quickstart in Couchbase Lite Query with Android and Java - Couchbase","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/","og_locale":"de_DE","og_type":"article","og_title":"Quickstart in Couchbase Lite Query with Android and Java","og_description":"Introduction Couchbase Lite brings powerful querying and Full-Text-Search(FTS) capabilties to the edge. The new query interface is based on N1QL, Couchbase\u2019s declarative query language that extends SQL for JSON. If you are familiar with SQL, you will feel right at home with the semantics of the new API. The query API is designed using the [&hellip;]","og_url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/","og_site_name":"Couchbase","article_publisher":"https:\/\/www.facebook.com\/Couchbase\/","og_image":[{"width":2548,"height":1171,"url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_site":"@couchbase","twitter_misc":{"Est. reading time":"13\u00a0Minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/","url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/","name":"Quickstart in Couchbase Lite Query with Android and Java - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/de\/#website"},"datePublished":"2023-06-23T08:43:43+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/#breadcrumb"},"inLanguage":"de","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/quickstart-android-java-query\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/"},{"@type":"ListItem","position":2,"name":"Quickstart in Couchbase Lite Query with Android and Java"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/de\/#website","url":"https:\/\/www.couchbase.com\/de\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/de\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/de\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"de"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/de\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/de\/","logo":{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","contentUrl":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","width":1129,"height":1129,"caption":"Couchbase"},"image":{"@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Couchbase\/","https:\/\/x.com\/couchbase","https:\/\/www.youtube.com\/c\/CouchbaseServer","https:\/\/www.linkedin.com\/company\/couchbase\/","https:\/\/github.com\/couchbase\/","https:\/\/en.wikipedia.org\/wiki\/Couchbase,_Inc."],"description":"Couchbase ist ein in San Jose, Kalifornien, ans\u00e4ssiges Unternehmen f\u00fcr Datenbanksoftware, das eine operative Datenplattform f\u00fcr KI bereitstellt, die von Hunderten von globalen Unternehmen eingesetzt wird.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"acf":[],"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10262","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10262\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/media?parent=10262"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-languages?post=10262"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-tags?post=10262"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-technologies?post=10262"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-types?post=10262"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}