How to run this code every 5000ms in Android - android

In my application I want check internet and when connected load some data, if not connected check data any 5000ms and check this 3 level (15000ms), if in this 15000ms not connected show user "Internet Not Connected" and when connected internet get this data.
My code:
private void retrofitData(boolean isConnect) {
if (isConnect) {
try {
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<Retrofit_ColoniesModelResponse> call = apiInterface.getColoniesResponse();
call.enqueue(new Callback<Retrofit_ColoniesModelResponse>() {
#Override
public void onResponse(Call<Retrofit_ColoniesModelResponse> call, Response<Retrofit_ColoniesModelResponse> response) {
try {
if (response != null) {
if (response.body() != null) {
// first remove
models.clear();
// then fill
models.addAll(response.body().getCategories());
mAdaper.notifyDataSetChanged();
colonies_RecyclerView.setAdapter(mAdaper);
CustomProcessDialog.dissmis();
showHelp();
} else {
CustomProcessDialog.dissmis();
new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
.setTitleText("title")
.setContentText("message")
.setConfirmText("ok")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
finish();
startActivity(getIntent());
}
})
.show();
}
} else {
CustomProcessDialog.createAndShow(context);
TastyToast.makeText(context, "error", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
checkNetLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<Retrofit_ColoniesModelResponse> call, Throwable t) {
new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
.setTitleText("title")
.setContentText("message")
.setConfirmText("ok")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
finish();
startActivity(getIntent());
}
})
.show();
}
});
} catch (Exception e) {
Log.e("ServerEx", "Error : " + e);
}
} else {
checkNetLayout.setVisibility(View.VISIBLE);
if (mAdaper != null) {
mAdaper.clear();
colonies_RecyclerView.setAdapter(mAdaper);
}
categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
}
How can I achieve this? Please help me. I am amateur.

place this method in your Conastant class where you place utility methods:
public abstract static class BackoffCallback<T> implements Callback<T> {
private static int RETRY_COUNT = 3;
private static final double RETRY_DELAY = 5000;
private int retryCount = 0;
protected BackoffCallback(int retryNum) {
RETRY_COUNT=retryNum;
}
#Override
public void onFailure(final Call<T> call, Throwable t) {
retryCount++;
if (retryCount <= RETRY_COUNT) {
int expDelay = (int) (RETRY_DELAY);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
retry(call);
}
}, expDelay);
} else {
onFailedAfterRetry(t);
}
}
private void retry(Call<T> call) {
call.clone().enqueue(this);
}
public abstract void onFailedAfterRetry(Throwable t);
}
And use it in main activity like:
private void retrofitData(boolean isConnect) {
if (isConnect) {
try {
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<Retrofit_ColoniesModelResponse> call = apiInterface.getColoniesResponse();
call.enqueue(new Constants.BackoffCallback<Retrofit_ColoniesModelResponse>(3) {
#Override
public void onResponse(Call<Retrofit_ColoniesModelResponse> call, Response<Retrofit_ColoniesModelResponse> response) {
try {
if (response != null) {
if (response.body() != null) {
// first remove
models.clear();
// then fill
models.addAll(response.body().getCategories());
mAdaper.notifyDataSetChanged();
colonies_RecyclerView.setAdapter(mAdaper);
CustomProcessDialog.dissmis();
showHelp();
} else {
CustomProcessDialog.dissmis();
new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
.setTitleText("title")
.setContentText("message")
.setConfirmText("ok")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
finish();
startActivity(getIntent());
}
})
.show();
}
} else {
CustomProcessDialog.createAndShow(context);
TastyToast.makeText(context, "error", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
checkNetLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
#Override
public void onFailedAfterRetry(Throwable t) {
new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
.setTitleText("title")
.setContentText("message")
.setConfirmText("ok")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
finish();
startActivity(getIntent());
}
})
.show();
}
});
}
} else {
checkNetLayout.setVisibility(View.VISIBLE);
if (mAdaper != null) {
mAdaper.clear();
colonies_RecyclerView.setAdapter(mAdaper);
}
categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
}

Related

require help to bind button after button click & data is coming from retrofit2 api call

