My face book app is not worrking when nativefacebook app installed - java

package com.facebook.samples.hellofacebook;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.*;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphPlace;
import com.facebook.model.GraphUser;
import com.facebook.widget.*;
import java.util.*;
public class HelloFacebookSampleActivity extends FragmentActivity {
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final Location SEATTLE_LOCATION = new Location("") {
{
setLatitude(47.6097);
setLongitude(-122.3331);
}
};
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
private Button postStatusUpdateButton;
private Button postPhotoButton;
private Button pickFriendsButton;
private Button pickPlaceButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private ViewGroup controlsContainer;
private GraphUser user;
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.mainfb);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email", "user_birthday"));
loginButton.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
HelloFacebookSampleActivity.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to be populated in order to post a
// status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});
postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});
pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
});
pickPlaceButton = (Button) findViewById(R.id.pickPlaceButton);
pickPlaceButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickPlace();
}
});
controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);
final FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment != null) {
// If we're being re-created and have a fragment, we need to a) hide the main UI controls and
// b) hook up its listeners again.
controlsContainer.setVisibility(View.GONE);
if (fragment instanceof FriendPickerFragment) {
setFriendPickerListeners((FriendPickerFragment) fragment);
} else if (fragment instanceof PlacePickerFragment) {
setPlacePickerListeners((PlacePickerFragment) fragment);
}
}
// Listen for changes in the back stack so we know if a fragment got popped off because the user
// clicked the back button.
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (fm.getBackStackEntryCount() == 0) {
// We need to re-show our UI.
controlsContainer.setVisibility(View.VISIBLE);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
updateUI();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
protected 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();
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (pendingAction != PendingAction.NONE &&
(exception instanceof FacebookOperationCanceledException ||
exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(HelloFacebookSampleActivity.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI() {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons);
postPhotoButton.setEnabled(enableButtons);
pickFriendsButton.setEnabled(enableButtons);
pickPlaceButton.setEnabled(enableButtons);
if (enableButtons && user != null) {
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
#SuppressWarnings("incomplete-switch")
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 POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post, message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE);
}
private void postStatusUpdate() {
if (user != null && hasPublishPermission()) {
final String message = getString(R.string.status_update, user.getFirstName(), (new Date().toString()));
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO);
}
private void postPhoto() {
if (hasPublishPermission()) {
Bitmap image = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
private void showPickerFragment(PickerFragment<?> fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment, FacebookException error) {
String text = getString(R.string.exception, error.getMessage());
Toast toast = Toast.makeText(HelloFacebookSampleActivity.this, text, Toast.LENGTH_SHORT);
toast.show();
}
});
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
controlsContainer.setVisibility(View.GONE);
// We want the fragment fully created so we can use it immediately.
fm.executePendingTransactions();
fragment.loadData(false);
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void setFriendPickerListeners(final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
Collection<GraphUser> selection = fragment.getSelection();
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
showAlert(getString(R.string.you_picked), results);
}
private void onPlacePickerDone(PlacePickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String result = "";
GraphPlace selection = fragment.getSelection();
if (selection != null) {
result = selection.getName();
} else {
result = getString(R.string.no_place_selected);
}
showAlert(getString(R.string.you_picked), result);
}
private void onClickPickPlace() {
final PlacePickerFragment fragment = new PlacePickerFragment();
fragment.setLocation(SEATTLE_LOCATION);
fragment.setTitleText(getString(R.string.pick_seattle_place));
setPlacePickerListeners(fragment);
showPickerFragment(fragment);
}
private void setPlacePickerListeners(final PlacePickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new PlacePickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> pickerFragment) {
onPlacePickerDone(fragment);
}
});
fragment.setOnSelectionChangedListener(new PlacePickerFragment.OnSelectionChangedListener() {
#Override
public void onSelectionChanged(PickerFragment<?> pickerFragment) {
if (fragment.getSelection() != null) {
onPlacePickerDone(fragment);
}
}
});
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null)
.show();
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
} else {
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
}
}
}
}
whenever i click login button it shows pop window that this app willl access your facebook details
after clicking ok buttton is shows like as previous
this is my code please help me someone
and i am new to android
if anybody having any suggestion please send mail to maruthu2j#gmail.com

