Answer the question
In order to leave comments, you need to log in
How to get data without stopping the thread?
Hello! Got stuck: I have an application that, at startup, and / or at the user's command, makes a request to the server (GET). During the request, the application does not respond for several seconds (even though the server is in LAN). I found a solution in Google - AsyncTask, now the request is made nearby in the main thread, without interfering with it. However, I need to process the server response, for this I call the get () method, which, attention, blocks the thread, and the whole point of using AsyncTask is lost. Question: how to get a response from the server asynchronously without freezing the ui thread?
package com.oralo.server_notepad;
import android.os.AsyncTask;
import android.util.Log;
import androidx.core.util.Consumer;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
class NotepadServer extends AsyncTask<String, Void, String> {
private static String API;
private static String TAG = "NOTEPAD_LOG";
public NotepadServer(String api){
API = api;
}
@Override
protected String doInBackground(String... method) {
try {
URL url = new URL(API + method[0]);
System.out.println(Arrays.toString(method));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept-Encoding", "identity");
con.setRequestProperty("secret", "1001");
try (final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
final StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
return content.toString();
}
} catch (final Exception ex) {
ex.printStackTrace();
}
return "404";
}
}
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
server = new NotepadServer(API);
server.execute("add?login=" + login + "&password=" + password + "&body=" + editText.getText().toString());
editText.setText("");
try {
Log.i("server:response", server.get());//тут поток останавливается и ждет ответа
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question