Android/Java: How to Delay Return in a Method

Android/Java: how to delay return in a method

I created this and managed like the following way please have a look, hope it will be useful to you

public class APIManager {

public static void createRequest(Context c, String requestTag,
String endPoint, List<NameValuePair> params,
final OnRequestCompletedListener listener,
TransParentProgressDialog pd) {
ServerDetails serverDetails = new ServerDetails(c, endPoint, params);
JsonObjectRequest request = new JsonObjectRequest(Method.GET,
serverDetails.getQueryUrl(), null,
new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
listener.onRequestCompleted(response);
}
}, getErrorListener(c, pd)) {

};
AppController.getInstance().addToRequestQueue(request, requestTag);
}

public static ErrorListener getErrorListener(final Context c,
final TransParentProgressDialog pd, final TextView tvEmpty,
final String errorText) {

Response.ErrorListener listener = new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
if (tvEmpty != null) {
tvEmpty.setText(errorText);
}
MyDialog dialog;
Log.d("volley-error", error.toString());

if (error instanceof TimeoutError) {
dialog = new MyDialog(c, "Server Timeout");
dialog.show();
return;
} else if (error instanceof NoConnectionError) {
dialog = new MyDialog(c, "No Connection or Invalid Url");
dialog.show();
return;

} else if (error instanceof ServerError) {
NetworkResponse response = error.networkResponse;
if (response != null) {
// int statusCode = response.statusCode;
byte[] data = response.data;
if (data != null) {
String str = new String(data);
try {
JSONObject object = new JSONObject(str);
Log.d("error response", object.toString());
if (object.has("errors")) {
JSONArray errors = object
.getJSONArray("errors");
JSONObject errorObject = errors
.getJSONObject(0);
dialog = new MyDialog(c, "Error!",
errorObject.getString("message"));
dialog.show();
} else {
dialog = new MyDialog(c, "Error!",
object.toString());
dialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Server Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Server Error");
dialog.show();
}

} else if (error instanceof NetworkError) {
NetworkResponse response = error.networkResponse;
if (response != null) {
// int statusCode = response.statusCode;
byte[] data = response.data;
if (data != null) {
String str = new String(data);
try {
JSONObject object = new JSONObject(str);
Log.d("error response", object.toString());
if (object.has("errors")) {
JSONArray errors = object
.getJSONArray("errors");
JSONObject errorObject = errors
.getJSONObject(0);
dialog = new MyDialog(c, "Error!",
errorObject.getString("message"));
dialog.show();
} else {
dialog = new MyDialog(c, "Error!",
object.toString());
dialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Network Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Network Error");
dialog.show();
}
} else if (error instanceof ParseError) {
dialog = new MyDialog(c, "Parse Error");
dialog.show();
} else if (error instanceof AuthFailureError) {
NetworkResponse response = error.networkResponse;
if (response != null) {
// int statusCode = response.statusCode;
byte[] data = response.data;
if (data != null) {
String str = new String(data);
try {
JSONObject object = new JSONObject(str);
Log.d("error response", object.toString());
if (object.has("errors")) {
JSONArray errors = object
.getJSONArray("errors");
JSONObject errorObject = errors
.getJSONObject(0);
dialog = new MyDialog(c, "Error!",
errorObject.getString("message"));
dialog.show();
} else {
dialog = new MyDialog(c, "Error!",
object.toString());
dialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Error connecting server");
dialog.show();
}
}
}
};
return listener;
}
}

And the interface for call back on request completed is

public interface OnRequestCompletedListener {

public void onRequestCompleted(JSONObject response);
}

How to call a method after a delay in Android

Kotlin

Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
}, 100)

Java

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);

The class to import is android.os.handler.

Return to method, which contains postDelayed

You don't. You need to rearchitecture what you're doing. The only way to delay a return is to hold up the UI thread, which is not the right way to do anything ever. What you need to do is make any code that needs the return value execute in the postDelayed Runnable. What you want to do will never work.

How to set delay in android?

Try this code:

import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
}
}, 5000);

How to use delay functions in Android Studio?

 try {
//set time in mili
Thread.sleep(3000);

}catch (Exception e){
e.printStackTrace();
}

edited as your code

 kileri.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("F");
try {
//set time in mili
Thread.sleep(3000);

}catch (Exception e){
e.printStackTrace();
}
sendData("S");
}
});

Delay execution of code in method Java

Option 1: Using threads, you might run your job off the main (UI) thread:

new Thread(new Runnable() {
// some code here ...

// This might be in a loop.
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
// Handle ...
}
}
}).start();

Then, if this new thread you'd like to modify UI (i.e. show/hide button, display something on the screen etc), remember to pass that through the UI thread, as only this one can modify the UI. You might consider using Activity.runOnUiThread() for that.

Option 2: Another, more Android-style way of approaching that issue is to use AsyncTask. It contains three callbacks which can be used to do work on- and off- the UI thread. Sketch of such a code could look like:

 private class MyTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... param) {
// This method is running off the UI thread.
// Safe to stop execution here.

return null;
}

protected void onProgressUpdate(Void... progress) {
// This methid is running on the UI thread.
// Do not stop thread here, but safe to modify the UI.
}

protected void onPostExecute(Long result) {
// Also on UI thread, executed once doInBackground()
// finishes.
}
}

Option 3: Then there is also a Timer, as suggested by @Stultuske. It's less flexible then AsyncTask, but handles the interval for you.

Add delay to a loop in android without stalling the UI Thread

Maybe Creating Something like this should work,

protected static void startTimer() {
timer.schedule(new TimerTask() {
public void run() {
mHandler.obtainMessage(1).sendToTarget();
}
}, 500);
}

public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
myFunction();
}
};

Execute function after 5 seconds in Android

You can use the Handler to add some delay.Call the method displayData() as below so that it will be executed after 5 seconds.

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
displayData();
}
}, 5000);

Note : Do not use the threads like Thread.sleep(5000); because it will block your UI and and makes it irresponsive.



Related Topics



Leave a reply



Submit