Wait until callback of request is completed, Facebook-SDK android - java

I have the following class that I instantiate from my fragment:
public class FacebookLogin {
private CallbackManager mCallbackManager;
private LoginButton lButton;
private AccessToken accessToken;
private Profile profile;
private static final String TAG = "FacbookLogin";
public FacebookLogin(Context c) {
FacebookSdk.sdkInitialize(c);
mCallbackManager = CallbackManager.Factory.create();
Log.i(TAG, " Constructor called");
}
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, " logged in...");
AccessToken accessToken = loginResult.getAccessToken();
profile = Profile.getCurrentProfile(); //Access the profile who Is the person login i
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.i(TAG, " Error");
Log.e(TAG, e.getMessage());
}
};
public void setCallback(LoginButton lButton) {
lButton = lButton;
lButton.registerCallback(mCallbackManager, mCallback);
Log.i(TAG, " setCallback called");
}
And here Is my fragment-class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fLogin = new FacebookLogin(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.login, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
final LoginButton loginButton = (LoginButton) getView().findViewById(R.id.login_button);
final TextView infoText = (TextView) getView().findViewById(R.id.text_details);
loginButton.setFragment(this);
loginButton.setReadPermissions("user_friends");
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, " Button clickde");
fLogin.setCallback(loginButton); //Let's register a callback
profile = fLogin.getProfile();
if (profile != null) {
Log.i(TAG, profile.getName()); //Call this after the callback request Is finished
} else {
Log.i(TAG, "NULL....... inside onresume");
}
}
});
}
I want to call profile = fLogin.getProfile(); after the callback request is complete. But I don't know how to do this. I have read about the onComplete();, but I don't know how to Implement It here.

Related

What to set on textview from the JSON response I'm getiing through retrofit for DashboardResponse?

