package com.example.feelhut;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class editprofile extends AppCompatActivity {
ImageButton proileimagebutton;
private static final int ImageRequest=1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
proileimagebutton= findViewById(R.id.edit_profile);
proileimagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("imageeeeeee/");
There ImageRequest showing Error in startActivityForResult. Means I am not able to identify image request here.
startActivityForResult(intent.ImageRequest);
}
});
}
}
public class editprofile extends AppCompatActivity {
ImageButton proileimagebutton;
private static final int ImageRequest=1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//no content view? add like this setContentView(R.layout.yourViewLayout);
proileimagebutton= findViewById(R.id.edit_profile);
proileimagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,ImageRequest);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ImageRequest&& resultCode == RESULT_OK) {
// your ImageView.setUri(data.getData();
}
}
}
You need to declare int above "public class editprofile extends AppCompatActivity".
The code should be
private ImageButton proileimagebutton;
private static final int ImageRequest=1;
public class editprofile extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
proileimagebutton= findViewById(R.id.edit_profile);
proileimagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("imageeeeeee/");
Related
There must be a way to get intent result in a class without using onActivityResult. By using other methods...
I dont know how, but Iam sure there is a way.
My class that should get the result of the intent filepicker from this class without using onActivityResult in the MainActivity.java that extents activity. FilePicker.java
package com.hadiawali.codeeditor;
import android.content.Intent;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
public class FilePicker {
Intent filePicker = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
public static void startPicking(Activity activity) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Intent chooseFolder = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
chooseFolder.addCategory(Intent.CATEGORY_DEFAULT);
activity.startActivityForResult(Intent.createChooser(chooseFolder, "Choose directory"), 9999);
}
}
}
My class that extents activity. MainActivity.java
package com.hadiawali.codeeditor;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
FilePicker.startPicking(MainActivity.this);
//I need to get the intent reslut from the class without using onActivityResult
}
});
}
}
For example you send to intent from activity A to B then
in Activity A create Activity Result like below
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// callback called
}
}
});
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//call B activity
someActivityResultLauncher.launch(intent);
}
in Activity B your task is successfully complete then set
setResult(RESULT_OK);
finish();
or if task is not complete successfully then put
setResult(RESULT_CANCELED);
finish();
I'm really confused on how to add from another activity I keep getting an error in this part of the code:
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
So the error says "actual and formal argument lists differ in length". if anyone could help me out it would be such a huge help thank you :)
this my code:
main activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button newEmail;
private ListView listView;
private EmailAdapter emailAdapter;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
emailAdapter = new EmailAdapter(this, emailsArrayList);
listView.setAdapter(emailAdapter);
updateList();
newEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SendActivity.class);
startActivity(intent);
}
});
}
private void init(){
newEmail = (Button) findViewById(R.id.newBtn);
listView = (ListView) findViewById(R.id.list);
emailsArrayList = new ArrayList<>();
Emails emails = new Emails ();
emails.setEmails("josemari#yahey.com");
emails.setSubject("Sample Data");
emails.setBody("this is the sample data");
emailsArrayList.add(emails);
}
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onStart() {
super.onStart();
Log.d("MainActivity","onStart invoked");
}
#Override
protected void onResume() {
super.onResume();
Log.d("MainActivity","onResume invoked");
}
#Override
protected void onPause() {
super.onPause();
Log.d("MainActivity","onPause invoked");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
this is the add item activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class SendActivity extends AppCompatActivity {
private Button send;
private Button discard;
private EditText email;
private EditText subject;
private EditText body;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
send = (Button) findViewById(R.id.sendBtn);
discard = (Button) findViewById(R.id.discardBtn);
email = (EditText) findViewById(R.id.inputEmail);
subject = (EditText) findViewById(R.id.inputSubject);
body = (EditText) findViewById(R.id.inputBody);
discard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SendActivity.this, MainActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputEmail = email.getText().toString();
String inputSubject = subject.getText().toString();
String inputBody = body.getText().toString();
if (inputBody.isEmpty() || inputEmail.isEmpty() || inputEmail.isEmpty()){
Toast.makeText(SendActivity.this, "Please enter the following data", Toast.LENGTH_SHORT).show();
}
else {
emailsArrayList = new ArrayList<>();
Emails newEmails = new Emails ();
newEmails.setEmails(inputEmail);
newEmails.setSubject(inputSubject);
newEmails.setBody(inputBody);
emailsArrayList.add(newEmails);
Intent intent = new Intent();
getIntent().putExtra("inputEmail", inputEmail);
getIntent().putExtra("inputSubject", inputSubject);
getIntent().putExtra("inputBody", inputBody);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}
I would also change the following as well:
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
to
private void updateList()
{
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle != null)
{
Emails a = new Emails(String)bundle.get("inputEmail"), (String)bundle.get("inputBody"), (String)bundle.get("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
I would try this absolutley first: You may beable to use what you have and just change the Bundle bundle and Intent intent lines around in your updateList(). Again no expert but try that first and then above that second. I hope it works for you.
In my app, I have music playing when the app starts. If the user goes to settings they can change the volume or turn the music on and off, however I do not know how to recall the information from the radio buttons to turn the music on or off in other activities. I know if I turn the music off in the main activity under onCreate it will listen to the radio buttons, but I want music playing when the app starts and when you resume the activity it inputs the info from the radio buttons.
This is the code of my main activity
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent svc = new Intent(this, music.class
);
startService(svc);
}
public void onPlayPressed(View view) {
Intent myIntent = new Intent(getBaseContext(), Game.class);
startActivity(myIntent);
}
public void onSettingsPressed(View view) {
Intent myIntent = new Intent(getBaseContext(), Settings.class);
startActivity(myIntent);
}
public void onHowtoPressed(View view) {
Intent myIntent = new Intent(getBaseContext(), HowtoPlay.class);
startActivity(myIntent);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
Intent svc = new Intent(this, music.class);
stopService(svc);
}
}
and this is the code of my Settings activity
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Toast;
public class Settings extends AppCompatActivity {
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final Intent svc = new Intent(this, music.class
);
RadioButton rdb = (RadioButton) findViewById(R.id.on);
rdb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean checked = ((RadioButton) v).isChecked();
// Check which radiobutton was pressed
if (checked){
startService(svc);
}
else{
stopService(svc);
}
}
});
RadioButton rdb2 = (RadioButton) findViewById(R.id.off);
rdb2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean checked = ((RadioButton) v).isChecked();
// Check which radiobutton was pressed
if (checked){
stopService(svc);
}
else{
startService(svc);
}
}
});
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar)findViewById(R.id.seekBar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
}
});
}
public void onMainMenuPressed(View view){
Intent myIntent=new Intent(getBaseContext(),MainActivity.class);
startActivity(myIntent);
}
public void onResumePressed (View view){
Intent myIntent=new Intent(getBaseContext(),Game.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(myIntent);
finish();
}
} ```
Use SharedPreferences with simple boolean flag.
You should use onCheckedChangeListener on the radio group rather than onClickListener on individual radio button, like so:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(...) {
getSharedPreferences("prefs", 0).edit().putBoolean("music", rdb.isChecked()).apply();
}
});
Then inside other activity:
boolean music = getSharedPreferences("prefs", 0).getBoolean("music", true);
Then check value of the flag to determine whether or not to start the music service.
I have been trying to start a new activity from a successful login attempt with facebook integration however when the login button is pressed after logging pin it returns to the same activity that the login button is on.
I already have in place an intent to move to the next activity however it doesn't seem to have any response to success of the login.
Here is my code (sorry for the untidiness I've been at this for a long time now):
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphResponse;
import com.facebook.login.Login;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import android.widget.Toast;
import com.facebook.GraphRequest;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.json.JSONObject;
public class userlogin extends FragmentActivity {
LoginButton loginButton; //The Facebook login button
TextView loginstatus;
CallbackManager callbackManager;
private AccessToken accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_userlogin);
loginButton = (LoginButton) findViewById(R.id.fb_login_button);
loginstatus = (TextView)findViewById(R.id.loginstatus);
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
// **Description: If the user cancels the login before it is completed a message will
// be shown to let them know that they are not logged in
//**Parameters:
//** Loginresult: the results of the login attempt.
//**
//**Precondition: loginButton must have been clicked first
//**
//**throws: N/A
//** returns: a textView that displays a message of whether or not the login was succesful
public void onSuccess(LoginResult loginResult) {
loginstatus.setText("Login Success");
accessToken = loginResult.getAccessToken();
Toast.makeText(userlogin.this, "Eureka", Toast.LENGTH_LONG).show();
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("FB", "complete");
Log.d("FB", object.optString("name"));
Log.d("FB", object.optString("link"));
Log.d("FB", object.optString("id"));
Log.d("FB", object.optString("gender"));
TextView Username;
Username = (TextView) findViewById(R.id.loginstatus);
String id = object.optString("id");
String name = object.optString("name");
Username.setText("Welcome:" + name);
ImageView userPhoto = (ImageView) findViewById(R.id.facebookuserPortrait);
String i = "http://graph.facebook.com/" + id + "/picture?type=large";
Glide.with(userlogin.this).load(i).override(350, 350).into(userPhoto);
Intent intent = new Intent(userlogin.this, AlertsandPlanning.class);
startActivity(intent);
}
// **Description: If the user cancels the login before it is completed a message will
// be shown to let them know that they are not logged in
//**Parameters: N/A
//**
//**Precondition: loginButton must have been clicked first
//**
//**throws: N/A
//** returns: a textView that displays a message
public void onCancel() {
loginstatus.setText("Login Canceled");
}
// **Description: If the user has an error during the login before it is completed
// a message will be shown to let them know that they are not logged in
//**Parameters: FacebookException: an error transpoding if the login fails
//**
//**Precondition: loginButton must have been clicked first
//**
//**throws: Exception
//** returns: a textView that displays a message
public void onError(FacebookException exception) {
loginstatus.setText("Something went wrong \n+" +
"Check your credentials and try again");
}
});
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
protected void onActivivityResult(int requestCode, int resultCode, Intent data) {
userlogin.super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
});
}
}
I appreciate any insight given, I may start from scratch on this activity and try again if nothing seems to work.
To reiterate the issue: The "Continue with facebook" button is clicked and the next activity shown is the userlogin activity instead of the AlertsandPlanning activity.
update:
I tried the current first comment here is the updated code,
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import com.facebook.CallbackManager;
import com.facebook.login.widget.LoginButton;
import com.facebook.FacebookSdk;
import android.view.View;
import com.facebook.login.LoginResult;
import com.facebook.FacebookCallback;
import org.json.JSONObject;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.login.LoginManager;
import com.facebook.GraphResponse;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphRequestAsyncTask;
public class UserLogin extends AppCompatActivity implements View.OnClickListener {
LoginButton btnFacebookLogin;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_user_login);
callbackManager = CallbackManager.Factory.create();
setUI();
}
private void setUI() {
btnFacebookLogin = (LoginButton) findViewById(R.id.FBLoginBtn);
btnFacebookLogin.setOnClickListener(this);
btnFacebookLogin.setReadPermissions("email", "public_profile");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.FBLoginBtn:
facebookLogin();
}
}
private void facebookLogin() {
// Callback registration
btnFacebookLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
String username = (user.optString("name"));
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with facebook", Toast.LENGTH_SHORT).show();
Intent startAlertsAndPlanning = new Intent(UserLogin.this, AlertsAndPlanning.class);
startActivity(startAlertsAndPlanning);
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Please try with following code. I hope it will be helpful for you and please use CamelCase Notation for Class Name.
public class Userlogin extends AppCompatActivity implements View.OnClickListener {
LoginButton btnFacebookLogin;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
setUI();
}
private void setUI() {
btnFacebookLogin = (LoginButton) findViewById(R.id.btnFacebookLogin);
btnFacebookLogin.setOnClickListener(this);
btnFacebookLogin.setReadPermissions("email", "public_profile");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnFacebookLogin:
facebookLogin();
}
}
private void facebookLogin() {
// Callback registration
btnFacebookLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
username = (user.optString("name"));
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Userlogin .this, AlertsandPlanning.class));
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
I made a fragment to connect via Facebook, the code of which is here :
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class LoginFragment extends Fragment
{
private TextView mTextDetails;
private CallbackManager fbCallbackManager;
private AccessTokenTracker tTracker;
private ProfileTracker pTracker;
private FacebookCallback<LoginResult> fbCallback = new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onCancel()
{
}
#Override
public void onError(FacebookException error)
{
}
};
public LoginFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
fbCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();
tTracker.startTracking();
pTracker.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)
{
super.onViewCreated(view, savedInstanceState);
setTextDetails(view);
setupFBLoginButton(view);
}
#Override
public void onResume()
{
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onStop()
{
super.onStop();
tTracker.stopTracking();
pTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
fbCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setupFBLoginButton(View view)
{
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(fbCallbackManager, fbCallback);
}
private void setTextDetails(View view)
{
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}
private void setupTokenTracker()
{
tTracker= new AccessTokenTracker()
{
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken)
{
//TODO
}
};
}
private void setupProfileTracker()
{
pTracker = new ProfileTracker()
{
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile)
{
//TODO
}
};
}
}
I am trying to "call" this fragment from my main activity using the following code :
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity
{
private boolean logged = false;
private LoginFragment loginFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
LoginFragment loginFragment = new LoginFragment();
fTransaction.add(R.id.fragment_container, loginFragment, "fragment_container");
fTransaction.commit();
setContentView(R.layout.activity_main);
}
}
Yet, I have an error on the 2nd argument of this line fTransaction.add(R.id.fragment_container, loginFragment, "fragment_container");.
My IDE tells me it's expecting an android.app.Fragment object, and mine is a my.package.LoginFragment.
I don't get it, my LoginFragment extends Fragment...
I also tried to pass everything in android.support.v4.*, but then I can't do loginButton.setFragment(this);, and then I have no idea on how to set the Fragment to the loggin button.
Use getSupportFragmentManager() when working with support fragments instead of getFragmentManager().
Also, adding the fragment should happen after setContentView() so the fragment_container can be found.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginFragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, loginFragment, "fragment_container")
.commit();
}
After doing this you will have to fix a couple imports too. Make sure you use the following in MainActivity.
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;