#FormUrlEncoded
#POST("MaidDetails.ashx")
Call<jsonResponse> fn_GetMaidDetails(#Field("ClientID") int ClientID, #Field("MaidID") int MaidID, #Field("HashKey") String HashKey);
#Override
public void onBindViewHolder(#NonNull MaidViewHolder maidViewHolder, int i) {
final Maids Maid = Maids.get(i);
context = maidViewHolder.ltl_Name.getContext();
maidViewHolder.ltl_Name.setText(Maid.getMaid_Name());
maidViewHolder.ltl_Type.setText(Maid.getMaid_Type());
maidViewHolder.ltl_Locality.setText(Maid.getMaid_Locality());
maidViewHolder.ltl_City.setText(Maid.getMaid_City());
maidViewHolder.ltl_Age.setText(Maid.getMaid_Age());
maidViewHolder.ltl_Experience.setText(Maid.getMaid_Experience());
maidViewHolder.ltl_Address.setText(Maid.getMaid_Address());
maidViewHolder.ltl_Date.setText(Maid.getMaid_Date());
maidViewHolder.btn_MobileNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int iMaidID = Maid.getMaid_ID();
Button btn_MobileNo = (Button)view;
fn_GetMaidDetails(iMaidID);
Toast.makeText(context, "After - " + strResponseText, Toast.LENGTH_LONG).show();
}
});
}
protected void fn_GetMaidDetails(int iMaidID){
preferences = new SharedPrefs(context);
int iAccountID = preferences.GetAccountID();
String strHashKey = Library.fn_GenerateMD5(String.valueOf(iAccountID));
MaidApi objApi = RetrofitClient.getRetrofit().create(MaidApi.class);
Call<jsonResponse> call = objApi.fn_GetMaidDetails(iAccountID, iMaidID, strHashKey);
call.enqueue(new Callback<jsonResponse>() {
#Override
public void onResponse(Call<jsonResponse> call, Response<jsonResponse> response) {
if (response.isSuccessful()) {
jsonResponse objResponse = response.body();
if (objResponse.getResponse_Identity() > 0) {
strResponseText = objResponse.getResponse_Text();
Toast.makeText(context, "Before - " + strResponseText, Toast.LENGTH_LONG).show();
}
else
{
Intent i = new Intent(context, PackagesActivity.class);
context.startActivity(i);
}
} else {
Toast.makeText(context, "3", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<jsonResponse> call, Throwable t) {
Toast.makeText(context, "4", Toast.LENGTH_LONG).show();
}
});
}
I want to set button text after
if (objResponse.getResponse_Identity() > 0) {
//set button text = objResponse.getResponse_Text();
}
'you can do it like this'
button.setText(objResponse.getResponse_Text().toString());
or
button.setText(objResponse.getResponse_Text());

how to make generic retrofit library for api calling

i'm working on API integration. i want to make generic class for API integration. which can comfortable with for all API integration.right now i'm using separate code for all API. i'm new in android application development. so please guide me.
public void getHomeCategoryDetailApi(Context context) {
final ProgressDialog loadingDialog = ProgressDialog.show(context, "Please wait", "Loading...");
Retrofit restAdapter = ApiLists.retrofit;
ApiLists apiCall = restAdapter.create(ApiLists.class);
Call<HomeCategoryModelClass> call = apiCall.homePageCatListAPI();
Log.d(TAG, "CategoryDetail : " + call.request()+" \n"+apiCall.homePageCatListAPI().toString());
call.enqueue(new Callback<HomeCategoryModelClass>() {
#Override
public void onResponse(Call<HomeCategoryModelClass> call, Response<HomeCategoryModelClass> response) {
Log.d(TAG, "onResponse: CategoryDetail:" + response.body());
Log.d(TAG, "onResponse: response.code():" + response.code());
if (response.body() == null) {
loadingDialog.dismiss();
globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
} else {
loadingDialog.dismiss();
if (response.body().getStatusCode().equalsIgnoreCase("1")) {
homeCategoryImageMenu = (ArrayList<Menu>) response.body().getMenu();
thirdHorizontalRecyclerAdapter.notifyDataSetChanged();
} else {
globalClass.showAlertDialog(getActivity(), "Alert", "" + response.body().getStatus(), false);
}
}
if (response.errorBody() != null) {
try {
Log.d(TAG, "onResponse: response.errorBody()===>" + response.errorBody().string());
if (loadingDialog.isShowing() && loadingDialog != null) {
loadingDialog.dismiss();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<HomeCategoryModelClass> result, Throwable t) {
Log.d(TAG, "onFailure: " + result.toString());
loadingDialog.dismiss();
globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
}
});
}
Here is Bast Way to call API
public class APIResponse {
private static String TAG = APIResponse.class.getSimpleName();
public static <T> void callRetrofit(Call<T> call, final String strApiName, Context context, final ApiListener apiListener) {
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
if (strApiName.equalsIgnoreCase("LoginApi")) {
if (response.isSuccessful()) {
Log.d(TAG, "onResponse: " + response.body().toString());
// NearByNurse nearByNurse = (NearByNurse) response.body(); // use the user object for the other fields
// apiListener.success(url,nearByNurse);
progressDialog.dismiss();
} else {
try {
Log.d(TAG, "onResponse: " + response.errorBody().string());
apiListener.error(strApiName, response.errorBody().string());
progressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (strApiName.equalsIgnoreCase("")) {
//Patient user = (Patient) response.body();
}
}
#Override
public void onFailure(Call<T> call, Throwable t) {
Log.d(TAG, "onFailure: " + t.toString());
if (strApiName.equalsIgnoreCase("searchNearbyTest")) {
apiListener.failure(strApiName, t.toString());
}
progressDialog.dismiss();
}
});
}
In API Calling Side
private void loginApi() {
Retrofit retrofit = ApiLists.retrofit;
ApiLists apiList = retrofit.create(ApiLists.class);
Call<JsonElement> loginApiCall = apiList.loginApi("kjdf", "fkldngdkl", "lkfdxngl", "kjngn", "jksdgkj");
APIResponse.callRetrofit(loginApiCall, "LoginApi", LoginActivity.this, this);
}
#Override
public void success(String strApiName, Object response) {
if (strApiName.equals("LoginApi")) {
}
}
#Override
public void error(String strApiName, String error) {
if (strApiName.equals("LoginApi")) {
}
}
#Override
public void failure(String strApiName, String message) {
if (strApiName.equals("LoginApi")) {
}
and interface call on API response.
public interface ApiListener {
void success(String strApiName, Object response);
void error(String strApiName, String error);
void failure(String strApiName, String message);
}
This's my common function basic call Api.java
public class Api {
private void basicCall(Call<DataResponse> call) {
if (call == null) {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
return;
}
call.enqueue(new Callback<DataResponse>() {
#Override
public void onResponse(#NonNull Call<DataResponse> call, #NonNull Response<DataResponse> response) {
int code = response.code();
//Check http ok
if (code == HttpURLConnection.HTTP_OK) {
//Check status
if (response.body().getStatus() == Config.STATUS_OK) {
//Everything's OK
listener.onResponseCompleted(Config.STATUS_OK, response.body().getError(), response.body().getData());
} else {
listener.onResponseCompleted(Config.STATUS_FAILED, response.body().getError(), null);
}
} else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
try {
ErrorResponse error = Api.gson.fromJson(response.errorBody().string(), ErrorResponse.class);
listener.onResponseCompleted(Config.STATUS_401, error.getError(), error.getData());
} catch (IOException e) {
e.printStackTrace();
}
} else {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
}
}
#Override
public void onFailure(#NonNull Call<DataResponse> call, #NonNull Throwable t) {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
}
});
}
//And you can use
public void getProductList(OnResponseCompleted listener) {
this.listener = listener;
Call<DataResponse> call = apiService.getProductList();
basicCall(call);
}
}
//or orther function
This's ApiService.java
public interface ApiInterface {
#POST("product/list")
Call<DataResponse> getProductList();
}
This's OnResponseCompleted.java
public interface OnResponseCompleted {
void onResponseCompleted(int status, String error, Object data);
}
i want to make like this .i just pass some require parameter....
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
// Set Dialog Message
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
if (status != null)
// Set alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_success : R.drawable.ic_fail);
// Set OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Show Alert Message
alertDialog.show();
}
Try this code..
In this code Retrofit object set up done in one class and all api calling into interface..
public class ApiClient {
private final static String BASE_URL = "https://api.github.com";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
after that call the api into api interface..
public interface ApiInterface {
#GET("{affenpinscher}/images")
Call<Product> getProductData(#Path("affenpinscher") String breed);
#GET("getProductDetailByProductId?ProductId=3")
Call<JsonObject> ITEM_DESCRIPTION_RESPONSE_CALL();
#POST("linke")
Call<Response> passJsonData(#Body JsonData jsonData);
#GET("/users/waadalkatheri/repos")
Call<Response> getdata();
}
and when you call api in activity or fragment used below code..
ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<ResponseData> responseCall = apiInterface.getdata();
responseCall.enqueue(new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, retrofit2.Response<ResponseData> response) {
if (response.isSuccessful() && response.body() != null && response != null) {
Toast.makeText(getApplicationContext(), "GetData" + response.body().getLanguage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t) {
Log.d("Errror", t.getMessage());
}
});

Branch.io setDebug() not working

I have implemented Branch.io referral program.Debug mode is on. When I click on the link it navigates to the app. On signup success i am using setIdentity("user_id") method and then getCredits() and Redeem Credits of referrer and referred user.It works only one or two times on a device then after that, it returns returned{} on setIdentity("user_id").
There is my code:
branch.setIdentity(Settings.USERID, new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (!referrer_id.equalsIgnoreCase("")) {
branch.userCompletedAction("referAFriend");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
branch.loadRewards(new Branch.BranchReferralStateChangedListener() {
#Override
public void onStateChanged(boolean changed, BranchError error) {
if (error == null) {
if (changed) {
credits = branch.getCredits();
Log.e("credits", credits + "");
branch.redeemRewards(credits, new Branch.BranchReferralStateChangedListener() {
#Override
public void onStateChanged(boolean changed, BranchError error) {
branch.logout(new Branch.LogoutStatusListener() {
#Override
public void onLogoutFinished(boolean loggedOut, BranchError error) {
if (loggedOut) {
Log.e("210", loggedOut + "");
if (!referrer_id.equalsIgnoreCase("")) {
Log.e("209",referrer_id+"");
branch.setIdentity(referrer_id, new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
Log.e("215",referringParams+"");
if(referringParams.toString().equalsIgnoreCase("{}"))
{
Utils.resultdialog(SignupActivity.this, "Registered Successfully.", "signup");
}
else {
if (error == null) {
branch.loadRewards(new Branch.BranchReferralStateChangedListener() {
#Override
public void onStateChanged(boolean changed, BranchError error) {
if (error == null) {
if (changed) {
refreepoints = branch.getCredits();
Log.e("refreepoints", refreepoints + "");
branch.redeemRewards(refreepoints, new Branch.BranchReferralStateChangedListener() {
#Override
public void onStateChanged(boolean changed, BranchError error) {
if (error == null) {
if (changed) {
} else {
}
} else {
Log.e("255", "255");
}
}
}
});
}
} else {
Log.e("265", error + "");
Utils.resultdialog(SignupActivity.this, "Registered Successfully.", "signup");
}
}
});
} else {
Log.e("268", error + "");
}
}
}
});
} else {
Log.e("266", "error");
}
}
}
});
}
});
} else {
Log.e("271", error + "");
}
} else {
Log.e("274", error + "");
}
}
});
}
}, 10000);
} else {
}
}
});