Related

How to allow multiple windows on webview to get facebook login working?

I'm creating an app for my website and need to when you click on external links like facebook and google login you get a new window tab that closes after login.
I`ve added mWebView.getSettings().setSupportMultipleWindows(true); but now when I click on the link nothing happens
MainFragment.java
public class MainFragment extends TaskFragment implements SwipeRefreshLayout.OnRefreshListener, AdvancedWebView.Listener {
private static final String ARGUMENT_URL = "url";
private static final String ARGUMENT_SHARE = "share";
private static final int REQUEST_FILE_PICKER = 1;
private boolean mProgress = false;
private View mRootView;
private StatefulLayout mStatefulLayout;
private AdvancedWebView mWebView;
private String mUrl = "about:blank";
private String mShare;
private boolean mLocal = false;
private ValueCallback<Uri> mFilePathCallback4;
private ValueCallback<Uri[]> mFilePathCallback5;
private int mStoredActivityRequestCode;
private int mStoredActivityResultCode;
private Intent mStoredActivityResultIntent;
public static MainFragment newInstance(String url, String share) {
MainFragment fragment = new MainFragment();
// arguments
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_URL, url);
arguments.putString(ARGUMENT_SHARE, share);
fragment.setArguments(arguments);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
// handle fragment arguments
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.DISABLED ? R.layout.fragment_main : R.layout.fragment_main_swipeable;
mRootView = inflater.inflate(layout, container, false);
mWebView = mRootView.findViewById(R.id.main_webview);
return mRootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// restore webview state
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
// setup webview
setupView();
// pull to refresh
setupSwipeRefreshLayout();
// setup stateful layout
setupStatefulLayout(savedInstanceState);
// load data
if (mStatefulLayout.getState() == StatefulLayout.EMPTY) loadData();
// progress popup
showProgress(mProgress);
// check permissions
if (WebViewAppConfig.GEOLOCATION) {
PermissionUtility.checkPermissionAccessLocation(this);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mWebView.onResume();
}
#Override
public void onPause() {
super.onPause();
mWebView.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mRootView = null;
}
#Override
public void onDestroy() {
super.onDestroy();
mWebView.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(this)) {
// permitted
mWebView.onActivityResult(requestCode, resultCode, intent);
} else {
// not permitted
mStoredActivityRequestCode = requestCode;
mStoredActivityResultCode = resultCode;
mStoredActivityResultIntent = intent;
}
//handleFilePickerActivityResult(requestCode, resultCode, intent); // not used, used advanced webview instead
}
#Override
public void onSaveInstanceState(Bundle outState) {
// save current instance state
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
// stateful layout state
if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState);
// save webview state
mWebView.saveState(outState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// action bar menu
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_main, menu);
// show or hide share button
MenuItem share = menu.findItem(R.id.menu_main_share);
share.setVisible(mShare != null && !mShare.trim().equals(""));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// action bar menu behavior
switch (item.getItemId()) {
case R.id.menu_main_share:
IntentUtility.startShareActivity(getContext(), getString(R.string.app_name), getShareText(mShare));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA:
case PermissionUtility.REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE:
case PermissionUtility.REQUEST_PERMISSION_ACCESS_LOCATION: {
// if request is cancelled, the result arrays are empty
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// permission granted
if (requestCode == PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA) {
// continue with activity result handling
if (mStoredActivityResultIntent != null) {
mWebView.onActivityResult(mStoredActivityRequestCode, mStoredActivityResultCode, mStoredActivityResultIntent);
mStoredActivityRequestCode = 0;
mStoredActivityResultCode = 0;
mStoredActivityResultIntent = null;
}
}
} else {
// permission denied
}
}
} else {
// all permissions denied
}
break;
}
}
}
#Override
public void onRefresh() {
runTaskCallback(new Runnable() {
#Override
public void run() {
refreshData();
}
});
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
Logcat.d("");
}
#Override
public void onPageFinished(String url) {
Logcat.d("");
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
Logcat.d("");
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
Logcat.d("");
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
}
}
#Override
public void onExternalPageRequest(String url) {
Logcat.d("");
}
public void refreshData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress popup
showProgress(true);
// load web url
String url = mWebView.getUrl();
if (url == null || url.equals("")) url = mUrl;
mWebView.loadUrl(url);
} else {
showProgress(false);
Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show();
}
}
private void handleArguments(Bundle arguments) {
if (arguments.containsKey(ARGUMENT_URL)) {
mUrl = arguments.getString(ARGUMENT_URL);
mLocal = mUrl.contains("file://");
}
if (arguments.containsKey(ARGUMENT_SHARE)) {
mShare = arguments.getString(ARGUMENT_SHARE);
}
}
// not used, used advanced webview instead
private void handleFilePickerActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_FILE_PICKER) {
if (mFilePathCallback4 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback4.onReceiveValue(uri);
} else {
mFilePathCallback4.onReceiveValue(null);
}
}
if (mFilePathCallback5 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback5.onReceiveValue(new Uri[]{uri});
} else {
mFilePathCallback5.onReceiveValue(null);
}
}
mFilePathCallback4 = null;
mFilePathCallback5 = null;
}
}
private void loadData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress
if (WebViewAppConfig.PROGRESS_PLACEHOLDER) {
mStatefulLayout.showProgress();
} else {
mStatefulLayout.showContent();
}
// load web url
mWebView.loadUrl(mUrl);
} else {
mStatefulLayout.showOffline();
}
}
private void showProgress(boolean visible) {
// show pull to refresh progress bar
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (contentSwipeRefreshLayout != null) contentSwipeRefreshLayout.setRefreshing(visible);
if (offlineSwipeRefreshLayout != null) offlineSwipeRefreshLayout.setRefreshing(visible);
if (emptySwipeRefreshLayout != null) emptySwipeRefreshLayout.setRefreshing(visible);
mProgress = visible;
}
private void showContent(final long delay) {
final Handler timerHandler = new Handler();
final Runnable timerRunnable = new Runnable() {
#Override
public void run() {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mRootView != null) {
Logcat.d("timer");
mStatefulLayout.showContent();
}
}
});
}
};
timerHandler.postDelayed(timerRunnable, delay);
}
private void setupView() {
// webview settings
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath());
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
// user agent
if (WebViewAppConfig.WEBVIEW_USER_AGENT != null && !WebViewAppConfig.WEBVIEW_USER_AGENT.equals("")) {
mWebView.getSettings().setUserAgentString(WebViewAppConfig.WEBVIEW_USER_AGENT);
}
// advanced webview settings
mWebView.setListener(getActivity(), this);
mWebView.setGeolocationEnabled(true);
// webview style
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // fixes scrollbar on Froyo
// webview hardware acceleration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// webview chrome client
View nonVideoLayout = getActivity().findViewById(R.id.main_non_video_layout);
ViewGroup videoLayout = getActivity().findViewById(R.id.main_video_layout);
View progressView = getActivity().getLayoutInflater().inflate(R.layout.placeholder_progress, null);
VideoEnabledWebChromeClient webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, progressView, (VideoEnabledWebView) mWebView);
webChromeClient.setOnToggledFullscreen(new MyToggledFullscreenCallback());
mWebView.setWebChromeClient(webChromeClient);
//mWebView.setWebChromeClient(new MyWebChromeClient()); // not used, used advanced webview instead
// webview client
mWebView.setWebViewClient(new MyWebViewClient());
// webview key listener
mWebView.setOnKeyListener(new WebViewOnKeyListener((DrawerStateListener) getActivity()));
// webview touch listener
mWebView.requestFocus(View.FOCUS_DOWN); // http://android24hours.blogspot.cz/2011/12/android-soft-keyboard-not-showing-on.html
mWebView.setOnTouchListener(new WebViewOnTouchListener());
// webview scroll listener
//((RoboWebView) mWebView).setOnScrollListener(new WebViewOnScrollListener()); // not used
// admob
setupBannerView();
}
private void setupBannerView() {
if (WebViewAppConfig.ADMOB_UNIT_ID_BANNER != null && !WebViewAppConfig.ADMOB_UNIT_ID_BANNER.equals("") && NetworkUtility.isOnline(getActivity())) {
ViewGroup contentLayout = mRootView.findViewById(R.id.container_content);
AdMobUtility.createAdView(getActivity(), WebViewAppConfig.ADMOB_UNIT_ID_BANNER, AdSize.BANNER, contentLayout);
}
}
private void controlBack() {
if (mWebView.canGoBack()) mWebView.goBack();
}
private void controlForward() {
if (mWebView.canGoForward()) mWebView.goForward();
}
private void controlStop() {
mWebView.stopLoading();
}
private void controlReload() {
mWebView.reload();
}
private void setupStatefulLayout(Bundle savedInstanceState) {
// reference
mStatefulLayout = (StatefulLayout) mRootView;
// state change listener
mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() {
#Override
public void onStateChange(View view, #StatefulLayout.State int state) {
Logcat.d(String.valueOf(state));
// do nothing
}
});
// restore state
mStatefulLayout.restoreInstanceState(savedInstanceState);
}
private void setupSwipeRefreshLayout() {
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.ENABLED) {
contentSwipeRefreshLayout.setOnRefreshListener(this);
offlineSwipeRefreshLayout.setOnRefreshListener(this);
emptySwipeRefreshLayout.setOnRefreshListener(this);
} else if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.PROGRESS) {
contentSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
offlineSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
emptySwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
}
}
private String getShareText(String text) {
if (mWebView != null) {
if (mWebView.getTitle() != null) {
text = text.replaceAll("\\{TITLE\\}", mWebView.getTitle());
}
if (mWebView.getUrl() != null) {
text = text.replaceAll("\\{URL\\}", mWebView.getUrl());
}
}
return text;
}
private boolean isLinkExternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_EXTERNAL_BROWSER) {
if (url.contains(rule)) return true;
}
return false;
}
private boolean isLinkInternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_INTERNAL_WEBVIEW) {
if (url.contains(rule)) return true;
}
return false;
}
// not used, used advanced webview instead
private class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback5 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
return true;
}
return false;
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
public void openFileChooser(ValueCallback<Uri> filePathCallback) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
}
private class MyToggledFullscreenCallback implements VideoEnabledWebChromeClient.ToggledFullscreenCallback {
#Override
public void toggledFullscreen(boolean fullscreen) {
if (fullscreen) {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
} else {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
}
private class MyWebViewClient extends WebViewClient {
private boolean mSuccess = true;
#Override
public void onPageFinished(final WebView view, final String url) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mSuccess) {
showContent(500); // hide progress bar with delay to show webview content smoothly
showProgress(false);
if (WebViewAppConfig.ACTION_BAR_HTML_TITLE) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(view.getTitle());
}
CookieSyncManager.getInstance().sync(); // save cookies
}
mSuccess = true;
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null) {
mSuccess = false;
mStatefulLayout.showEmpty();
showProgress(false);
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
// forward to deprecated method
onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (DownloadFileUtility.isDownloadableFile(url)) {
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
return true;
}
return true;
} else if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
// determine for opening the link externally or internally
boolean external = isLinkExternal(url);
boolean internal = isLinkInternal(url);
if (!external && !internal) {
external = WebViewAppConfig.OPEN_LINKS_IN_EXTERNAL_BROWSER;
}
// open the link
if (external) {
IntentUtility.startWebActivity(getContext(), url);
return true;
} else {
showProgress(true);
return false;
}
} else if (url != null && url.startsWith("file://")) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
return false;
} else {
return IntentUtility.startIntentActivity(getContext(), url);
}
}
}
}

How to fix ExoPlayer video Freeze 2.9.6

I use this code to play the full-screen video but I have a problem when it is video playing and moving from the main activity to the full-screen activity occurs freezing of the video for 2-3 seconds This problem occurs only with the releases after 2.8.3 only but with 2.8.0 works Video is smooth
code full: https://github.com/MATPOCKIH/ExoPlayerFullscreen
PlayerViewManager
public class PlayerViewManager {
private static final String TAG = "ExoPlayerViewManager";
public static final String EXTRA_VIDEO_URI = "video_uri";
private static Map<String, PlayerViewManager> instances = new HashMap<>();
private Uri videoUri;
public boolean isPlayerPlaying;
private boolean isMustPlaying;
private UniversalPlayerView universalPlayer;
public static PlayerViewManager getInstance(String videoUri) {
PlayerViewManager instance = instances.get(videoUri);
if (instance == null) {
instance = new PlayerViewManager(videoUri);
instances.put(videoUri, instance);
}
return instance;
}
private PlayerViewManager(String videoUri) {
this.videoUri = Uri.parse(videoUri);
}
public void preparePlayer(PlayerHolderView playerHolderView) {
if (playerHolderView == null) {
return;
}
if (universalPlayer == null) {
universalPlayer = createPlayer(playerHolderView.getContext());
isPlayerPlaying = true;
isMustPlaying = true;
}
universalPlayer.initialize(videoUri, playerHolderView);
}
public void releaseVideoPlayer() {
if (universalPlayer != null) {
universalPlayer.release();
}
universalPlayer = null;
}
public void goToBackground() {
if (universalPlayer != null /*&& !isMustPlaying*/) {
//isPlayerPlaying = player.getPlayWhenReady();
universalPlayer.pause();
}
}
public void goToForeground() {
if (universalPlayer != null && isMustPlaying) {
universalPlayer.play();
}
}
public void pausePlayer(){
if (universalPlayer != null) {
universalPlayer.pause();
isPlayerPlaying = false;
isMustPlaying = false;
}
}
public void playPlayer(){
if (universalPlayer != null) {
universalPlayer.play();
isPlayerPlaying = true;
isMustPlaying = true;
}
}
private UniversalPlayerView createPlayer(Context context){
if (videoUri.getScheme().startsWith("http")){
return new FaceterExoPlayerView(context);
}
return new FaceterExoPlayerView(context);
}
}
FaceterExoPlayerView
public class FaceterExoPlayerView extends UniversalPlayerView {
private Uri videoUri;
private DefaultDataSourceFactory dataSourceFactory;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private Context context;
public FaceterExoPlayerView(Context context) {
this.context = context;
}
#Override
public void initialize(Uri videoUri, PlayerHolderView playerHolderView) {
if (playerHolderView == null || videoUri == null)
return;
exoPlayerView = playerHolderView.findViewById(R.id.exo_player);
if (player == null) {
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "faceter"));
MediaSource videoSource = buildMediaSource(videoUri, null);
player.prepare(videoSource);
}
player.clearVideoSurface();
player.setVideoTextureView((TextureView) exoPlayerView.getVideoSurfaceView());
exoPlayerView.setPlayer(player);
exoPlayerView.hideController();
setResizeModeFill(playerHolderView.isResizeModeFill());
}
#Override
public void play() {
player.setPlayWhenReady(true);
}
#Override
public void pause() {
player.setPlayWhenReady(false);
}
#SuppressWarnings("unchecked")
private MediaSource buildMediaSource(Uri uri, #Nullable String overrideExtension) {
int type = Util.inferContentType(uri, overrideExtension);
switch (type) {
/*case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new DashManifestParser(), (List<RepresentationKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new SsManifestParser(), (List<StreamKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);*/
case C.TYPE_HLS:
return new HlsMediaSource.Factory(dataSourceFactory)
/*.setPlaylistParser(
new FilteringManifestParser<>(
new HlsPlaylistParser(), (List<RenditionKey>) getOfflineStreamKeys(uri)))*/
.createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
#Override
public void release() {
if (player != null) {
player.release();
}
player = null;
}
#Override
public void setResizeModeFill(boolean isResizeModeFill) {
if (isResizeModeFill) {
exoPlayerView.setResizeMode(RESIZE_MODE_FILL);
} else {
exoPlayerView.setResizeMode(RESIZE_MODE_FIT);
}
}
}
PlayerHolderView.java
public class PlayerHolderView extends FrameLayout {
private String videoUrl;
private boolean isResizeModeFill = true;
private OnUserInteractionListener onUserInteractionListener;
public PlayerHolderView(#NonNull Context context) {
super(context);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.layout_player, this, true);
View controlView = this.findViewById(R.id.exo_controller);
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).pausePlayer();
}
});
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FullscreenVideoActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
getContext().startActivity(intent);
}
});
MainActivity
public class MainActivity extends AppCompatActivity {
private List<PlayerHolderView> playerHolders = new ArrayList<>();
private List<TextView> links = new ArrayList<>();
private List<String> mVideoUrls = new ArrayList<>(
Arrays.asList(
//"http://10.110.3.30/api/Playlists/6a3ecad7-e744-446f-9341-0e0ba834de63?from=2018-09-20&to=2018-09-21"
"https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/TearsOfSteel.m3u8",
"http://redirector.c.youtube.com/videoplayback?id=604ed5ce52eda7ee&itag=22&source=youtube&sparams=ip,ipbits,expire,source,id&ip=0.0.0.0&ipbits=0&expire=19000000000&signature=513F28C7FDCBEC60A66C86C9A393556C99DC47FB.04C88036EEE12565A1ED864A875A58F15D8B5300&key=ik0",
"https://html5demos.com/assets/dizzy.mp4"
//"https://cdn.faceter.io/hls/ab196789-8876-4854-82f3-087e5682d013",
//"https://cdn.faceter.io/hls/65d1c673-6a63-44c8-836b-132449c9462a"
)
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerHolders.add((PlayerHolderView) findViewById(R.id.holder1));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder2));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder3));
links.add((TextView) findViewById(R.id.title1));
links.add((TextView) findViewById(R.id.title2));
links.add((TextView) findViewById(R.id.title3));
}
#Override
public void onResume() {
super.onResume();
int i = 0;
for (final String videoUrl : mVideoUrls) {
playerHolders.get(i).setupPlayerView(videoUrl);
playerHolders.get(i).setOnUserInteractionListener(this);
links.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVideoTitleClicked(videoUrl);
}
});
i++;
}
}
#Override
public void onPause() {
super.onPause();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).goToBackground();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).releaseVideoPlayer();
}
}
public void onVideoTitleClicked(String videoUrl) {
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
startActivity(intent);
}
}
FullscreenVideoActivity
public class FullscreenVideoActivity extends AppCompatActivity {
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of
// API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
private String mVideoUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_video);
mContentView = findViewById(R.id.enclosing_layout);
PlayerHolderView playerHolderView = findViewById(R.id.player_holder);
playerHolderView.setResizeModeFill(false);
mVideoUri = getIntent().getStringExtra(PlayerViewManager.EXTRA_VIDEO_URI);
PlayerViewManager.getInstance(mVideoUri).preparePlayer(playerHolderView);
/*
// Set the fullscreen button to "close fullscreen" icon
View controlView = playerView.findViewById(R.id.exo_controller);
ImageView fullscreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
fullscreenIcon.setImageResource(R.drawable.exo_controls_fullscreen_exit);
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).pausePlayer();
}
});*/
}
#Override
public void onResume() {
super.onResume();
PlayerViewManager.getInstance(mVideoUri).goToForeground();
}
#Override
public void onPause() {
super.onPause();
PlayerViewManager.getInstance(mVideoUri).goToBackground();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide();
}
private void hide() {
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide() {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, 100);
}
}
Just try out this code for video freeze problem:
#Override
public void play() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
public void pause() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
Here player.getPlaybackState(); is help full to get it to back state.

Unable to start activity ComponentInfo : Attempt to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
NullPointerException addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
(8 answers)
Closed 4 years ago.
This is a barcode scanning app. It crashes when I scanned the code. If anyone knows how to fix help me out.
It crashes after I scanned the code from the ScanActivity.java and pass the object to the TicketResultActivity.javato display the result.
error
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.movietickets/info.androidhive.movietickets.TicketResultActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void info.androidhive.movietickets.MyApplication.addToRequestQueue(com.android.volley.Request)' on a null object reference
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// making toolbar transparent
transparentToolbar();
setContentView(R.layout.activity_main);
findViewById(R.id.btn_scan).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, ScanActivity.class));
}
});
}
private void transparentToolbar() {
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
private void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
ScanActivity.java
public class ScanActivity extends AppCompatActivity implements BarcodeReader.BarcodeReaderListener{
BarcodeReader barcodeReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
// get the barcode reader instance
barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_scanner);
}
#Override
public void onScanned(Barcode barcode) {
// playing barcode reader beep sound
barcodeReader.playBeep();
// ticket details activity by passing barcode
Intent intent = new Intent(ScanActivity.this, TicketResultActivity.class);
intent.putExtra("code", barcode.displayValue);
startActivity(intent);
}
#Override
public void onScannedMultiple(List<Barcode> list) {
}
#Override
public void onBitmapScanned(SparseArray<Barcode> sparseArray) {
}
/*#Override
public void onCameraPermissionDenied() {
finish();
}*/
#Override
public void onScanError(String s) {
Toast.makeText(getApplicationContext(), "Error occurred while scanning " + s, Toast.LENGTH_SHORT).show();
}
}
TicketResultActivity.java
public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();
// url to search barcode
private static final String URL = "https://api.androidhive.info/barcodes/search.php?code=";
private TextView txtName, txtDuration, txtDirector, txtGenre, txtRating, txtPrice, txtError;
private ImageView imgPoster;
private Button btnBuy;
private ProgressBar progressBar;
private TicketView ticketView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtName = findViewById(R.id.name);
txtDirector = findViewById(R.id.director);
txtDuration = findViewById(R.id.duration);
txtPrice = findViewById(R.id.price);
txtRating = findViewById(R.id.rating);
imgPoster = findViewById(R.id.poster);
txtGenre = findViewById(R.id.genre);
btnBuy = findViewById(R.id.btn_buy);
imgPoster = findViewById(R.id.poster);
txtError = findViewById(R.id.txt_error);
ticketView = findViewById(R.id.layout_ticket);
progressBar = findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
// close the activity in case of empty barcode
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
// search the barcode
searchBarcode(barcode);
}
/**
* Searches the barcode by making HTTP call
* Request was made using Volley network library but the library is
* not suggested in production, consider using Retrofit
*/
private void searchBarcode(String barcode) {
// making volley's json request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL + barcode, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Ticket response: " + response.toString());
// check for success status
if (!response.has("error")) {
// received movie response
renderMovie(response);
} else {
// no movie found
showNoTicket();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
showNoTicket();
}
});
MyApplication.getInstance().addToRequestQueue(jsonObjReq);
}
private void showNoTicket() {
txtError.setVisibility(View.VISIBLE);
ticketView.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
/**
* Rendering movie details on the ticket
*/
private void renderMovie(JSONObject response) {
try {
// converting json to movie object
Movie movie = new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
txtName.setText(movie.getName());
txtDirector.setText(movie.getDirector());
txtDuration.setText(movie.getDuration());
txtGenre.setText(movie.getGenre());
txtRating.setText("" + movie.getRating());
txtPrice.setText(movie.getPrice());
Glide.with(this).load(movie.getPoster()).into(imgPoster);
if (movie.isReleased()) {
btnBuy.setText(getString(R.string.btn_buy_now));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
btnBuy.setText(getString(R.string.btn_coming_soon));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.btn_disabled));
}
ticketView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
} else {
// movie not found
showNoTicket();
}
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// exception
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private class Movie {
String name;
String director;
String poster;
String duration;
String genre;
String price;
float rating;
#SerializedName("released")
boolean isReleased;
public String getName() {
return name;
}
public String getDirector() {
return director;
}
public String getPoster() {
return poster;
}
public String getDuration() {
return duration;
}
public String getGenre() {
return genre;
}
public String getPrice() {
return price;
}
public float getRating() {
return rating;
}
public boolean isReleased() {
return isReleased;
}
}
}
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
To initialize MyApplication properly you have to add the following in the AndroidManifest.xml
<application android:name="com.package.subpackage.MyApplication">
...
</application>

(Android) Starting up a fragment is blocking LocationListener

So when I comment out past the facebook code comment, the Location manager does work and onLocationChanged does update the proper Latitude and Longitude. However, when I uncomment it, the Facebook functionality works but the onLocationChanged never gets called for some reason.
MainActivity.java
public class MainActivity extends FragmentActivity implements OnClickListener {
private MainFragment mainFragment;
Button sendIPbutton; //Button for sending IP Address
EditText mEdit; //Get info from what user enters in form
//TextView mText;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/*/
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
/**************************Facebook code********************************************/
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);
}
/*********************************************************************************/
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude();
// Toast.makeText( getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
coordinates = (TextView)findViewById(R.id.coordinates);
coordinates.setText(Text);
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}/* End of Class MyLocationListener */
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
public void setObject(View view){
Intent intent = new Intent(this, SetObjectActivity.class);
startActivity(intent);
}
I think there must be something going on in the oncreate function.
Here is my MainFragment.java code. Note that it's primarily from the Facebook Login and Sharing tutorial on their website.
public class MainFragment extends Fragment {
private Button shareButton;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private static final String TAG = MainFragment.class.getSimpleName();
private TextView coordinates;
private UiLifecycleHelper uiHelper;
private final List<String> permissions;
public MainFragment() {
permissions = Arrays.asList("user_status");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
shareButton = (Button) view.findViewById(R.id.shareButton);
coordinates = (TextView) view.findViewById(R.id.coordinates);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(permissions);
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
return view;
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
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);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
shareButton.setVisibility(View.INVISIBLE);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
String text = coordinates.getText().toString();
Bundle postParams = new Bundle();
postParams.putString("name", "My Location!");
postParams.putString("caption", "Thanks to Hot and Cold");
postParams.putString("description", text);
postParams.putString("link", null);
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
}
So apparently I was spot on about the Fragment causing the issue. to Resolve it, I just added Context to the fragment class, i imported all of the Location logic into MainFragment, and now it works!

Android - Facebook SDK login -> logout -> login not working

I have an Android application (very simple one, just starting to learn the basics). I've implemented Facebook login, which is almost working perfectly. Starting the app first time everything works just fine: pressing the login button, asking for permissions, logging in, then the app shows the authenticated page for the user. When pressing the logout button it shows me the login page again, so that works too. Now when I try to log in again it doesn't work. It opens the facebook stuff again for some seconds then it just goes back to the login page like nothing have happened. If I remove the permissions on facebook for the app and try log in again it works again. So for some reason I can't log in when I already have the permission I guess...
Here is the code:
package com.just.simply.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
public class MyActivity extends FragmentActivity {
private static final int SPLASH = 0;
private static final int SELECTION = 1;
private static final int SETTINGS = 2;
private static final int FRAGMENT_COUNT = SETTINGS + 1;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
private boolean isResumed = false;
private MenuItem settings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
FragmentManager fm = getSupportFragmentManager();
fragments[SPLASH] = fm.findFragmentById(R.id.splashFragment);
fragments[SELECTION] = fm.findFragmentById(R.id.selectionFragment);
fragments[SETTINGS] = fm.findFragmentById(R.id.userSettingsFragment);
FragmentTransaction transaction = fm.beginTransaction();
for(int i = 0; i < fragments.length; i++) {
transaction.hide(fragments[i]);
}
transaction.commit();
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
isResumed = true;
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
isResumed = false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
// Only make changes if the activity is visible
if (isResumed) {
FragmentManager manager = getSupportFragmentManager();
// Get the number of entries in the back stack
int backStackSize = manager.getBackStackEntryCount();
// Clear the back stack
for (int i = 0; i < backStackSize; i++) {
manager.popBackStack();
}
if (state.isOpened()) {
// If the session state is open:
// Show the authenticated fragment
showFragment(SELECTION, false);
} else if (state.isClosed()) {
// If the session state is closed:
// Show the login fragment
showFragment(SPLASH, false);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.equals(settings)) {
showFragment(SETTINGS, true);
return true;
}
return false;
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// if the session is already open,
// try to show the selection fragment
showFragment(SELECTION, false);
} else {
// otherwise present the splash screen
// and ask the person to login.
showFragment(SPLASH, false);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// only add the menu when the selection fragment is showing
if (fragments[SELECTION].isVisible()) {
if (menu.size() == 0) {
settings = menu.add(R.string.settings);
}
return true;
} else {
menu.clear();
settings = null;
}
return false;
}
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 showFragment(int fragmentIndex, boolean addToBackStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
transaction.show(fragments[i]);
} else {
transaction.hide(fragments[i]);
}
}
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
}
Any help would be appreciated! If any other files needed just ask.
Thanks!

Categories

Resources