I'm new to Android Java and I would really appreciate it I can get some references and/or examples to make some simple network calls without using AsyncTask.
I'm making a program to parse a simple JSON Object from a URL.
In Android 11 (API 30), All AsyncTask are going to be deprecated as shown here:
https://developer.android.com/reference/android/os/AsyncTask
This is an example of how to send a request without AsyncTask using Thread
void send_request(final String url) {
try {
Thread thread = new Thread() {
public void run() {
Looper.prepare();
final JSONObject[] maindata = {new JSONObject()};
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
String data = "";
String error_data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
int status = httpURLConnection.getResponseCode();
Log.d("GET RX", " status=> " + status);
try {
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
Log.d("GET RX =>", " " + data);
sdbw sd = new sdbw(act);
maindata[0] = new JSONObject(data);
} catch (Exception exx) {
InputStream error = httpURLConnection.getErrorStream();
InputStreamReader inputStreamReader2 = new InputStreamReader(error);
int inputStreamData2 = inputStreamReader2.read();
while (inputStreamData2 != -1) {
char current = (char) inputStreamData2;
inputStreamData2 = inputStreamReader2.read();
error_data += current;
}
Log.e("TX", "error => " + error_data);
}
} catch (Exception e) {
Log.e("TX", " error => " + e.getMessage());
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, 2000);
Looper.loop();
}
};
thread.start();
} catch (Exception ex) {
Log.e("ERROR =>", "" + ex.getMessage());
ex.printStackTrace();
}
}
Heres what i found for room query, works well
val x = Executors.newSingleThreadExecutor().submit(Callable { mDao.getX() }).get()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With