# Java/Kotlin (Android Studio)

## Using Java

### Download .jar library

Download the NEP Java library using the next link:

[Download nep-0.0.1.jar](https://bitbucket.org/enriquecoronadozu/nep-installers/downloads/nep-0.0.1.jar)

{% hint style="info" %}
This tutorial needs NEP-CLI to version 0.2.0 or above, or NEP+ App 0.0.5 or above.
{% endhint %}

### Include .jar library

1. **Copy .jar to the "libs" Directory:** Navigate to the **apps/libs** directory in the Android Studio project and copy and paste the .jar file, such as the figure below.

<figure><img src="https://423882023-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9aELFWec9V26rEZKHjDA%2Fuploads%2FMyAXMcs2KuuUhWvyE5fT%2Flibs%2018_03_2024%2008_16_00%20p.%20m..png?alt=media&#x26;token=670d7c51-98ae-426f-9a14-c70791a3fc41" alt=""><figcaption></figcaption></figure>

2. **Include the required `.jar` file in Your Project:** In Android Studio open build.gradle(Module:app) located in Grandle Scripts -> build.gradle and the next **dependencies**:

{% code title="bundle.gradle(:app)" %}

```json
implementation 'org.zeromq:jeromq:0.5.2'
implementation 'com.google.code.gson:gson:2.10.1'
implementation files('/libs/nep-0.0.1.jar')
```

{% endcode %}

3. **Sync Gradle Files:**  Click on the "Sync Project with Gradle Files" button in the toolbar. This action ensures that the newly added library is properly included in your project's build configuration.
4. **Verify the Gradle Sync:** Once the Gradle sync is complete, verify that there are no errors in the Gradle console.
5. **Configure Network Permissions:** Since your app will be using network sockets, you need to ensure that your AndroidManifest.xml file includes the necessary permissions. Add the following permission to your manifest file:

{% code title="Android.Manifest.xml" %}

```xml
<uses-permission android:name="android.permission.INTERNET" />
```

{% endcode %}

### Create a simple publisher:

Import NEP libraries to the MainActivity file as follows:

{% code title="MainActivity.java" %}

```java
import nep.Node;
import nep.Publisher;
```

{% endcode %}

Modify the MainActivity class as follows:

<pre class="language-java" data-title="MainActivity.java" data-line-numbers><code class="lang-java">
public class MainActivity extends AppCompatActivity {

    private Publisher pub;
    private Node node;
<strong>    private String nepMasterIP = "192.168.0.178";
</strong>    private int index = 0;

    private static class JsonValue {
        int result;

        public JsonValue(int result) {
            this.result = result;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        node = new Node("android_test");
        pub = node.new_pub("test", "json", nepMasterIP);
    }

    public void onClickBtn(View v)
    {

        if (pub.started)
        {
            JsonValue jsonValue = new JsonValue(index++);
            pub.publish(jsonValue);
        }

    }

</code></pre>

Update `nepMasterIP` (line 6) with the IP address of the computer running the NEP master server (using NEP-CLI or NEP+ App).

Add a button in activity\_main.xml and inside the XML layout (code ) file set its `onClick` attribute to execute a function named `onClickBtn`

<pre class="language-xml" data-title="activity_main.xml" data-line-numbers><code class="lang-xml">   &#x3C;Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
<strong>        android:onClick="onClickBtn"
</strong>        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</code></pre>

In this example `onClick` attribute is set in line 5.

### Add a simple subscriber:

For this example, we need to import the next packages/libraries:

```java
import nep.Subscriber;
import com.google.gson.Gson;
import android.os.AsyncTask;
import java.io.IOException;
```

To the previous code, we will add a background thread or AsyncTask to perform socket communication operations. AsyncTask is a convenient way to perform background tasks and update the UI thread with the results.&#x20;

Here's an example of how you can define an AsyncTask to handle socket communication:

```java

public class SubscriberTask extends AsyncTask<Void, String, Void> {

        private Node node;
        private Subscriber sub;

        // Constructor to initialize the node
        public SubscriberTask(Node node) {
            this.node = node;
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Perform socket communication operations here
            // This method runs on a background thread
            // Create a new subscriber with the topic <'test'>
            sub = node.new_sub("test", "json", nepMasterIP);


            while (!isCancelled()) {
                String msg = null; // Message obtained as an String
                try {
                    msg = sub.listen();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (!"{}".equals(msg)) // If message is not {}
                {
                    System.out.println(msg);
                    // Then, convert string to Java object
                    Gson gson = new Gson();
                    JsonValue obj = gson.fromJson(msg,JsonValue.class);
                    // Print message
                    System.out.println(obj.result);
                }
            }

            // Clean up resources when finished
            sub.close();
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            // Update the UI with the received message
            String message = values[0];
            // Handle the received message as needed
        }
    }
```

After defining the AsyncTask, you can create an instance of it and execute it to start listening to the subscriber. You can execute the AsyncTask in the `onCreate()` method of your Activity or wherever appropriate.

<pre class="language-java"><code class="lang-java">    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        node = new Node("android_test");
        pub = node.new_pub("test", "json", nepMasterIP);
<strong>        subscriberTask = new SubscriberTask(node);
</strong><strong>        subscriberTask.execute();
</strong>    }
</code></pre>

Ensure that you properly handle cleanup when your AsyncTask is no longer needed. You can cancel the AsyncTask and clean up resources in the `onDestroy()` method of your Activity or wherever appropriate.

```java
   @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscriberTask != null) {
            subscriberTask.cancel(true);
        }
    }
```

An example of putting it all together is shown below:

<pre class="language-java" data-title="MainActivity.java" data-line-numbers><code class="lang-java">...

import nep.Node;
import nep.Publisher;

import nep.Subscriber;
import com.google.gson.Gson;
import android.os.AsyncTask;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private Publisher pub;
    private Node node;
<strong>    private String nepMasterIP = "192.168.0.178";
</strong>    private int index = 0;

    SubscriberTask subscriberTask;

    private static class JsonValue {
        int result;

        public JsonValue(int result) {
            this.result = result;
        }
    }


    public class SubscriberTask extends AsyncTask&#x3C;Void, String, Void> {

        private Node node;
        private Subscriber sub;

        // Constructor to initialize the node
        public SubscriberTask(Node node) {
            this.node = node;
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Perform socket communication operations here
            // This method runs on a background thread
            // Create a new publisher with the topic &#x3C;'test'>
<strong>            sub = node.new_sub("test", "json", nepMasterIP);
</strong>

            while (!isCancelled()) {
                String msg = null; // Message obtained as an String
                try {
<strong>                    msg = sub.listen();
</strong>                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (!"{}".equals(msg)) // If message is not {}
                {
                    System.out.println(msg);
                    // Then, convert string to Java object
                    Gson gson = new Gson();
                    JsonValue obj = gson.fromJson(msg,JsonValue.class);
                    // Print message
                    System.out.println(obj.result);
                }
            }

            // Clean up resources when finished
            sub.close();
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            // Update the UI with the received message
            String message = values[0];
            // Handle the received message as needed
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
<strong>        node = new Node("android_test");
</strong><strong>        pub = node.new_pub("test", "json", nepMasterIP);
</strong>        subscriberTask = new SubscriberTask(node);
        subscriberTask.execute();
    }

    public void onClickBtn(View v)
    {

        if (pub.started)
        {
            JsonValue jsonValue = new JsonValue(index++);
<strong>            pub.publish(jsonValue);
</strong>        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscriberTask != null) {
            subscriberTask.cancel(true);
        }
    }
}
</code></pre>

## Using Koltin (Soon ...)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coronadoenrique.gitbook.io/nep+/programming-enviroments/java-kotlin-android-studio.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