I'm getting nullPointerException when I try to set data to textviews from the JSON response,I'm getting through retrofit. I would like to set the total sale, total expense and total purchase values to the textviews:
tv_total_purchase_today,
tv_total_sale_today,
tv_total_expense_today
What should I put in the setsaleInformations method?
Here's my code:
API Response
public class DashboardResponse extends CommonResponse {
#Expose
#SerializedName("graph_data")
private ArrayList<Graph> graph_data;
#Expose
#SerializedName("total_sale")
private String total_sale;
#Expose
#SerializedName("total_purchase")
private String total_purchase;
#Expose
#SerializedName("total_expense")
private String total_expense;
public ArrayList<Graph> getGraph_data() {
return graph_data;
}
public void setGraph_data(ArrayList<Graph> graph_data) {
this.graph_data = graph_data;
}
public String getTotal_sale() {
return total_sale;
}
public void setTotal_sale(String total_sale) {
this.total_sale = total_sale;
}
public String getTotal_purchase() {
return total_purchase;
}
public void setTotal_purchase(String total_purchase) {
this.total_purchase = total_purchase;
}
public String getTotal_expense() {
return total_expense;
}
public void setTotal_expense(String total_expense) {
this.total_expense = total_expense;
}
}
API Interactor Implementation
#Override
public void getDashboard(final DashboardListener dashboardListener) {
Call<DashboardResponse> call = apiServiceInterface.getDashboard();
call.enqueue(new Callback<DashboardResponse>() {
#Override
public void onResponse(Call<DashboardResponse> call, Response<DashboardResponse> response) {
if(isResponseValid(response) && response.body().isSuccess()){
dashboardListener.onDashboardFetch(response.body());
}else{
dashboardListener.onFailed(prepareFailedMessage(response), APIConstants.DASHBOARD);
}
}
Dashboard Fragment
public class DashboardFragment extends Fragment {
private Context context;
private SalesUtils salesUtils;
private DashboardResponse dashboardResponse;
private HomePresenter homePresenter;
private HomeView homeView;
#BindView(R.id.tv_total_sale_today)
TextView tv_total_sale_today;
#BindView(R.id.tv_total_purchase_today)
TextView tv_total_purchase_today;
#BindView(R.id.tv_total_expense_today)
TextView tv_total_expense_today;
#BindView(R.id.cv_sale_today)
CardView cv_sale_today;
#BindView(R.id.cv_purchase_today)
CardView cv_purchase_today;
#BindView(R.id.cv_expense_today)
CardView cv_expense_today;
private ArrayList<Sale> salesToday;
private ArrayList<Product> productSoldToday;
private SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
public DashboardFragment() {
// Required empty public constructor
}
public static DashboardFragment newInstance(HomePresenter homePresenter) {
DashboardFragment fragment = new DashboardFragment();
fragment.initializeSaleInfo(homePresenter);
return fragment;
}
private void initializeSaleInfo(HomePresenter homePresenter) {
this.homePresenter = homePresenter;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
homeView = (HomeView) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
ButterKnife.bind(this, rootView);
cv_sale_today.startAnimation(AnimationUtils.loadSlideInLeftAnimation(context));
cv_purchase_today.startAnimation(AnimationUtils.loadFadeInAnimation(context));
cv_expense_today.startAnimation(AnimationUtils.loadSlideInRightAnimation(context));
homePresenter.fetchDashboard();
setListeners();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
if(homeView!=null) {
homeView.changeSearchState(false);
}
}
#Override
public void onPause() {
super.onPause();
if(homeView != null)
homeView.setIsInSaleInfo(false);
}
public void setSaleInformations() {
if (getActivity() != null && isAdded())
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tv_total_purchase_today.setText();
tv_total_sale_today.setText();
tv_total_expense_today.setText();
}
});
}
private Thread resumeSaleInfo = new Thread(new Runnable() {
#Override
public void run() {
salesToday = salesUtils.getSalesDuring(ApplicationUtils.getStartingDateTime(simpleDateTimeFormat.format(System.currentTimeMillis())), ApplicationUtils.getEndingDateTime(simpleDateTimeFormat.format(System.currentTimeMillis())));
if (getActivity() != null && isAdded())
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tv_total_purchase_today.setText(ApplicationUtils.getBengaliNumber(salesToday.size() + "") + " " + getString(R.string.buy_today_label));
tv_total_sale_today.setText(ApplicationUtils.currencyFormat(SalesUtils.getTotalSale(salesToday)));
tv_total_expense_today.setText(ApplicationUtils.getBengaliNumber(SalesUtils.countUnitSold(productSoldToday) + "") + " " + getString(R.string.unit_sold));
}
});
}
});
private void setListeners() {
cv_sale_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homePresenter.showSaleAt(simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
cv_purchase_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homePresenter.showSaleAt(simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
cv_expense_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homePresenter.showUnitSold(simpleDateTimeFormat.format(System.currentTimeMillis()), simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
}
public void setDashboard(DashboardResponse dashboardResponse) {
Log.e("DASHBOARD", new Gson().toJson(dashboardResponse));
this.dashboardResponse = dashboardResponse;
setSaleInformations();
}
}
That means either the text views haven't loaded onto the screen yet or the views haven't been initialized yet.

I need call another activity automatic, more not know where to put code, facebook login

Sorry my english ! need call another activity automatic, more not know where to put code, "facebook login sdk" It how is code, "startActivity" not function
/** * A placeholder fragment containing a simple view. */
public class MainFragment extends Fragment {
private TextView mTextDetails;
private CallbackManager mCallbackManager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("KeyHash", "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onCancel() {
Log.d("KeyHash", "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.d("KeyHash", "onError " + e);
}
};
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();
mTokenTracker.startTracking();
mProfileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
setupTextDetails(view);
setupLoginButton(view);
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onStop() {
super.onStop();
mTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setupTextDetails(View view) {
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}
private void setupTokenTracker() {
mTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
Log.d("KeyHash", "Welcome" + currentAccessToken);
}
};
}
private void setupProfileTracker() {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Log.d("KeyHash", "Welcome" + currentProfile);
mTextDetails.setText(constructWelcomeMessage(currentProfile));
}
};
}
private void setupLoginButton(View view) {
LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
mButtonLogin.setFragment(this);
mButtonLogin.setReadPermissions("public_profile,user_friends,email");
mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);
}
private String constructWelcomeMessage(Profile profile) {
StringBuffer stringBuffer = new StringBuffer();
if (profile != null) {
stringBuffer.append("Welcome " + profile.getName());
}
return stringBuffer.toString();
}
}
If you are trying to start an activity as soon as the user successfully logs in, you can call startActivity(intent) in the onSuccess(LoginResult loginResult) method of the FacebookCallback.
try this in onSuccess method
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String name = object.getString("name");
String id = object.getString("id");
Intent redirect=new Intent(Login_Activity.this,anotheractivity.class);
startActivity(redirect);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Cannot open activity from Fragment inside onSuccess

