Need help in Rapid Api extension devlopment argent

I Compiled an Rapid Api extension, In Niotron IDE.

It’s giving me runtime error (undefined) In apk.

It’s blocks.

Here is extension.
SatwikGetExtensionnew.aix (9.2 KB)

Its source code.
satwikgetextension.txt (5.6 KB)

Run the method you are using to make an API request inside a thread.

1 Like

I made this code with the help of (chatgpt) now modified as you say,but now getting

compiling error 413

Here is modified code.
.
.
.

package com.satwikgetextension.in;

import android.util.Log;
import com.google.appinventor.components.annotations.;
import com.google.appinventor.components.runtime.
;
import com.google.appinventor.components.common.ComponentCategory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@DesignerComponent(version = 1,
description = “Enhanced extension for interacting with App Inventor blocks, using ExecutorService for asynchronous tasks.”,
category = ComponentCategory.EXTENSION,
nonVisible = true,
iconName = “aiwebres/icon.png”)
@SimpleObject(external = true)
public class SatwikGetExtension extends AndroidNonvisibleComponent {
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
private final HashMap<Integer, Future<?>> taskMap = new HashMap<>();

private String apiUrl;
private String apiKey;
private String apiHost;

public SatwikGetExtension(ComponentContainer container) {
    super(container.$form());
}

@SimpleFunction(description = "Set API details for HTTP requests")
public void SetApiDetails(String url, String apiKey, String apiHost) {
    this.apiUrl = url;
    this.apiKey = apiKey;
    this.apiHost = apiHost;
}

@SimpleFunction(description = "Make HTTP GET Request with Headers")
public void MakeHttpGetRequest(final int taskId) {
    executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                // Your existing MakeHttpGetRequest code here
                if (apiUrl == null || apiKey == null || apiHost == null) {
                    // Dispatch the RequestError event
                    EventDispatcher.dispatchEvent(SatwikGetExtension.this, "RequestError", "API details not set. Call SetApiDetails before making requests.");
                    return;
                }

                URL url = new URL(apiUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                // Set headers using the values set in SetApiDetails
                connection.setRequestProperty("X-RapidAPI-Key", apiKey);
                connection.setRequestProperty("X-RapidAPI-Host", apiHost);

                int responseCode = connection.getResponseCode();
                Log.d("SatwikGetExtension", "Response Code: " + responseCode);

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // Read response data using an InputStreamReader
                    InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    StringBuilder response = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    reader.close();
                    inputStreamReader.close();
                    connection.disconnect();

                    // Dispatch the GotHttpResponse event with the taskId parameter
                    EventDispatcher.dispatchEvent(SatwikGetExtension.this, "GotHttpResponse", response.toString(), responseCode, taskId);
                } else {
                    connection.disconnect();
                    // Dispatch the RequestError event
                    EventDispatcher.dispatchEvent(SatwikGetExtension.this, "RequestError", "HTTP request failed with response code: " + responseCode);
                }

            } catch (IOException e) {
                e.printStackTrace();
                // Dispatch the RequestError event
                EventDispatcher.dispatchEvent(SatwikGetExtension.this, "RequestError", "Error during HTTP request: " + e.getMessage());
            }
        }
    });
}

@SimpleFunction(description = "Cancels an asynchronous task with a specific identifier.")
public void CancelAsyncTask(int taskId) {
    try {
        Future<?> future = taskMap.get(taskId);
        if (future != null) {
            future.cancel(true);
            taskMap.remove(taskId);
        } else {
            // Dispatch the AsyncTaskErrorOccurred event
            EventDispatcher.dispatchEvent(this, "AsyncTaskErrorOccurred", taskId, "Task ID not found: " + taskId);
        }
    } catch (Exception e) {
        // Dispatch the AsyncTaskErrorOccurred event
        EventDispatcher.dispatchEvent(this, "AsyncTaskErrorOccurred", taskId, "Failed to cancel task: " + e.getMessage());
    }
}

@SimpleEvent(description = "Event fired when the asynchronous task with delay is completed.")
public void AsyncTaskWithDelayCompleted(int taskId) {
    EventDispatcher.dispatchEvent(this, "AsyncTaskWithDelayCompleted", taskId);
}

@SimpleEvent(description = "Event fired when an error occurs in an asynchronous task.")
public void AsyncTaskErrorOccurred(int taskId, String errorMessage) {
    EventDispatcher.dispatchEvent(this, "AsyncTaskErrorOccurred", taskId, errorMessage);
}

