my fragment showing blank screen after i am having this code - android

package com.example.mindwareuae;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter.LengthFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
public class FacebokkFragment extends Fragment{
private LoginButton loginBtn;
private Button postImageBtn;
private Button updateStatusBtn;
private TextView userName;
private UiLifecycleHelper uiHelper;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
try
{
View rootView = inflater.inflate(R.layout.fragment_facebook,container,false);
userName = (TextView)rootView.findViewById(R.id.user_name);
loginBtn = (LoginButton) rootView.findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
} else {
userName.setText("You are not logged");
}
}
});
postImageBtn = (Button)rootView.findViewById(R.id.fbpost_image);
postImageBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
postImage();
}
});
updateStatusBtn = (Button)rootView.findViewById(R.id.fbupdate_status);
updateStatusBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonsEnabled(false);
}catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
public void buttonsEnabled(boolean isEnabled) {
postImageBtn.setEnabled(isEnabled);
updateStatusBtn.setEnabled(isEnabled);
}
public void postImage() {
if (checkPermissions()) {
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(getActivity(),
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
} else {
requestPermissions();
}
}
// public void postStatusMessage() {
// if (checkPermissions()) {
// Request request = Request.newStatusUpdateRequest(
// Session.getActiveSession(), message,
// new Request.Callback() {
// #Override
// public void onCompleted(Response response) {
// if (response.getError() == null)
// Toast.makeText(getActivity(),
// "Status updated successfully",
// Toast.LENGTH_LONG).show();
// }
// });
// request.executeAsync();
// } else {
// requestPermissions();
// }
// }
public boolean checkPermissions() {
Session s = Session.getActiveSession();
if (s != null) {
return s.getPermissions().contains("publish_actions");
} else
return false;
}
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
// #Override
// public void onResume() {
// super.onResume();
// uiHelper.onResume();
// buttonsEnabled(Session.getActiveSession().isOpened());
// }
//
// #Override
// public void onPause() {
// super.onPause();
// uiHelper.onPause();
// }
//
// #Override
// public void onDestroy() {
// super.onDestroy();
// if (rootView != null) {
// ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
// if (parentViewGroup != null) {
// parentViewGroup.removeAllViews();
// }
// }
// uiHelper.onDestroy();
// }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
i want login the facbook from this fragment..but i am not getiing any thing my xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="20dp"
android:background="#EEEEEE">
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
<TextView
android:id="#+id/fb_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textSize="18sp" />
<Button
android:id="#+id/fbupdate_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="update_status" />
<Button
android:id="#+id/fbpost_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post_image" />
</LinearLayout>
it is my xml file why i am not able to get the fragment with my facebook login button.
please any one can explain me.

Create a FragmentActivity and add your fragment to that FragmentActivity
public class MainActivity extends FragmentActivity{
FacebokkFragment fbFragment;
ArrayList<Fragment> fragemetnList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fbFragment = new FacebokkFragment();
fragemetnList = getFragmnetsList();
setContentView(R.layout.activity_main);
}
ArrayList<Fragment> getFragmnetsList() {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(fbFragment);
// you can also add more fragments here
return fragments;
}
}
Now create an activity_main.xml file into your res/layout directory
Don't forget to make the entry of your MainActivity into AndroidManifest.xml file
May this code will solve your problem

if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
Is this part of code really required? Try removing this.
Try this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container, false);
...
return rootView;

Related

ZXing 3.6.0 in portrait mode?

