Convert AsyncTask to RxJava in Android studio java - java

First, I'm brand new to java on android studio, and trying to use codes from github using asyncTask. However AsyncTask is deprecated so it needs to be replaced with rxJava according to what I was suggested. I'd appreciate if someone help convert the code below to rxJava. Thank you.
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("DownloadTask","DownloadTask : " + data);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Directions in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}

Related

Issue accessing a variable in a Java class

I am trying to access the variable ArrayofTaxiDrivers in the class DownloadTask from the onCreate method of my activity file. However the variable is blank when accessed this way. The content does show when accessed from within the onPostExecute method of DownloadTask though.
Any help is greatly appreciated!
public class DownloadTask extends AsyncTask<String,Void,String> {
ArrayList<TaxiDriver> ArrayofTaxiDrivers = new ArrayList<TaxiDriver>();
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray items = jsonObject.getJSONArray("items");
DownloadTask task = new DownloadTask();
for(int i=0; i<items.length(); i++) {
JSONObject itemsObject = items.getJSONObject(i);
JSONObject fields = itemsObject.getJSONObject("fields");
task.addTaxiDriver(new TaxiDriver(fields.getString("name"), fields.getString("contact")));(asList(fields.getString("name"), fields.getString("contact"))));
}
Log.i("info",task.ArrayofTaxiDrivers.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_taxi_main);
DownloadTask task = new DownloadTask();
task.execute("https://test.com/json");
Log.i("info",task.ArrayofTaxiDrivers.toString());
}
When you call
task.execute("https://test.com/json");
the task will be executed based on its priority. For this reason the onPostExecute will be called after some time and probably after the onCreate
Log.i("info",task.ArrayofTaxiDrivers.toString());
I suggest you to think that "execute" is an instruction that exits immediatly and only after a while it will be executed.
I am trying to access the variable ArrayofTaxiDrivers in the class
DownloadTask from the onCreate method of my Activity.
That is because when you created DownloadTask, the List ArryofTaxiDrivers is initialized and at that time the size of the List is zero.
If you have the data in the onPostExecute() method, that means it was probably added by AsyncTask's doInBackground() method. Could be somewhere else entirely depending on your code.
Now the AsyncTask works asynchronously: it means that while it has been kicked to start executing, it doesn't start right away. However it will eventually start executing.
So when you access the list in onCreate() of the Activity, the list doesn't have any data because you haven't added to it.
What you should do
Instead implement an interface/callback to notify the Activity that the data is loaded and ready to be used. This callback can come from onPostExecute().

Execute Async Tasks one after another

