Show view contents after successfully authentication - java

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?

Related

Why is my code always receiving a null pointer exception when I have binded the element in to it? I am using Java in Android Studio

I am receiving java.lang.NullPointerException, although I have binded the element correctly.
Tried to check the ID of the element, it matches, but still I receive the same exception.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Text to Speech
tts = new TextToSpeech(this, this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
speakButton = view.findViewById(R.id.speakButton);
}
}
It should be running fine, But I am receiving the java.lang.NullPointerException
You button code should be declared in you fragment not in you activity as the button is in your fragment.xml. As you are accessing the button in onCreate method of the activity it will give nullpointer exception because you fragment's view is not yet rendered.The best practice is to access the view in onViewCreated function of your fragment.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Text to Speech
tts = new TextToSpeech(getActivity(), this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
}
void speakOut(){
}
The solution is to implement TextToSpeech.OnInitListener in the project and make the public variables to be private.
public class TranslatorFragment extends Fragment implements TextToSpeech.OnInitListener{
private Button speakButton; // public Button speakButton;
private TextToSpeech tts;
private EditText speechText; // public EditText speechText;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tts = new TextToSpeech(getActivity(), this);
speakButton = view.findViewById(R.id.speakButton);
speechText = view.findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
}
private void speakOut(){
String text = speechText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status){
if(status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(getActivity(), "Language not supported!", Toast.LENGTH_SHORT).show();
} else {
speakButton.setEnabled(true);
speakOut();
}
}
else
{
Toast.makeText(getActivity(), "Initilization failed!", Toast.LENGTH_SHORT).show();
}
}
public void onDestroy() {
if(tts != null){
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}

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

How to make a new newRequestQueue In Volley, Android

I have an fragment where I try to Instantiate a new newRequestQueue with the Volley API.
I try to instantiate it like this:
RequestQueue queue = Volley.newRequestQueue(this);
However, when I try to create the request, I get the following error:
newRequestQueue In Volley cannot be applied to annonymous android.view.View.OnClickListener
Here is my Fragment class:
public class LoginFragment extends Fragment {
private FacebookLogin fLogin;
private Profile profile;
private CallbackManager mCallbackManager; //Used in activity result below. Gets a value when u hit the button
private static final String TAG = "Event";
private static String url_create_user = "127.0.0.1/create_row.php";
#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);
final ImageView profilP = (ImageView) getView().findViewById(R.id.profilePicture);
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
RequestQueue queue = Volley.newRequestQueue(this);
fLogin.setFacebookListener(new FacebookLogin.OnFacebookListener() {
#Override
public void onFacebookLoggedIn(JSONObject parameters) {
Log.i(TAG, "INNNNNNNNNNNE");
Log.i(TAG, parameters.toString());
}
});
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager = fLogin.getCallbackManager(); //Get the callbackmanager
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
the parameter of newRequestQueue is a Context object. In your case, this, refers to the View.OnClickListener anonymous inner class, where you are calling newRequestQueue. Change
Volley.newRequestQueue(this);
with
Volley.newRequestQueue(getActivity().getApplicationContext());
is, of course, getActivity() because you are subclassing Fragment
RequestQueue requestQueue = Volley.newRequestQueue(SignupActivity.this);
In this case, SignupActivity is the activity you have typed your code in.

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

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.

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