I use XZing 3.6.0 to scan QR codes within my Android app.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.Result;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class MainActivity extends AppCompatActivity {
Button btnScan;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScan = (Button) findViewById(R.id.btn_scan);
tv = (TextView) findViewById(R.id.tv);
btnScan.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this);
scanIntegrator.setOrientationLocked(false);
scanIntegrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
tv.setText(scanContent);
}
else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
AndroidManifest.xml
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
>
It works... except the camera is shown in landscape mode. How to change that to portrait mode?
Add this to your Manifest File :
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="android:screenOrientation"
android:stateNotNeeded="true"/>
try this in XML file :
<com.journeyapps.barcodescanner.CompoundBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="0dp"
app:zxing_viewfinder_mask="#ffffff"
android:layout_weight="40"
>
</com.journeyapps.barcodescanner.CompoundBarcodeView>
and here is the fragment code :
public class ScanFragment extends Fragment {
private String toast;
private LinearLayout qrCameraLayout;
IntentIntegrator intentIntegrator;
private CompoundBarcodeView barcodeView;
private TextView tv_qr_print;
public ScanFragment() {
}
public static ScanFragment newInstance(int page, String title, ViewPager viewPager) {
ScanFragment fragmentFirst = new ScanFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
displayToast();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
intentIntegrator = new IntentIntegrator(getActivity());
View view = inflater.inflate(R.layout.screen_scanner, container, false);
qrCameraLayout = (LinearLayout) view.findViewById(R.id.ll_qrcamera);
barcodeView = (CompoundBarcodeView) view.findViewById(R.id.barcode_scanner);
tv_qr_print = (TextView) view.findViewById(R.id.tv_qr_print);
barcodeView.decodeContinuous(callback);
/* View view = inflater.inflate(R.layout.fragment_scan, container, false);*/
CustomButton scan = (CustomButton) view.findViewById(R.id.scan_from_fragment);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* scanFromFragment();*/
}
});
return view;
}
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
barcodeView.setStatusText(result.getText());
tv_qr_print.setText(result.getText());
displayToast();
}
//Do something with code result
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
public void scanFromFragment() {
intentIntegrator.setOrientationLocked(true);
intentIntegrator.forSupportFragment(this).initiateScan();
}
private void displayToast() {
if(getActivity() != null && toast != null) {
Toast.makeText(getActivity(), toast, Toast.LENGTH_LONG).show();
toast = null;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
toast = "Cancelled from fragment";
} else {
toast = "Scanned from fragment: " + result.getContents();
}
// At this point we may or may not have a reference to the activity
displayToast();
}
}
#Override
public void onResume() {
barcodeView.resume();
barcodeView.getViewFinder().setVisibility(View.GONE);
super.onResume();
}
#Override
public void onPause() {
barcodeView.pause();
super.onPause();
}
}

How to get facebook profile pic android studio

