Java tutorial
/* * Copyright 2013 SciFY NPO <info@scify.org>. * * This product is part of the NewSum Free Software. * For more information about NewSum visit * * http://www.scify.gr/site/en/our-projects/completed-projects/newsum-menu-en * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * If this code or its output is used, extended, re-engineered, integrated, * or embedded to any extent in another software or hardware, there MUST be * an explicit attribution to this work in the resulting source code, * the packaging (where such packaging exists), or user interface * (where such an interface exists). * The attribution must be of the form "Powered by NewSum, SciFY" */ package gr.scify.newsum.ui; import gr.scify.newsum.Setlanguage; import java.util.Arrays; import java.util.List; import java.util.Locale; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.facebook.FacebookAuthorizationException; import com.facebook.FacebookOperationCanceledException; import com.facebook.FacebookRequestError; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.model.GraphObject; import com.facebook.model.GraphUser; import com.facebook.widget.LoginButton; import com.facebook.widget.ProfilePictureView; public class Facebook extends FragmentActivity { private static final List<String> PERMISSIONS = Arrays.asList("publish_actions"); private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction"; private Button postStatusUpdateButton; private LoginButton loginButton; private ProfilePictureView profilePictureView; private TextView greeting; private PendingAction pendingAction = PendingAction.NONE; private ViewGroup controlsContainer; private GraphUser user; String summaryF; private enum PendingAction { NONE, 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); if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) != Configuration.SCREENLAYOUT_SIZE_NORMAL & (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) != Configuration.SCREENLAYOUT_SIZE_SMALL) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } SharedPreferences userlang = getSharedPreferences("lang", 0); String newlang = userlang.getString("lang", Locale.getDefault().getLanguage()); // Changed getApplicationContext() to "this" Setlanguage.updateLanguage(this, newlang); 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.facebook); Bundle extras = getIntent().getExtras(); summaryF = extras.getString("summaryF"); loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() { @Override public void onUserInfoFetched(GraphUser user) { Facebook.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(); } }); 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); } // 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(Facebook.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); 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_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 = summaryF; 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 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)); } } } }