I have always worked with the class Asyntask
but today it is obsolete.
Default constructor in android.os.AsyncTask is deprecated
Also lately I have seen that it is damaging some parts of the code, I have changed a couple of classes little by little but because I perform different functions I cannot afford to modify absolutely all the classes where I use the Asyntask
, I have been looking for information about it but I'm afraid of breaking my code by changing something I've always been working on, so I'm sharing a couple of classes below so you can better understand the way I've been working all this time.
this is a counter in the shopping cart.
public class ContadorProductos {
public static class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void> {
@SuppressLint("StaticFieldLeak")
public Context context;
HttpResponse httpResponse;
JSONArray jsonObject = null;
String StringHolder = "";
String contador_url = "http://pedidoslab.6te.net/consultas/contadorProdPedidos.php" + "?id_prefactura=" + Login.gIdPedido;
public static Double gCount = 0.0;
DecimalFormat formatoDecimal = new DecimalFormat("#");
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(contador_url);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONArray(0);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
try {
JSONObject responseJSON = new JSONObject(String.valueOf(StringHolder));
gCount = (responseJSON.getJSONArray("voto").getJSONObject(0).getDouble("count"));
ObtenerProductos.tvCantProductos.setText(String.valueOf(formatoDecimal.format(gCount)));
ObtenerCategorias.tvCantProd3.setText(String.valueOf(formatoDecimal.format(gCount)));
//ObtenerAllProductos.tvCantProductos2.setText(String.valueOf(formatoDecimal.format(gCount)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In this class I eliminate orders
public class EliminarDetPedido extends AsyncTask<String, Void, String> {
private final WeakReference<Context> context;
public static boolean exitoDeleteProd = false;
Double total = 0.00;
public EliminarDetPedido(Context context) {
this.context = new WeakReference<>(context);
}
protected String doInBackground(String... params) {
String registrar_url = "http://pedidoslab.6te.net/consultas/EliminarDetPedido.php" + "?id_det_prefactura=" + adapProdReport.lidDetPedido;
String resultado;
try {
URL url = new URL(registrar_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
String idDetPrefactura = String.valueOf(adapProdReport.lidDetPedido);
String data = URLEncoder.encode("id_det_prefactura", "UTF-8") + "=" + URLEncoder.encode(idDetPrefactura, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
resultado = stringBuilder.toString();
//if(equals("Record deleted successfully")) {
exitoDeleteProd = true;
total = TicketDatos.gTotal - adapProdReport.lDetMontoFinal;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
TicketDatos.subTotalReporte.setText(String.valueOf(total));
}
});
//}else{
// exitoDeleteProd = false;
//}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
Log.d("MiAPP", "Se ha utilizado una URL con formato incorrecto");
resultado = "Se ha producido un ERROR";
} catch (IOException e) {
Log.d("MiAPP", "Error inesperado!, posibles problemas de conexion de red");
resultado = "Se ha producido un ERROR, comprueba tu conexion a Internet";
}
return resultado;
}
}
And this would be the way in which I have been working throughout the project, based on my code, what alternatives could they give me to change the complete nomenclature, it would help me a lot if they give me some advice on how to implement a new code.
The documentation recommends using kotlin coroutines for all async tasks but obviously this only works in kotlin. If you are still using Java, your best option is the RxJava library, which offers very similar features.
Of course there are also native options and they are in the package mentioned in the class warning
AsyncTask
:Those APIs are not very comfortable to use but, if you are interested, this is the guide on how to do it.
For http requests, the recommended library is Retrofit . In the official android course it is explained how to use it but I will give you an example applied to your case. The two classes you show could be replaced by just one interface that has a method for each query you need. Retrofit will then use the information in the annotations to automatically generate the implementation of that interface.
Each function must have the annotation of the corresponding http method (GET, POST, etc) within it the url is written (only the part that changes, the baseUrl is indicated elsewhere). Query parameters are added with the
@Query
. The return type indicates which class you want to convert the response to, but since the calls are asynchronous, you need to wrap it with some observable class.Call
it is the interface that retrofit brings but you can also use those of other libraries such as LiveData or any of the RxJava observable classes. In the example I convert the response toString
but most often it is to one of your own classes. More info in the documentation .In kotlin, you can make a function asynchronous simply by adding the word
suspend
. This way you can define the return type you want without the need for any wrapper