im unable to retrieve the facebook profile pic:
package com.androidtutorialpoint.flogin.Adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.androidtutorialpoint.flogin.ImageHelper;
import com.androidtutorialpoint.flogin.Model.Post_Song;
import com.androidtutorialpoint.flogin.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by sravya on 19-02-2017.
*/
public class SongPostListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Post_Song> songlist;
public SongPostListAdapter(ArrayList<Post_Song> songlist, int layout, Context context) {
this.songlist = songlist;
this.layout = layout;
this.context = context;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
TextView name,time,title,artist;
LinearLayout song_pic;
}
ImageView profilePicImageView;
#Override
public View getView(int position, View view, ViewGroup parent) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row ==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout,null);
holder.artist = (TextView)row.findViewById(R.id.artist);
holder.name = (TextView)row.findViewById(R.id.user_name);
holder.time = (TextView)row.findViewById(R.id.time);
holder.title = (TextView)row.findViewById(R.id.song_title);
holder.song_pic = (LinearLayout)row.findViewById(R.id.track_pic);
//holder.userImage =(ImageView) row.findViewById(R.id.user_pic);
profilePicImageView = (ImageView) row.findViewById(R.id.profilePicture);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
Post_Song posts = songlist.get(position);
holder.artist.setText(posts.getArtist());
holder.name.setText(posts.getUname());
holder.time.setText(posts.getTime());
holder.title.setText(posts.getTitle());
new LoadProfileImage(profilePicImageView).execute(posts.getUser_pic());
final ViewHolder finalHolder = holder;
Picasso.with(context).load(posts.getArtwork()).placeholder(R.drawable.music_placeholder).into(new Target(){
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
finalHolder.song_pic.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
Log.d("TAG", "FAILED");
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
Log.d("TAG", "Prepare Load");
}
});
return row;
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,90,90, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(context,resized,100,90,90, false, false, false, false));
}
}
}
}
This is my adaptor. Iam not able to get the profile pic here.
This is my Facebook fragment, here there is no problem with getting the profile pic
package com.androidtutorialpoint.flogin;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.content.SharedPreferences;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;
import com.facebook.share.widget.ShareDialog;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class FacebookFragment extends Fragment{
DatabaseHelper myDb;
private LoginButton loginButton;
private Button getLibrary;
private Button getShared;
private boolean postingEnabled = false;
private static final String PERMISSION = "publish_actions";
private final String PENDING_ACTION_BUNDLE_KEY =
"com.example.hellofacebook:PendingAction";
//private Button postStatusUpdateButton;
// private Button postPhotoButton;
private ImageView profilePicImageView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private boolean canPresentShareDialog;
private boolean canPresentShareDialogWithPhotos;
private CallbackManager callbackManager;
private ProfileTracker profileTracker;
private ShareDialog shareDialog;
private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
#Override
public void onCancel() {
Log.d("FacebookFragment", "Canceled");
}
#Override
public void onError(FacebookException error) {
Log.d("FacebookFragment", String.format("Error: %s", error.toString()));
String title = getString(R.string.error);
String alertMessage = error.getMessage();
showResult(title, alertMessage);
}
#Override
public void onSuccess(Sharer.Result result) {
Log.d("FacebookFragment", "Success!");
if (result.getPostId() != null) {
String title = getString(R.string.success);
String id = result.getPostId();
String alertMessage = getString(R.string.successfully_posted_post, id);
showResult(title, alertMessage);
}
}
private void showResult(String title, String alertMessage) {
new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
};
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(getActivity());
FacebookSdk.sdkInitialize(getActivity());
// Other app specific specialization
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_facebook, parent, false);
loginButton = (LoginButton) v.findViewById(R.id.loginButton);
// If using in a fragment
loginButton.setFragment(this);
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast toast = Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_SHORT);
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
toast.show();
handlePendingAction();
updateUI();
}
#Override
public void onCancel() {
// App code
if (pendingAction != PendingAction.NONE) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
#Override
public void onError(FacebookException exception) {
if (pendingAction != PendingAction.NONE
&& exception instanceof FacebookAuthorizationException) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
private void showAlert() {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
}
});
shareDialog = new ShareDialog(this);
shareDialog.registerCallback(
callbackManager,
shareCallback);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
updateUI();
handlePendingAction();
}
};
profilePicImageView = (ImageView) v.findViewById(R.id.profilePicture);
greeting = (TextView) v.findViewById(R.id.greeting);
//postStatusUpdateButton = (Button) v.findViewById(R.id.postStatusUpdateButton);
/*postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});*/
/*postPhotoButton = (Button) v.findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});*/
getLibrary = (Button) v.findViewById(R.id.getLibraryButton);
getShared = (Button)v.findViewById(R.id.getSharedButton);
getShared.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), SongPostList.class));
}
});
getLibrary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
// Can we present the share dialog for regular links?
canPresentShareDialog = ShareDialog.canShow(
ShareLinkContent.class);
// Can we present the share dialog for photos?
canPresentShareDialogWithPhotos = ShareDialog.canShow(
SharePhotoContent.class);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
if(!postingEnabled) {
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
}else{
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
// GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
// new GraphRequest.GraphJSONObjectCallback() {
// #Override
// public void onCompleted(
// JSONObject object,
// GraphResponse response) {
// if (object != null) {
// Log.d("Me Request",object.toString());
// Toast t = Toast.makeText(getActivity(), object.toString(), Toast.LENGTH_SHORT);
// t.show();
// }
//
// }
// });
// Bundle parameters = new Bundle();
// parameters.putString("fields", "id,name,link,email");
// request.setParameters(parameters);
// request.executeAsync();
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "user_friends"));
//
//
//
// }
// });
return v;
}
#Override
public void onResume() {
super.onResume();
// Call the 'activateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onResume methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.activateApp(getActivity());
updateUI();
}
#Override
public void onPause() {
super.onPause();
// Call the 'deactivateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onPause methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.deactivateApp(getActivity());
}
#Override
public void onDestroy() {
super.onDestroy();
profileTracker.stopTracking();
}
private void updateUI() {
boolean enableButtons = AccessToken.getCurrentAccessToken() != null;
//postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
//postPhotoButton.setEnabled(enableButtons || canPresentShareDialogWithPhotos);
Profile profile = Profile.getCurrentProfile();
if (enableButtons && profile != null) {
new LoadProfileImage(profilePicImageView).execute(profile.getProfilePictureUri(200, 200).toString());
greeting.setText(getString(R.string.hello_user, profile.getName()));
boolean isInserted =myDb.insertData(profile.getId(),profile.getName(),profile.getProfilePictureUri(200,200).toString());
if(isInserted == true){
Toast.makeText(getActivity(),"Data Inserted",Toast.LENGTH_LONG).show();
SharedPreferences settings = getActivity().getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("uid", profile.getId());
editor.putString("name",profile.getName());
editor.putString("pic",profile.getProfilePictureUri(200,200).toString());
editor.commit();
}else{
Toast.makeText(getActivity(),"Not Inserted",Toast.LENGTH_LONG).show();
}
postingEnabled = true;
//postPhotoButton.setVisibility(View.VISIBLE);
//postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
} else {
Bitmap icon = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.user_default);
profilePicImageView.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(), icon, 200, 200, 200, false, false, false, false));
greeting.setText(null);
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case NONE:
break;
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}
private void postStatusUpdate() {
Profile profile = Profile.getCurrentProfile();
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Integrate Facebook Login to your Android App")
.setContentDescription(
"This app shows how to integrate Facebook Login to your Android App")
.setContentUrl(Uri.parse("http://www.androidtutorialpoint.com/material-design/adding-facebook-login-to-android-app/"))
.build();
if (canPresentShareDialog) {
shareDialog.show(linkContent);
} else if (profile != null && hasPublishPermission()) {
ShareApi.share(linkContent, shareCallback);
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
}
private void postPhoto() {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.androidlogo);
SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(image).build();
ArrayList<SharePhoto> photos = new ArrayList<>();
photos.add(sharePhoto);
SharePhotoContent sharePhotoContent =
new SharePhotoContent.Builder().setPhotos(photos).build();
if (canPresentShareDialogWithPhotos) {
shareDialog.show(sharePhotoContent);
} else if (hasPublishPermission()) {
ShareApi.share(sharePhotoContent, shareCallback);
} else {
pendingAction = PendingAction.POST_PHOTO;
// We need to get new permissions, then complete the action when we get called back.
LoginManager.getInstance().logInWithPublishPermissions(
this,
Arrays.asList(PERMISSION));
}
}
private boolean hasPublishPermission() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null && accessToken.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action, boolean allowNoToken) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null || allowNoToken) {
pendingAction = action;
handlePendingAction();
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,200,200, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),resized,250,200,200, false, false, false, false));
}
}
}
}
Please help, iam unable to figure out whats wrong
Instead of downloading the image using a custom class extended from AsyncTask you can load it with Picasso.
Uri image = Profile.getCurrentProfile().getProfilePictureUri(200, 200);
Picasso.with(context).load(image).placeholder(R.drawable.placeholder).into(imageView);

