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 :).
Related
Here I am trying to use post method, which needs authentication which I am trying to send from my most bottom code but it shows multiple error such as : "Unexpected token", etc IDK what to do plese help.
public class HouseOwner extends Fragment {
CircleImageView circleImageView;
ImageView imageView;
private static final int PICK_Image=1;
Button button;
EditText a,b,c,d,e,f;
CheckBox g,h;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public HouseOwner() {
// Required empty public constructor
}
public static HouseOwner newInstance(String param1, String param2) {
HouseOwner fragment = new HouseOwner();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity(). getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_house_owner, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/* TextView textView = view.findViewById(R.id.search);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(startActivity();));*//*
}
});*/
imageView = view.findViewById(R.id.pick);
a = view.findViewById(R.id.edtTitle);
b = view.findViewById(R.id.edtdescription);
c = view.findViewById(R.id.edtEmail);
d = view.findViewById(R.id.edtphone);
e = view.findViewById(R.id.edtLocation);
f = view.findViewById(R.id.edtPrice);
/*g = view.findViewById(R.id.rad1);
h = view.findViewById(R.id.rad2);*/
button = view.findViewById(R.id.done);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(a.getText().toString()) || TextUtils.isEmpty(b.getText().toString())
|| TextUtils.isEmpty(c.getText().toString()) || TextUtils.isEmpty(d.getText().toString()) || TextUtils.isEmpty(e.getText().toString())
|| TextUtils.isEmpty(f.getText().toString())){
Toast.makeText(getActivity(), "Please fill all the details", Toast.LENGTH_LONG).show();
}
else{
rooms();
}
}
});
CircleImageView circleImageView = view.findViewById(R.id.add);
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select"),PICK_Image);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode, data);
if (requestCode == 1){
Uri uri = data.getData();
imageView.setImageURI(uri);
}
}
private void rooms() {
RoomPostRequest roomPostRequest = new RoomPostRequest();
roomPostRequest.setTitle(a.getText().toString());
roomPostRequest.setDescription(b.getText().toString());
roomPostRequest.setEmail(c.getText().toString());
roomPostRequest.setPhone_number(d.getText().toString());
roomPostRequest.setLocation(e.getText().toString());
roomPostRequest.setPrice(f.getText().toString());
/*roomPostRequest.setInternet(g.getText().toString());
roomPostRequest.setParking(h.getText().toString());*/
Call<RoomPostResponse> RoomPostRsp = ApiPost.roomPost().postRooms(roomPostRequest);
RoomPostRsp.enqueue(new Callback<RoomPostResponse>() {
#Override
public void onResponse(Call<RoomPostResponse> call, Response<RoomPostResponse> response) {
if (response.isSuccessful()){
String token = response.body().getToken().toString();
// Log.i("login", "Token: " + token);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("secret", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString("token", token);
edit.commit();
Toast.makeText(getActivity(), "Sending", Toast.LENGTH_LONG).show();
}
else { Toast.makeText(getActivity(),"Login Failed",Toast.LENGTH_LONG).show();}
}
#Override
public void onFailure(Call<RoomPostResponse> call, Throwable t) {
Toast.makeText(getActivity(),"Throwable"+t.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
});{
***#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
SharedPreferences p = getContext().getSharedPreferences("secret", Context.MODE_PRIVATE);
String token = p.getString("token", "");
params.put("Authorization", "Token " + token);
return params;***
}
}}}
I wan't to force logout from facebook when I exit the application so I have to login every time I start the application. If that is not possible I need help with checking if a user is already logged in.
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
if (object != null) {
name = object.getString("first_name") + " "+object.getString("last_name");
email = object.getString("email");
mTextDetails.setText("Welcome " + name);
editor.putString("username", name);
editor.putString("email", email);
editor.apply();
}
} catch (JSONException e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email, first_name, last_name, gender");
request.setParameters(parameters);
request.executeAsync();
}
// }
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
public MainFragment() {
// Required empty public constructor
}
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) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
mTextDetails = (TextView) view.findViewById(R.id.text_details);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email");//Only ask if you must
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager, mCallback);
sharedPref = this.getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
editor = sharedPref.edit();
name = sharedPref.getString("username", "");
email = sharedPref.getString("email","");
if (name != "") {
mTextDetails.setText(name);
}
// Toast.makeText(getActivity(), sharedPref.getString("username", ""), Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), sharedPref.getString("email", ""), Toast.LENGTH_LONG).show();
return view;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
You can use this LoginManager.getInstance().logOut();
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();
}
}
});
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();
}
}
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?