2

I made an android app 5 years ago that use AsyncTask to create an HTTP POST request to send a receive data from server, with two parameters. Any help would be appreciated, thanks

Call example:

String asyncResult = new AsyncCall().execute(UrlServer, jsonData.toString()).get();

My basic AsyncTask Class

public class AsyncCall extends AsyncTask<String, String, String>{

private static final int CONNECTION_TIMEOUT=10000;
private static final int READ_TIMEOUT=15000;

@Override
protected void onPreExecute() {
    super.onPreExecute();

}
@Override
protected String doInBackground(String... params) {
    //URL: params[0]
    //JSON Data: params[1]
    
    // I made HTTP URL CONNECTION and store server data in result variable
}

@Override
protected void onPostExecute(String result) {

    return result;
}
Cristian
  • 329
  • 2
  • 6
  • 14
  • Does this answer your question? [Android Asynctask deprecated. Need substitute examples](https://stackoverflow.com/questions/62438770/android-asynctask-deprecated-need-substitute-examples) – Liastre Oct 23 '20 at 09:43
  • I prefere to convert java code into Kotlin coroutines with async – Cristian Oct 24 '20 at 07:37

4 Answers4

0

Use ExecutorService with methods.

Instead of calling the asynctask, call method with parameters.

String asyncResult = AsyncCall(UrlServer, jsonData.toString());

Create method to handle the parameters.

public String AsyncCall(String UrlServer, String jsonData) {

private static final int CONNECTION_TIMEOUT=10000;
private static final int READ_TIMEOUT=15000;
private static String getResult = null;

  ExecutorService executor = Executors.newSingleThreadExecutor();
  Handler handler = new Handler(Looper.getMainLooper());
   
  executor.execute(() -> {
        //Background work here
        
    //URL: params[0]
    String URL = UrlServer;
    //JSON Data: params[1]
    String JSONData = jsonData;
    
    // I made HTTP URL CONNECTION and store server data in result variable
    
    getResult = result;
    
    handler.post(() -> {
        //UI Thread work here
        return result;
    });
  });
 }
Jayavinoth
  • 544
  • 1
  • 9
  • 24
0

Use retrofit for http post request as it is easy and flexible.

0

I couldn't get compiled what #Jayavinoth proposed, so I worked out of it solution, that worked for me. Additionally I put that in the external class for sanity and clarity purpose. But you can move it to the MainActivity and get rid of reference to it.

public class GetAsyncURL {
private final MainActivity mainActivity;

public GetAsyncURL (MainActivity mainActivity) {
    this.mainActivity = mainActivity; 
}


public void asyncCall(String urlServer) {

    AtomicReference<String> getResult = new AtomicReference<>();

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Handler handler = new Handler(Looper.getMainLooper());

    executor.execute(() -> {
        //Background work here

        String answerHTTP = null;
        try {
            answerHTTP = getUrlString(urlServer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        getResult.set(answerHTTP);

        handler.post(() -> {
            //UI Thread work here
            if(getResult.get() != null && !getResult.get().equals("")) {
                mainActivity.process_your_result_in_main(getResult.get());
            }
        });
    });
}



private static String getUrlString(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    URLConnection connection = url.openConnection();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = connection.getInputStream();

    int bytesRead;
    byte[] buffer = new byte[65536];
    while((bytesRead = in.read(buffer)) > 0) {
        out.write(buffer, 0, bytesRead);
    }
    out.close();
    return out.toString();
}

}

Then you call it simply with:

new GetAsyncURL(this).asyncCall(your_url);
basileus
  • 295
  • 3
  • 9
-1
  ExecutorService executor = Executors.newSingleThreadExecutor();
  Handler handler = new Handler(Looper.getMainLooper());
  executor.execute(() -> {
        //Background work here
        handler.post(() -> {
            //UI Thread work here
        });
  });
  • 2
    Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it answers the specific question being asked. See [answer]. – ChrisGPT was on strike Apr 09 '21 at 00:38