How to resolve fragment not attached to activity in android?

I have a fragment in which,I load some data from sever using background thread and update the UI using "runOnUiThread".But it gives me error "fragment not attached to activity".
How can I resolve that issue?
code:-
AsyncTask.execute(new Runnable() {
#Override
public void run() {
/*Checking whether user is loggedin or not*/
if (loginSessionManager.isLogin()) {
/*Creating object of "CServerRequest" class*/
cServerRequest = new CServerRequest(mContext);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put(CRequestKey.AGENT_CODE, m_szMobileNumber.trim());
jsonObject.put(CRequestKey.PIN, m_szEncryptedPassword.trim());
if (BuildConfig.kDebugInfo)
Log.d(TAG, "Request::" + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.VISIBLE);
}
});
}
String s_szWalletURL = CAPIStorage.IREWARDS_URL + CAPIStorage.WALLET_BALANCE_URL;
cServerRequest.postWalletRequest("POST", s_szWalletURL, jsonObject);
/*Handling server response and error here*/
cServerRequest.setCallBackListener(new CServerRequest.IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
if (BuildConfig.kDebugInfo)
Log.d(TAG, "Response::" + response);
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(CResponseKey.GENERAL_RESULT_CODE));
if (nResultCodeFromServer == ConstantInt.TRANSACTION_SUCCESS) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.GONE);
m_walletHeading.setVisibility(View.VISIBLE);
m_SuccessLayout.setVisibility(View.VISIBLE);
}
});
}
String s_szWalletBalance = response.getString(CResponseKey.WALLET_BALANCE).trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet balance here from ui thread.
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (m_szCountryCode.equalsIgnoreCase(CResponseKey.COUNTRY_INDIA)) {
m_currency.setText(getString(string.ruppes_symbol));
} else {
m_currency.setText(getString(string.currency_dollar));
}
m_points.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
if (m_szCountryCode.equalsIgnoreCase(CResponseKey.COUNTRY_INDIA)) {
/*If found indian user then show conversion of points in rupees*/
amountConversionIndia();
} else {
/*If found non-indian then will show conversion of points in doller*/
amountConversionInternational();
}
}
});
}
/*Connection lost error*/
} else if (nResultCodeFromServer == ConstantInt.CONNECTION_LOST) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.connection_lost));
m_ErrorText.setText(getResources().getString(string.retry));
}
});
}
/*Timed out error from response*/
} else if (nResultCodeFromServer == ConstantInt.TIMED_OUT) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.connection_timed_out));
m_ErrorBtn.setText(getResources().getString(string.retry_text));
}
});
}
/*Technical failure response from server*/
} else if (nResultCodeFromServer == ConstantInt.TECHNICAL_FAILURE) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.technical_failure));
m_ErrorBtn.setText(getResources().getString(string.retry_text));
}
});
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void notifyError(String requestType, VolleyError error) {
if (BuildConfig.kDebugInfo)
Log.d(TAG, "Error::" + error);
if (isAdded()) {
/*Time out volley error*/
if (error instanceof TimeoutError) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.connection_timed_out));
m_ErrorBtn.setText(getResources().getString(string.retry_text));
}
});
/*Network volley error*/
}
}
if (isAdded()) {
if (error instanceof NetworkError) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_walletHeading.setVisibility(View.GONE);
m_ErrorText.setText(getResources().getString(string.unable_to_connect_text));
m_ErrorBtn.setText(getResources().getString(string.retry));
}
});
}
}
}
});
} else {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (isAdded()) {
m_loading_layout.setVisibility(View.GONE);
m_ErrorLayout.setVisibility(View.VISIBLE);
m_ErrorText.setText(mContext.getResources().getString(string.please_log_into_your_account));
m_ErrorBtn.setText(getResources().getString(string.login_btn_text));
}
}
});
}
}
}
});
}
The solution to this problem should be cancel your asynctask in onStop().
You also don't introduce the problem of memory leak.
#Override
public void onStop() {
super.onStop();
mYourAsyncTask.cancel(true);
}