My issue is very simple, I want users to login using Facebook. After a successful login, grab some details and pass it on another activity. I have my new class in manifeset. I see the log for Log.v("facebook - profile", profile.getFirstName()); I'm quite baffled about what's going on. I have no errors either. I'm passing my activity in the onSuccess.
public class MainActivityFragment extends Fragment {
TextView textview;
private AccessTokenTracker tokenTracker;
private ProfileTracker profileTracker;
private CallbackManager mCallbackManager;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
if(Profile.getCurrentProfile() == null) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
Log.v("facebook - profile", profile2.getFirstName());
profileTracker.stopTracking();
}
};
profileTracker.startTracking();
}
else {
Profile profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
//get info to pass to next activity
String[] profileDetailsArray = new String [5];
profileDetailsArray[0] = profile.getFirstName();
profileDetailsArray[1] = profile.getLastName();
profileDetailsArray[2] = profile.getId();
Bundle arrayBundle = new Bundle();
arrayBundle.putStringArray("profileDetails",profileDetailsArray);
Intent intent = new Intent(getActivity(),LandingPage.class);
intent.putExtras(arrayBundle);
startActivity(intent);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "public_profile"));
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager,mCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume(){
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onStop(){
super.onStop();
}
}

Show view contents after successfully authentication

How and Where do I set view contents to be displayed for persons who has successfully been authenticated using Facebook SDK?
After the persons has logged In, I want to display a User profile view.
I have tried to Instansiate a new fragment like the code below, but that don't work. The text "Fish" Is not displayed.
public class LoginFragment extends Fragment {
private CallbackManager mCallbackManager;
private static final String TAG = "Facebook";
private LoginButton login;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, " logged in...");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile(); //Access the profile who Is the person login in
if(profile != null) {
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if(fragment == null) {
fragment = new LoggedInFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.i(TAG, " Error");
}
};
public LoginFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
//Ask the use for permission to access friends
loginButton.setReadPermissions("user_friends");
//Because we work with fragments
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager, mCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Here IS fragement that the user should see when he/she Is logged In:
package com.waddapp.bryan.waddapp;
public class LoggedInFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.logged_in, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
TextView mTextDetails = (TextView)view.findViewById(R.id.text_details);
mTextDetails.setText("FISH");
}
public LoggedInFragment() {
}
}
Anyone who can explain how acomplish this?

Passing Facebook variables to Tab android

I want to know if there's a way to get and pass FBUSER and FBID to each of my tab bars, and use them in every web view by passing them in the url, because I need to use them in my web views.
Here is the code:
public class SampleFragment extends Fragment {
private static final String ARG_POSITION = "position";
private WebView myWebView;
private String LOG_TAG = "AndroidWebViewActivity";
private int position;
public static SampleFragment newInstance(int position) {
SampleFragment f = new SampleFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
position = getArguments().getInt(ARG_POSITION);
View rootView = inflater.inflate(page, container, false);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
final ProgressBarCircular progressBarCircular = (ProgressBarCircular) rootView.findViewById(R.id.progress);
Log.i("ADebugTag", "Value: ");
final WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setSupportZoom(false);
webView.setInitialScale(0);
LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
// If using in a fragment
loginButton.setFragment(this);
// Other app specific specialization
CallbackManager callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Profile profile = Profile.getCurrentProfile();
String firstName = profile.getFirstName();
String a = "a";
Log.i("ADebugTag", "Value: " + firstName);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.i("ADebugTag", "BANANA ");
}
#Override
public void onError(FacebookException exception) {
Log.i("ADebugTag", "BOOH ");
}
});
switch (position) {
case 0:
fab.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
webView.loadUrl("file:///android_asset/eventiresponsive.html");
}
});
webView.loadUrl("file:///android_asset/eventiresponsive.html");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
progressBarCircular.setVisibility(View.GONE);
}
});
loginButton.setVisibility(View.GONE);
break;
case 1:
fab.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
webView.loadUrl("file:///android_asset/fotostream.html");
}
});
loginButton.setVisibility(View.GONE);
webView.loadUrl("file:///android_asset/fotostream.html");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
progressBarCircular.setVisibility(View.GONE);
}
});
break;
case 2:
fab.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
webView.loadUrl("file:///android_asset/eventiresponsive.html");
}
});
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
progressBarCircular.setVisibility(View.GONE);
}
});
loginButton.setVisibility(View.GONE);
webView.loadUrl("http://www.google.com");
break;
case 3:
fab.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
break;
}
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
CallbackManager callbackManager = CallbackManager.Factory.create();
callbackManager.onActivityResult(requestCode, resultCode, data);
}
I know that simply getting these variables can be quite tricky because they're always nested in callback methods.
What I do is store them in SharedPreferences, and then I get them easily in another part of the app.
To write more elegant and more importantly safe/efficient code, you can look up event bus (like Otto, EventBus) or Observables (RxJava) which can handle sending these objects asynchronously very easily !
Hope I helped you :).

Categories

Resources