I know that there are already some discussions and I searched on the internet a lot for a solution, I have 3 get calls (volley) I want to execute one after another because the next get does need variables which were set on the get before this but it doesn't seem to work here. When I debug the whole process it worked fine of course but when running the app normally it doesn't get any data which I would have gotten when debugging it.
Now I tried to set static boolean variables to make this whole thing work but theres so far no success..
public class AsyncToken extends AsyncTask<String , Void, Void> {
private PacketBuilder pb = new PacketBuilder();
private Context context;
AsyncUser u = new AsyncUser(context);
#Override
protected Void doInBackground(String... params) {
while( task1finished == false )
{
try
{
Log.d("App", "Waiting for GetTask");
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
Log.d("App", "GetTask finished");
// Do what ever you like
// ...
pb.Get("token", "", params[0], context);
return null;
}
protected void onPostExecute(String ... params)
{
task2finished = true;
}
public AsyncToken(Context context)
{
this.context = context;
}
}
EDIT, the code:
When async task is completed onPostExecute() is called, so start another async task with computed values there. You can have global variables what should be computed or you can pass them through parameters.
//start first async task
new TaskOne().execute();
class TaskOne extends AsyncTask<Void,Void,String>{
String tmp;
#Override
protected String doInBackground(Void... records) {
tmp = computeNeededValue();
return tmp;
}
#Override
protected void onPostExecute(String result) {
new TaskTwo().execute(tmp);
}
)
class TaskTwo extends AsyncTask<String,Void,Void>{
#Override
protected Void doInBackground(String... records) {
//use computed value from first task here
}
#Override
protected void onPostExecute(Void result) {
//start another async task
}
)

Send a value from a listener interface to onPostExecute in AsyncTask class

I'm actually trying to build a WebSocket client application on Android with the nv-websocket-client.
But I'm stuck with interfaces in my doInBackground function.
I'm trying to use a AsyncTask for the WebSocket connetion, but I'm stuck when I have to pass to onPostExecute the message from onTextMessage :/
private class Reseau extends AsyncTask<Void, Void, String> {
// This is run in a background thread
#Override
protected String doInBackground(Void... params) {
socket.addListener(new WebSocketAdapter() {
#Override
public void onTextMessage(WebSocket websocket, String message) throws Exception {
// Here I want to return the String message to onPostExecute
// How to do it ? return message do not work because onTextMessage is void
}
});
try { socket = new WebSocketFactory()
.setConnectionTimeout(5000)
.createSocket(adresse[0] + adresse[1])
.connect();
}
catch (IOException e) { e.printStackTrace(); } catch (WebSocketException e) { e.printStackTrace(); }
return "I want to pass message from onTextMessage to onPostExecute";
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
zone.append(result);
}
}
I can use a RunOnUIThread or enable StrictMode but this is not the good method to do that job.
Thank you for your help !

sending a string to the server and receiving not updated response

I'm writing an app for android in Java, and the server side also with Java.
The connection is through sockets. To send strings to the server I'm using asyncTask as follows:
public static void send(String content) throws IOException {
mConnectionHandler.new AsyncSendToServer().execute(content);
}
private class AsyncSendToServer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
out.println(params[0]);
return null;
}
}
Now the response from the server is done as follows:
public static String receive() {
mConnectionHandler.new AsyncReceiveFromServer().execute();
return serverResponse;
}
private class AsyncReceiveFromServer extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String result = null;
try {
result = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result) {
serverResponse = result;
}
}
Because the methods are async, the serverResponse does not get the appropriate value in receive(). When I execute AsyncReceiveFromServer, receive() return the value of serverResponse before it's get updated in the asyncTask. What can I do in order to send the updated serverResponse?
Execute your AsyncReceiveFromServer from the onPostExecute of your AsyncSendToServer.
This way, you are absolutely certain that the Send has finished.

need to return value from AsyncTask [duplicate]

This question already has answers here:
AsyncTask return value
(4 answers)
Closed 9 years ago.
I am calling soap webservice and need to display what is returned. but I couldnt do it because AsyncTask is complex and I dont know how to use it properly. would you please tell me how to return data from the called function via asynctask?
here is my code
public class WebserviceTool {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://192.168.0.11:9289/Service1.asmx";
private final String SOAP_ACTION = "http://tempuri.org/get_currency";
private final String METHOD_NAME = "get_currency";
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String execute_barcode_webservice(String s1, String s2) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("date",s1);
request.addProperty("cur_code",s2);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.encodingStyle = SoapEnvelope.ENC;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Object response;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
response = (Object) envelope.getResponse();
Log.i("my_error", response.toString());
} catch (Exception e) {
Log.i("my_error", e.getMessage().toString());
}
return "testarif";
}
public class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
execute_barcode_webservice(params[0], params[1]);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
this is the function execute_barcode_webservice() that does all the job and returns data. but since I call execute_barcode_webservice() view AsyncTask, I dont know how to return with it. how can I do it?
The result of the async task execution is the response object produced by execute_barcode_webservice(). However, don't think about the async task as something that will execute and return a value to you. Instead, inside the method onPostExecute() you must take the response object and process it (extract its values and display them in a list, or whatever you want to do with it). The async task is just a way to execute some code in a separate thread then go back to the main thread (the UI thread) and process the results, which is done in onPostExecute().
My suggestion: rewrite execute_barcode_webservice() to return a response object instead of a String (an object that can be null if the operation fails) and pass that object to the onPostExecute() method. You will have to change the async task to:
public class AsyncCallWS extends AsyncTask<String, Void, Object> {
#Override
protected Object doInBackground(String... params) {
Object response = null;
try {
response = execute_barcode_webservice(params[0], params[1]);
} catch (Exception e) {
// TODO: handle exception
}
return response;
}
#Override
protected void onPostExecute(Object response) {
if (response != null) {
// display results in a list or something else
}
}

Categories

Resources