Getting multiple errors while writing an extension

There are some Java concepts that you need to clear up. Look at your getJoke function.

First of all, you should rename the function according to the naming conventions to GetJoke.

Second, you don’t have to import activity and context. They are replaceable with the variable form, because Form implements activity and context. Do not use context.this, use form.

On top of this, you need to understand when to return a value. A void function does not return a value, it only does something. If you want to return a value, use String; however in this context, you are running something using the Internet, so you should rather call an event.

With all of those cleared up, I rewrote your code. You also have to add the JSON library found here which you forgot. (json-20220924.jar)

You must also replace the ellipsis in the line .addHeader("X-RapidAPI-Key", "...") with your own Rapid API key.

package com.gordonlu.expressjokes;

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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
        
import java.io.IOException;
        
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
        
@DesignerComponent(
    version = 1,
    description = "Introducing the ExpressJokes extension! Be no more worried to entertain your users. Simply use the extension to get a new, randomly selected joke delivered straight to your app. Whether you're looking to make your users laugh or just need a quick pick-me-up for our admin panel, this extension has you covered. Give it a try and bring some joy to your day!",
    category = ComponentCategory.EXTENSION,
    nonVisible = true,
    iconName = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhL5ve5hVzd7Oa5HY0FjGcXg8ybTBPqu0rDxrGJmltzDh9QK5kXlQpiMDoFarZNp0LWlKcHt_O9YhAo-Bd7pHYbivQ8_ji4O-fzr9ioyF4FCe9tDWUaAzW6x1SoKq4dCMm7D2FX7gfjWtdOJjsIA8WHm41mmvSTnl08oAOfGpoW2jV3bxQq9ntSC4B/s320/expressJoke.jpg")
    
@SimpleObject(external = true)
@UsesLibraries(libraries = "okhttp-3.9.0.jar,json-20220924.jar")
@UsesPermissions(permissionNames = "android.permission.INTERNET")
        
public class ExpressJokes extends AndroidNonvisibleComponent {
        
    public String apiresponse;
    public String joke;
        
    public ExpressJokes(ComponentContainer container){
        super(container.$form());
    }
        
    @SimpleFunction(description = "Get a new, randomly selected joke delivered")
    public void GetJoke(){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes")
                .get()
                .addHeader("X-RapidAPI-Key", "...")
                .addHeader("X-RapidAPI-Host", "jokes-by-api-ninjas.p.rapidapi.com")
                .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 {
                if(response.isSuccessful()){
                    apiresponse = response.body().string();
                    form.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONArray jsonArray = new JSONArray(apiresponse);
                                JSONObject jsonObject = jsonArray.getJSONObject(0);
                                joke = jsonObject.getString("joke");
                                GotJoke(joke);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Error(e.getMessage());
                            }
                        }
                    });
                }
            }
        });
    }

    @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 joke.")
    public void GotJoke(String joke) {
        EventDispatcher.dispatchEvent(this, "GotJoke", joke);
    }
}

3 Likes