@SimpleEvent(description = "Event fired when an error occurs in an HTTP request.")
public void RequestError(String errorMessage) {
    EventDispatcher.dispatchEvent(this, "RequestError", errorMessage);
}

@SimpleEvent(description = "Event fired when HTTP response is received.")
public void GotHttpResponse(String response, int responseCode, int taskId) {
    EventDispatcher.dispatchEvent(this, "GotHttpResponse", response, responseCode, taskId);
}

}

I don’t know java.

I know web component do this job perfectly, but just want to work with these

This post was flagged by the community and is temporarily hidden.

This post was flagged by the community and is temporarily hidden.

You should learn it first.

1 Like

:pensive: I will but for now please.

I trying from yesterday. Yes with gpt. But getting error and arror and error.:face_with_head_bandage:

Now I created the code from app inventor example code.

Currently getting this error.

Screenshot_2024-03-04-07-17-14-44_724829578cdd387db4526584b07fc1f0

Used jar file :-
1)okhttp-3.9.0.jar
2)json-20220924.jar

.
.
Source code.(Open source)

.
.
package com.satwikapi.in;

import android.app.Activity;
import android.content.Context;
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.EventDispatcher;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@DesignerComponent(
version = 1,
description = “”,
category = ComponentCategory.EXTENSION,
nonVisible = true,
iconName = “”)

@SimpleObject(external = true)
//Libraries
@UsesLibraries(libraries = “”)
//Permissions
@UsesPermissions(permissionNames = “”)

public class SatwikApi extends AndroidNonvisibleComponent {

public String apiresponse;

public SatwikApi(ComponentContainer container) {
    super(container.$form());
}

@SimpleFunction(description = "Get data from the API")
public void GetData(String url, String apiKey, String apiHost) {
    if (url == null || apiKey == null || apiHost == null) {
        Error("One or more parameters are null");
        return;
    }

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .get()
            .addHeader("X-RapidAPI-Key", apiKey)
            .addHeader("X-RapidAPI-Host", apiHost)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            Error(e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                final int responseCode = response.code();
                if (response.isSuccessful()) {
                    apiresponse = response.body().string();
                    form.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            GotData(apiresponse, responseCode);
                        }
                    });
                } else {
                    Error("Response not successful: " + responseCode);
                }
            } catch (IOException e) {
                e.printStackTrace();
                Error("Error processing response body");
            }
        }
    });
}

@SimpleEvent(description = "This event is fired when an error has occurred.")
public void Error(String error) {
    EventDispatcher.dispatchEvent(this, "Error", error);
}

@SimpleEvent(description = "This event is fired when the extension has successfully retrieved the data.")
public void GotData(String data, int responseCode) {
    EventDispatcher.dispatchEvent(this, "GotData", data, responseCode);
}

}

I think you have to help me now?

image

Over here, in the @UsesLibraries, it should be like this:

@UsesLibraries(libraries = “okhttp-3.9.0.jar, json-20220924.jar”)

Ok.wait checking.

Now getting another error :confused:.

For counter error I use ( okio-1.13.0.jar )
Now getting.

Response not successful: 500, and app crashesh.

I used wrong (api-key,url,host) thats why it’s generating error 500.
I searched on gpt it’s say eternal server problem( I checked my blocks, I used default key that’s why I think it is generated error.

With correct parameters it is working fine.:relaxed:

Extension blocks

Source code.
SatwikApi.txt (4.0 KB)

Used liabraries zip.
jar container.zip (518.5 KB)

Extension file.
SatwikApi.aix (471.4 KB)

Special Thanks.

  1. @Xoma ( on app inventor huge collection of
    example code. Help me to
    understand code. And once
    again.thank you for helping here also.)

  2. @Akshat_Rana ( thank you for replying on this
    topic. Your to good person
    liked your helping nature.)

  3. @vknow360 ( Thank you for your reply, due
    to your reply I understand
    basics of extension
    Development.)

  4. chatgpt. Helped to solve errors.

      As a B.A student this was really tuff for me.
    
2 Likes

What is the purpose of your extension?
Please provide also a short documentation about the methods and events

Taifun

) {Made for Rapid Api}

)Uses of this Extension:
No need to create List of headers.

)How it works here is the Example blocks. To parse Response data used (Jsontool extension. Provided by Techy Rakshak )

Please explain more… What is the Rapid API?
And why should we use the extension? What is the advantage to use this extension compared to just set 2 headers and use the web component?

Taifun

1 Like