How to combine two functions together in Java android

How can i be able to combine these two functions into just one and to be able to perform two actions Invisible and invisible. I dont wanna just get the if statment from buttonInVisible method and just put in in the buttonVisible one.
Here is the code
MainActivity
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
private WebViewFragment mWebViewFragment;
public TextView textView;
public Button buttons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons = (Button) findViewById(R.id.button);
buttons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
textView = (TextView) findViewById(R.id.textViewId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mWebViewFragment = new WebViewFragment();
fragmentTransaction.replace(R.id.mainFragment, mWebViewFragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
if(mWebViewFragment != null && mWebViewFragment.canGoBack()) {
mWebViewFragment.goBack();
} else {
super.onBackPressed();
}
}
public void setTitle(String title) {
if(textView != null){
textView.setText(title);
}
}
public void buttonVisible(int visibility) {
if(buttons != null){
buttons.setVisibility(visibility);
}
}
#Override
protected void onStart() {
super.onStart();
setVisible(true);
}
}
Fragment
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment extends Fragment {
private WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
mWebView = (WebView) view.findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("https://www.google.co.uk/");
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.v("WebView has started", url);
}
#Override
public void onPageFinished(WebView view, String url) {
String title = mWebView.getTitle();
Log.v(getClass().getName(), "Title=" + title);
/**if(mWebView.canGoBack()) {
buttonVisible();
} else {
buttonInVisible();
}**/
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
setTitle(title);
Log.v(getClass().getName(), "Received Title" + title);
}
});
return view;
}
public boolean canGoBack() {
return mWebView.canGoBack();
}
public void goBack() {
mWebView.goBack();
}
public void setTitle(String title) {
if (title != null && title.length() > 0) {
Activity activity = getActivity();
if(activity != null && activity instanceof MainActivity){
((MainActivity) activity).setTitle(title);
}
}
}
public void SetVibility() {
Activity activity = getActivity();
if(activity != null && activity instanceof MainActivity) {
((MainActivity) activity).buttonVisible(View.VISIBLE);
}
}
public void buttonInVisible() {
Activity activity = getActivity();
if(activity != null && activity instanceof MainActivity){
((MainActivity) activity).buttonVisible(View.INVISIBLE);
}
}
}
public void changeButtonVisibilityState() {
button.setVisibility(button.getVisibility() == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
}
Since the method
public void buttonVisible(int visibility) {
if(buttons != null){
buttons.setVisibility(visibility);
}
}
Is public on the MainActivity (which contains the fragment), you can simply invoke on your fragment when you want the following :
((MainActivity) getActivity).buttonVisible(View.VISIBLE)
This will call the MainActivity and change the visibility of the button on it

Cant import facebook Session class in android in android studio

I am newbie to android and working on a demo for getting facebook profilel info after login,I have successfully implemented login and want to fetch profile info,i got the code,But while adding profile info it's fail to import necessary classes(Session),can anybudy help me for this.
java
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.Session;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
.
.
.
.
.
private Session openActiveSession(Activity activity, boolean allowLoginUI,
StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
OpenRequest openRequest = new OpenRequest(activity).
setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
SSO_WITH_FALLBACK).setCallback(callback).
setDefaultAudience(SessionDefaultAudience.FRIENDS);
Session session = Session.getActiveSession();
Log.d(LOG_TAG, "" + session);
if (session == null) {
Log.d(LOG_TAG, "" + savedInstanceState);
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
session.openForRead(openRequest);
return session;
}
}
return null;
}
This is the working code for FACEBOOK INTEGRATION:
1) Create one xml: fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivityFragment">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_centerHorizontal="true"/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
2) Java Class i.e. MainFragment.java
package example.com.facebook_integration;
/**
* Created by dinesh sharma on 2/22/2016.
*/
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
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.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import net.simplifiedcoding.androidlogin.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
/**
* A placeholder fragment containing a simple view.
*/
public class MainFragment extends Fragment {
private CallbackManager callbackManager;
private TextView textView;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainFragment() {
}
#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();
}
#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);
final ImageView imageView=(ImageView)view.findViewById(R.id.myImage);
textView = (TextView) view.findViewById(R.id.textView);
//loginButton.setReadPermissions("user_likes");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday","user_likes","user_friends"));
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(final JSONObject object, GraphResponse response)
{
Log.v("LoginActivity", response.toString());
try
{
// Application code
System.out.println("JSONRESPOMSEEE "+response.toString());
String email = object.getString("email");
String birthday = object.getString("birthday"); // 01/31/1980 format
String name = object.getString("name");
Profile profile = Profile.getCurrentProfile();
Uri uri=(Uri)profile.getProfilePictureUri(200,200);
System.out.println("Email "+email+" Birthday "+birthday+name);
System.out.println("Email " + uri);
final ArrayList arrayList=new ArrayList();
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/likes",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
JSONObject json = new JSONObject(response.getRawResponse());
JSONArray jarray = json.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject likes = jarray.getJSONObject(i);
String likeId = likes.getString("id");
String likeName = likes.getString("name");
String likeCreatedTime = likes.getString("created_time");
arrayList.add("Page Name "+likeName+" Time= "+likeCreatedTime+" ID= "+likeId);
System.out.println("My Name " + likeName + " " + likeCreatedTime);
}
System.out.println("ArrayList mine "+arrayList);
System.out.println("ArrayList mine size "+arrayList.size());
}
catch(Exception e)
{
System.out.println("My Exception "+e);
}
}
}
).executeAsync();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void displayMessage(Profile profile) {
if(profile != null){
textView.setText(profile.getName());
}
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume()
{
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
}
3) Create one more xml: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:id="#+id/fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="example.com.facebook_integration.MainFragment"
></fragment>
</RelativeLayout>
4) Create your MainActivity.java
package example.com.facebook_integration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import net.simplifiedcoding.androidlogin.R;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
See this link https://www.simplifiedcoding.net/login-with-facebook-android-studio-using-facebook-sdk-4/
But i have done all the important changes in my code you can use this code after following all the steps from above link.

How to post to Facebook wall from my android App?

I have integrated Facebook with my app.But my requirement is after giving Facebook account access permission my app should autopost some text,images,links like below
to my facebook wall and then redirect to another activity (For example- SecondAcitivity)
FacebookActivity.java
package facebookIntegration;
import com.pcs.sliderringtineproj.R;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
public class FacebookActivity extends FragmentActivity {
private MainFragment mainFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainFragment.java
package facebookIntegration;
import java.util.Arrays;
import com.facebook.SessionState;
import com.facebook.Session;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.pcs.sliderringtineproj.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback=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) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_facebook, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
if(Session.getActiveSession().isOpened()){
Toast.makeText(getActivity(), "logged in to FB", 1).show();
}else{
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("public_profile"));
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
Bundle params = new Bundle();
params.putString("message", message);
String uri = "/me/feed?message=" + message + "" + "&access_token=" + session.getAccessToken();
uri = uri.replace(" ", "%20");
new Request(
session,
uri,
params,
HttpMethod.POST,
new Request.Callback() {
public void onCompleted(Response response) {
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
}
}
).executeAsync();

Categories

Resources