Need help for build extension

Hello, I am getting to know the appyBuilder IDE and trying to build an extension with “HttpURLConnection”.
The extension is built successfully but when I test it on kodular I get a "Runtime Error. undefined. Note: You will not see another error reported for 5 seconds. ". But I don’t know how what is wrong.
Please help me figure out what is wrong.
This is my code :

public class DocxpressoCloud extends AndroidNonvisibleComponent {
private ComponentContainer container;
private Activity activity;
private Context context;
/**
* @param container container, component will be placed in
*/
public DocxpressoCloud(ComponentContainer container) {
super(container.$form());
this.container = container;
this.activity = (Activity) container.$context();
}

@SimpleFunction (description=“Create a form to post”)
public void CallConvert (String email, String name, String numberPhone, String message) throws IOException {
URL http = new URL(“https://httpbingo.org/post”);
Map<String,Object> params = new LinkedHashMap<>();
params.put(“email”, email);
params.put(“name”, name);
params.put(“numberPhone”, numberPhone);
params.put(“message”, message);

  StringBuilder postData = new StringBuilder();
  for (Map.Entry<String,Object> param : params.entrySet()) {
    	if (postData.length()!= 0) postData.append('&');
  		postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
  		postData.append("=");
  		postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
  }
  byte[] postDataBytes = postData.toString().getBytes("UTF-8");
                        
  
 HttpURLConnection connection = (HttpURLConnection)http.openConnection();
 connection.setRequestMethod("POST");
 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 connection.setDoOutput(true);
 connection.getOutputStream().write(postDataBytes);
                        
 Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                        
            try {            
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
          sb.append((char)c);
                        
String response = sb.toString();
JSONObject myData = new JSONObject(response.toString());

String url = myData.getString("url");
String data = myData.getString("data");                        
GetData(url, data);  
              } catch(Exception e) {
   //System.out.println(e);
              GetError(e.getMessage());
 }

}

@SimpleEvent(description="Now you can use the data")
public void GetData(String url, String data){
EventDispatcher.dispatchEvent(this, "GetData", url, data);
		}

@SimpleEvent(description="If you catch an error")
public void GetError(String error){
EventDispatcher.dispatchEvent(this, "Error", error);
	}

}

Show the blocks image i want to check if you are putting the correct params

You should be aware that you can’t run long running operations on main thread.
You must run that in a background thread and post result to main thread whenever you get the result.

2 Likes

Here are my blocks.

I don’t understand how I can do this. can i have an example please.

You should run network operation in background thread instead of UI thread so that UI thread is not freezed .
Running Android tasks in background threads | Android Developers

I mostly use this method, It may help you.
To start a operation in new thread :

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
// Do your network operation here in new thread
}});
thread.start();

To pass value to UI thread again,

activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // call the event block from here 
                    }
                });
2 Likes

Thank you for your help. I have tried your method but I am only getting errors. I think the structure I have written is not suitable. The error is “error: illegal start of expression”.

This is the thread :

Thread thread = new Thread(new Runnable() {
@Override
public void run() {

  URL http = new URL("https://httpbingo.org/post");
  Map<String,Object> params = new LinkedHashMap<>();
  params.put("email", String email);
  params.put("name", String name);
  params.put("numberPhone", int numberPhone);
  params.put("message", String message);
 
  StringBuilder postData = new StringBuilder();
  for (Map.Entry<String,Object> param : params.entrySet()) {
    	if (postData.length()!= 0) postData.append('&');
  		postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
  		postData.append("=");
  		postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
  }
  byte[] postDataBytes = postData.toString().getBytes("UTF-8");
                        
  
 HttpURLConnection connection = (HttpURLConnection)http.openConnection();
 connection.setRequestMethod("POST");
 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 connection.setDoOutput(true);
 connection.getOutputStream().write(postDataBytes);

      }});

And the call block event :
@SimpleFunction (description=“Create a form to post”)
public void CallConvert (String email, String name, int numberPhone, String message) throws IOException {

      thread.start();
           activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { 
                
                  
                   Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
  
                                try {            
              StringBuilder sb = new StringBuilder();
              for (int c; (c = in.read()) >= 0;)
                        sb.append((char)c);

              String response = sb.toString();
              JSONObject myData = new JSONObject(response.toString());

              String url = myData.getString("url");
              String data = myData.getString("data");                        
              GetData(url, data);  
                            } catch(Exception e) {
                 //System.out.println(e);
                            GetError(e.getMessage());
               }
                  
                  
                }
            });                                 


}
2 Likes

Show your import.

/*
* I guess this example will help you -- Don't copy paste this , try to understand this
* I've edited this here so it may have error, so as I said, try to understand --don't copy paste--
* @author oseamiya
*/
@SimpleFunction
public void Post(String urls){
(new Thread(new Runnable() {
            @Override
            public void run() {
            HttpURLConnection httpURLConnection = null;
                InputStream inputStream = null;
                try {
                    URL url = new URL(urls);
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.setRequestProperty("Content-Type", "application/json");
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setRequestMethod(method);
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode / 100 == 2) {
                        inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                        String res = convertStreamToString(inputStream);
                        if(res != null){
                            activity.runOnUiThread(new Runnable(){
                                @Override
                                 public void run(){
                                 OnSuccess(res);
                                 }
                            });
                        }
                    } else {
                        String res = convertStreamToString(httpURLConnection.getErrorStream());
                        if(res != null){
                             activity.runOnUiThread(new Runnable(){
                                @Override
                                 public void run(){
                                 OnError(res);
                                 }
                            });
                        }
                    }
                   } catch(Exception e){
                       e.printStackTrace();
                      // You can trigger OnError method here in UI thread too
                   } finally {
                    if (httpUrlConnection != null) {
                        httpUrlConnection.disconnect();
                    }
})).start();
}
@SimpleEvent
public void OnSuccess(String data){
    EventDispatcher.dispatchEvent(this, "OnSuccess", data);
}
@SimpleEvent
public void OnError(String error){
    EventDispatcher.dispatchEvent(this, "OnError", error);
}
private String convertStreamToString(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        try {
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toString();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
			if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
1 Like

What to import ?

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.