Android: How do i get user online/offline status using quickblox?

I am not able to get the user online/offline status in QuickBlox. I have tried using QBRoster.
The function that I have written to get user presence.
private void subscribeUserForStatus(ArrayList<Integer> mQBUserList) {
if (QBChatService.getInstance().getRoster() != null) {
mQbRoster = QBChatService.getInstance().getRoster(
QBRoster.SubscriptionMode.mutual, this);
mQbRoster.addRosterListener(this);
for (Integer mId : mQBUserList) {
try {
if (mQbRoster.contains(mId)) {
mQbRoster.subscribe(mId);
} else {
mQbRoster.createEntry(mId, null);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
Log.e("Crash on subscription", e.getMessage());
}
}
}
}
int userID = 45;
QBPresence presence = chatRoster.getPresence(userID);
if (presence == null) {
// No user in your roster
return;
}
if (presence.getType() == QBPresence.Type.online) {
// User is online
}else{
// User is offline
}
This can also help you :
QBRosterListener rosterListener = new QBRosterListener() {
#Override
public void entriesDeleted(Collection<Integer> userIds) {
}
#Override
public void entriesAdded(Collection<Integer> userIds) {
}
#Override
public void entriesUpdated(Collection<Integer> userIds) {
}
#Override
public void presenceChanged(QBPresence presence) {
}
};
This link is helpful :
https://quickblox.com/developers/Android_XMPP_Chat_Sample
The above answer is correct and you can use it like this
QBRosterListener rosterListener = new QBRosterListener() {
#Override
public void entriesDeleted(Collection<Integer> userIds) {
}
#Override
public void entriesAdded(Collection<Integer> userIds) {
}
#Override
public void entriesUpdated(Collection<Integer> userIds) {
}
#Override
public void presenceChanged(QBPresence presence) {
if (presence == null) {
// No user in your roster
return;
}
if (presence.getType() == QBPresence.Type.online) {
// User is online
}else{
// User is offline
}
}
};
You can use this code
Roster roster = xmppConnection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
Presence presence;
for(RosterEntry entry : entries) {
presence = roster.getPresence(entry.getUser());
System.out.println(entry.getUser());
System.out.println(presence.getType().name());
System.out.println(presence.getStatus());
}

Categories

Resources