I need a camera function in my CameraFragment.java file. I already have the code for the camera and it is working in a empty application (when I put it in my MainActivity), but I don't know where to put the code in my CameraFragment.java.
I am really a beginner with Android Studio, but I couldn't find the answer on the internet. Also new on Stack Overflow.
CameraFragment.java
public class CameraFragment extends Fragment{
public static final String EXTRA_INFO = "default";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_camera, container, false);
}
}
AND I NEED THIS CODE IN MY CameraFragment FILE:
public class MainActivity extends AppCompatActivity {
private Button btnCapture;
private ImageView imgCapture;
private static final int Image_Capture_Code = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_camera);
btnCapture =(Button)findViewById(R.id.btnTakePicture);
imgCapture = (ImageView) findViewById(R.id.capturedImage);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == Image_Capture_Code) {
if (resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgCapture.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
}
}
Let me know how this works for you. Comment if you need more help setting this up.
public class CameraFragment extends Fragment {
public static final String EXTRA_INFO = "default";
private Button btnCapture;
private ImageView imgCapture;
private static final int Image_Capture_Code = 1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_camera, container, false);
btnCapture =(Button) view.findViewById(R.id.btnTakePicture);
imgCapture = (ImageView) view.findViewById(R.id.capturedImage);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Image_Capture_Code) {
if (resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgCapture.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();
}
}
}}
In fragment use same as activity but make method public
try this code
public class ChatFragment extends Fragment {
private RecyclerView chatRecylerview;
View view;
ChatUserlistAdapter userlistAdapter;
LinearLayoutManager manager;
ArrayList<HashMap<String, String>> userDetail = new ArrayList<>();
HashMap<String, String> data;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_chat, container, false);
btnCapture =(Button)view.findViewById(R.id.btnTakePicture);
imgCapture = (ImageView)view.findViewById(R.id.capturedImage);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Image_Capture_Code) {
if (resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgCapture.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
}
}
Related
i am trying create an app that is capable of uninstalling the other installed apps . So when i am using uninstall intent the dialog box opened ask for Ok or cancel. so how can i get informed whether the user selected ok or cancel as i need to hide the the uninstall button that is pressed. Assigned as button present in public class viewholder at end of the code
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
MainActivity mainActivity=new MainActivity();
private Context mContext;
List<Drawable> images;
List<String> titles;
List<String> apps;
LayoutInflater inflater;
public void uninstallAPK(String apkPackageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + apkPackageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivity(intent);
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
launchBrowser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchBrowser.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivity(launchBrowser);
mainActivity.finish();
}
public Adapter(Context ctx, List<String> titles, List<Drawable>
images,List<String> apps){
this.titles =titles;
this.images = images;
this.apps = apps;
this.inflater =LayoutInflater.from(ctx);
mContext = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view = inflater.inflate(R.layout.custom_grid_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int
position) {
holder.title.setText(titles.get(position));
holder.gridIcon.setImageDrawable(images.get(position));
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView gridIcon;
TextView title;
Button button;
Button button3;
public ViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textView);
gridIcon = itemView.findViewById(R.id.imageView2);
button = itemView.findViewById(R.id.button);
button3 = itemView.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uninstallAPK(apps.get(getAdapterPosition()));
//want to hide the button if ok is pressed otherwise want
to show the button
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ParseQuery<ParseObject> linkwa = new
ParseQuery<ParseObject>("package");
linkwa.whereEqualTo("packid",
apps.get(getAdapterPosition()));
linkwa.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects,
ParseException e) {
if(e==null && objects.size()>0){
for (ParseObject object:objects){
goToUrl(object.getString("link"));
}
}
}
});
}
});
}
}
}
There is actually workaround that you can give a try
StartActivityFotResult which will ensure you will get the callback inside onActivityResult
public void uninstallAPK(String apkPackageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + apkPackageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivityForResult(intent, 12345);
}
Now you can check the Result-Code whether it is a success or not RESULT_OK or RESULT_CANCELLED
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234) {
if(resultCode == Activity.RESULT_OK){
//Deleted
}
if (resultCode == Activity.RESULT_CANCELED) {
//Dismissed
}
}
}//onActivityResult
2.1. If the above-mentioned solution did not work then
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234) {
if (appInstalledOrNot("required_app_package_name")){
// Dismissed
}else {
//Deleted
}
}
}//onActivityResult
private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
PS. Checking if an app is installed or not is taken from here
Don't really know how is your implementation, but ideally I would have two button. One for cancel another for uninstall. And I would have set clicklistener on both of the button. So, whenever, the onclickListener is executed, means user pressed the button of the dialog box. So, first thing, I would dissmiss the dialog, second thing based on the button user clicked
public void onClick(View v){
if(v.getId == R.id.btn_dialog_uninstall){
uninstallPackage("package_name");
dialog.dissmiss();
}else{
dialog.dissmiss(); // user pressed cancelled;
}
hope that helps.
i want to get data from a edit text and give to adapter but adapter is null
data isnt null because i can toast it but it doesnt show in my model
My question now is: when is an adapter null in RecyclerView and what might be the solution to the problem?
Please help a green developer; this is my first app. Any suggestion would be welcomed.
this is my Main Activity
public class MainActivity extends AppCompatActivity {
public static final int request_code=1001;
RecyclerView recyclerView;
NoteListAdapter noteListAdapter;
List<Notes> Notes_list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.mainAc_recyclerview_notes);
noteListAdapter = new NoteListAdapter(this,Notes_list);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(noteListAdapter);
Button newnote= findViewById(R.id.mainAc_button_new);
newnote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,GenerateNote.class);
startActivityForResult(intent,request_code);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==request_code && resultCode==RESULT_OK && data!=null){
String name=data.getExtras().getString(result_name);
String description=data.getExtras().getString(result_description);
Notes notes=new Notes();
notes.setSnTitle(name);
notes.setSnDescription(description);
NoteListAdapter adapter=new NoteListAdapter(this,Notes_list);
adapter.addNote(notes);
Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
}
}
adapter
public class NoteListAdapter extends RecyclerView.Adapter<NoteListAdapter.notesViewHolder> {
#NonNull
private Context context;
private List<Notes> notes_list=new ArrayList<>();
public NoteListAdapter(Context context, List<Notes> notes_list) {
this.context = context;
this.notes_list=notes_list;
}
#Override
public NoteListAdapter.notesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_sample_note, parent, false);
return new notesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NoteListAdapter.notesViewHolder holder, int position) {
holder.bindNotes(notes_list.get(position));
}
#Override
public int getItemCount() {
return notes_list.size();
}
public void addNote(Notes notes){
notes_list.add(notes);
notifyItemInserted(1);
}
public class notesViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView description;
notesViewHolder(#NonNull View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.sn_textview_title);
description = (TextView)itemView.findViewById(R.id.sn_textview_description);
}
public void bindNotes(Notes notes) {
title.setText(notes.getSnTitle());
description.setText(notes.getSnDescription());
}
}
}
and activity for result
public class GenerateNote extends AppCompatActivity {
public static final String result_name="result_name";
public static final String result_description="result_description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generate_note);
final EditText name=findViewById(R.id.gn_edittext_name);
final EditText description=findViewById(R.id.gn_edittext_family);
Button save=findViewById(R.id.gn_button_save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra(result_name,name.getText().toString());
intent.putExtra(result_description,description.getText().toString());
setResult(RESULT_OK,intent);
finish();
}
});
}
}
change below code in onActivityResult() ;)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==request_code && resultCode==RESULT_OK && data!=null){
String name=data.getExtras().getString(result_name);
String description=data.getExtras().getString(result_description);
Notes notes=new Notes();
notes.setSnTitle(name);
notes.setSnDescription(description);
Notes_list.add(notes); // change here
adapter.notifyDataSetChanged(); // change here
Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
}
You have a method in the adapter to add Note. So, you can directly use that method Adapter.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==request_code && resultCode==RESULT_OK && data!=null){
String name=data.getExtras().getString(result_name);
String description=data.getExtras().getString(result_description);
Notes notes=new Notes();
notes.setSnTitle(name);
notes.setSnDescription(description);
adapter.addNote(notes); // Use Adapter method
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
}
public class ProfileFragment extends Fragment {
ImageView mImageview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
mImageview = (ImageView) view.findViewById(R.id.imgView);
view.findViewById(R.id.buttonLoadPicture).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
2000);
}
else {
startGallery();
}
}
});
return view;
}
private void startGallery() {
Intent cameraIntent = new Intent(Intent.ACTION_GET_CONTENT);
cameraIntent.setType("image/*");
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == RESULT_OK) {
}
Uri returnUri;
returnUri = data.getData();
Glide.with(this)
.load(returnUri)
.override(1280, 1280)
.centerCrop()
.crossFade()
.into(mImageview);
}
Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
I tried using the glide dependency and I am working in fragments not activity this code doesn't give anything in the output.
Even the gallery isn't opening
Can someone tell what have i left ?
Looking forward to a prompt reply.
I am trying to get a callback from an activity that I am starting with an intent in my fragment.
I thought I could do this with onActivityResult but it doesn't seem to get called when I finish(); on the activity. Is this possible in a fragment?
Fragment.java
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Waiver");
myView = inflater.inflate(R.layout.waiver_layout, container, false);
signBtn = myView.findViewById(R.id.signBtn);
signBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SignatureActivity.class);
intent.putExtra("signatureAbleId", device.id);
intent.putExtra("signatureAbleType", "App\\Models\\Device");
startActivity(intent);
}
});
return myView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
Log.v("Activity", "The activity has finished");
if(resultCode == 200){
saveWaiver();
}
}
private void saveWaiver(){
Log.v("Save Waiver", "Saving waiver for you.");
}
SignatureActivity.java
public class SignatureActivity extends AppCompatActivity {
private Button btnClear;
private Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_signature);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
signatureAbleId = bundle.getInt("signatureAbleId");
signatureAbleType = bundle.getString("signatureAbleType");
}
btnClear = findViewById(R.id.btnClear);
btnSave = findViewById(R.id.btnSave);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSignaturePad.clear();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
setResult(200);
finish();
});
}
}
Use this. It will help you
Intent intent = new Intent(getContext(), SignatureActivity.class);
Instead of
Intent intent = new Intent(getActivity(), SignatureActivity.class);
And Yes need to change :
startActivity to startActivityForResult
Use startActivityForResult instead of startActivity
startActivityForResult(intent, 11);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 11){
if(resultCode == 200){
saveWaiver();
}
}else{
super.onActivityResult(requestCode, resultCode, data)
}
}
I have nested fragment like the following.
MainActivity
FragmentA
FragmentA1
FragmentA3
FragmentA2
FragmentB
FragmentB1
I want to login facebook from FragmentA3. But can not.
In FragmentA3, my app stop in onResume after called onActivityResult.
What should I do?
FragmentA3
public class FragmentA3 extends Fragment {
public static final String TAG = FragmentA3.class.getCanonicalName();
private UiLifecycleHelper mFbSdkUiHelper;
private OnLoggedListener mCallback;
private final List<String> permissions;
public OthersFBLogin() {
// Required empty public constructor
permissions = Arrays.asList("basic_info", "email");
}
public interface OnLoggedListener {
//Callback to notify about login success.
public void onLoginSuccess();
}
private final Session.StatusCallback mSessionCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.d(TAG,"onSessionStateChange");
if (state.isOpened()) {
mCallback.onLoginSuccess();
} else if (state.isClosed()) {
if (session != null) {
session.closeAndClearTokenInformation();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG,"onCreate");
super.onCreate(savedInstanceState);
mFbSdkUiHelper = new UiLifecycleHelper(getActivity(), mSessionCallback);
mFbSdkUiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG,"onCreateView");
View rootView = inflater.inflate(R.layout.others_fblogin, container, false);
LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
loginButton.setFragment(this);
loginButton.setReadPermissions(permissions);
return rootView;
}
#Override
public void onAttach(Activity activity) {
Log.d(TAG,"onAttach");
super.onAttach(activity);
try {
mCallback = (OnLoggedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnLoggedListener in order to use this fragment");
}
}
#Override
public void onResume() {
Log.d(TAG,"onResume");
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
mFbSdkUiHelper.onResume();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
Log.d(TAG,"onPause");
super.onPause();
mFbSdkUiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mFbSdkUiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG,"onSaveInstanceState");
super.onSaveInstanceState(outState);
mFbSdkUiHelper.onSaveInstanceState(outState);
}
}
LogCat
D/com.example.sample.FragmentA3 ﹕ onAttach
D/com.example.sample.FragmentA3 ﹕ onCreate
D/com.example.sample.FragmentA3 ﹕ onCreateView
D/com.example.sample.FragmentA3 ﹕ onResume
D/dalvikvm ﹕ GC_FOR_ALLOC freed 764K, 10% free 7977K/8816K, paused 3ms, total 6ms
W/GooglePlayServicesUtil ﹕ Google Play services is missing.
D/com.example.sample.FragmentA3 ﹕ onPause
D/com.example.sample.FragmentA3 ﹕ onSessionStateChange
W/EGL_emulation ﹕ eglSurfaceAttrib not implemented
I/Choreographer ﹕ Skipped 174 frames! The application may be doing too much work on its main thread.
D/com.example.sample.MainActivity﹕ onActivityResult
D/com.example.sample.FragmentA ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onResume
Please try this solution:
public class FragmentA3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Fragment fragmentA1 = this.getParentFragment();
Fragment fragmentA = fragmentA1.getParentFragment();
loginButton.setFragment(fragmentA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA1 extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA3 !=null)
mFragmentA3.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA1 !=null)
mFragmentA1.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
Step 1: Add the below code in the fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
context = getContext();
FacebookSdk.sdkInitialize(context);
View view = inflater.inflate(R.layout.fragment_facebook_sign_in, container, false);
}
Step 2: Handle the callback of facebook.
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = object.getString("email");
String firstName = object.getString("first_name");
String lastName = object.getString("last_name");
profile_link = object.getString("link");
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
Utility.logMe("\nFacebook_user_mail:"+email +"\nFacebook_user_Fname:"+firstName+"\nFacebook_user_Lname:"+lastName+"\nFacebook_user_Image:"+profilePicUrl+"\nProfile_link:"+profile_link);
if(email != null && email.length()> 0)
{
LoginManager.getInstance().logOut();
signUpFacebook(firstName, lastName, email, profilePicUrl, profile_link);
}
else {
Toast.makeText(getActivity(), "Email not present to login", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Email Not Exist for this user on Facebook.", Toast.LENGTH_LONG).show();
progressDialog = new ProgressDialog(getContext());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,link,name,email,birthday,gender,first_name,last_name,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
Step 3:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
//displayMessage(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
Step 4:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
Step 5:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Step 6:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
for (Fragment fragmento : allFragments) {
if (fragmento instanceof TwitterSignIn) {
((TwitterSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof GooglePlusSignIn) {
((GooglePlusSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof FacebookSignIn) {
((FacebookSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
}
}