Branch.io setDebug() not working - android

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 {
}
}
});

Related

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());
}

How to run this code every 5000ms in 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();
}
});
}
}

about facebook Game Request how can I get the data when my app launcher

how can I to do get the data("world") when my app launcher in Activity
GameRequestContent content = new GameRequestContent.Builder()
.setMessage("hello")
.setData("world")
.build();
GameRequestDialog g = new GameRequestDialog(getActivity());
g.registerCallback(callbackManager, new FacebookCallback<GameRequestDialog.Result>() {
#Override
public void onSuccess(GameRequestDialog.Result o) {
Log.i("onSuccess", new Gson().toJson(o.getRequestRecipients()));
}
#Override
public void onCancel() {
Log.i("onSuccess", "onCancel");
}
#Override
public void onError(FacebookException error) {
Log.i("onError", error.getMessage());
error.printStackTrace();
}
});
g.show(content);

Facebook SSO , differentiating the login and wall post messages

I have made a sample for posting on Facebook using the basic Facebook library provided at developer.facebook.com and it works just fine with SSO,
btnPostOnFb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{
facebook.authorize(FBIntegrationSampleActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
if(values!=null && values.containsKey("access_token")){
postOnWall("NEW POST from" +count+"Android -Anuj");
Log.e("post on wall", "WALLPOST");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY POSTED MSG ON WALL", Toast.LENGTH_SHORT).show();
}else if(values!=null)
Log.e("LOGINE SUCCESS", "LOGIN SUCCESS");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY LOGGED IN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFacebookError(FacebookError error) {
Log.e("onFBERROR", "ONFBERROR");
}
#Override
public void onError(DialogError e) {
Log.e("on DESI ERROR", "ON_ERROR");
}
#Override
public void onCancel() {
Log.e("onCANCEL", "ONCANCEL");
}
});
}
}
});
Which successfully posts on the Facebook wall, what i want is, I need to show the user that he has successfully signed in, and a message would be posted there after.
The Issue i face is the onComplete(Bundle values) method is called for both successful login and for successful post, how can i differentiate between both of them, is there a key in the Bundle values that can help to find the differnence?
Any suggestions are welcome.
Problem is that you are using for Authentication and Posting. No need to do like this :
For Authentication use
facebook.authorize(a, PERMISSIONS,-1,new LoginListener());
And for posting :
1) Without Dialog facebook.request(parameters)
2) With Dialog
facebook.dialog(this,"stream.publish",parameters,new TestUiServerListener());
public class TestUiServerListener implements DialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
new AsyncFacebookRunner(ZValues.authenticatedFacebook).request(postId,new TestPostRequestListener());
} else {
Post_Message_Title.this.runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
public class TestPostRequestListener implements RequestListener {
public void onComplete(final String response, final Object state) {
try {
JSONObject json = Util.parseJson(response);
String postId = json.getString("id");
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
} catch (Throwable e) {
}
}
public void onFacebookError(FacebookError e, final Object state) {
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
e.printStackTrace();
}
}
Just create a method successLoginShowDialog() and show whatever you want ,
If Post is success , In TestPostRequestListener below Thread will be called , so do all stuffs in this Thread :
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
to postOnWall() you can get its response:
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
fbObj.request("me");
String response = fbObj.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
// showToast("Blank response.");
Toast.makeText(context, "blank response", Toast.LENGTH_SHORT)
.show();
} else {
// showToast("Message posted to your facebook wall!");
Toast.makeText(context,
"Message posted to your facebook wall!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// showToast("Failed to post to wall!");
e.printStackTrace();
}
}

Categories

Resources