Java tutorial
/* * The MIT License (MIT) * * Copyright (c) 2015 Mohammed Sazid-Al-Rashid * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mohammedsazid.android.tagger; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.text.method.ScrollingMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.facebook.FacebookException; import com.facebook.FacebookOperationCanceledException; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.widget.WebDialog; public class TaggerFragment extends Fragment implements TextWatcher, View.OnClickListener, CompoundButton.OnCheckedChangeListener { // private static final String LOG_TAG = TaggerFragment.class.getSimpleName(); private EditText inputEt; private TextView outputTv; private Button buttonCopy; private Button buttonShareFacebook; private Button buttonRequestFacebook; private Switch switchMode; private boolean loggedIn; private boolean plainOutput = false; private String changedText; /** * Bind views with the UI */ private void bindViews(View v) { inputEt = (EditText) v.findViewById(R.id.inputEt); outputTv = (TextView) v.findViewById(R.id.outputTv); buttonCopy = (Button) v.findViewById(R.id.buttonCopy); buttonShareFacebook = (Button) v.findViewById(R.id.buttonShareFacebook); buttonRequestFacebook = (Button) v.findViewById(R.id.buttonRequestFacebook); switchMode = (Switch) v.findViewById(R.id.switchMode); } /** * Bind listeners to views */ private void bindListeners() { buttonCopy.setOnClickListener(this); buttonShareFacebook.setOnClickListener(this); buttonRequestFacebook.setOnClickListener(this); switchMode.setOnCheckedChangeListener(this); inputEt.addTextChangedListener(this); outputTv.setMovementMethod(new ScrollingMovementMethod()); } private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception e) { onSessionStateChange(session, state, e); } }; private UiLifecycleHelper uiLifecycleHelper; public TaggerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); uiLifecycleHelper = new UiLifecycleHelper(getActivity(), callback); uiLifecycleHelper.onCreate(savedInstanceState); } @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. final Session session = Session.getActiveSession(); if (session != null && (session.isOpened() || session.isClosed())) { onSessionStateChange(session, session.getState(), null); } uiLifecycleHelper.onResume(); } @Override public void onPause() { super.onPause(); uiLifecycleHelper.onPause(); } @Override public void onDestroyView() { super.onDestroyView(); uiLifecycleHelper.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); uiLifecycleHelper.onSaveInstanceState(outState); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiLifecycleHelper.onActivityResult(requestCode, resultCode, data); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_tagger, container, false); bindViews(rootView); bindListeners(); return rootView; } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.buttonShareFacebook: String statusUpdate = outputTv.getText().toString(); postStatusUpdate(statusUpdate); break; case R.id.buttonCopy: copyToClipboard(getActivity(), outputTv.getText().toString()); Toast.makeText(getActivity(), "Copied", Toast.LENGTH_SHORT).show(); break; case R.id.buttonRequestFacebook: sendRequestDialog(); break; } } private void postStatusUpdate(String newStatus) { try { while (true) { if (WelcomeFragment.checkPermissions()) { Request request = Request.newStatusUpdateRequest(Session.getActiveSession(), newStatus, new Request.Callback() { @Override public void onCompleted(Response response) { Toast.makeText(getActivity(), "Status update successful", Toast.LENGTH_SHORT) .show(); } }); request.executeAsync(); break; } else { Toast.makeText(getActivity(), "You need to permit the app to post (login to facebook)", Toast.LENGTH_SHORT).show(); WelcomeFragment.requestPublishPermission(getActivity()); } } } catch (Exception e) { e.printStackTrace(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } private void setFbButtonsVisibility(boolean share, boolean request) { buttonShareFacebook.setVisibility(share == true ? View.VISIBLE : View.INVISIBLE); buttonRequestFacebook.setVisibility(request == true ? View.VISIBLE : View.INVISIBLE); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { changedText = s.toString(); if (!plainOutput) { changedText = convertString(changedText, "#"); } if (s.length() > 0 && loggedIn) { setFbButtonsVisibility(true, true); } else if (loggedIn) { setFbButtonsVisibility(false, true); } else { setFbButtonsVisibility(false, false); } outputTv.setText(changedText); } public boolean copyToClipboard(Context context, String text) { try { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context .getSystemService(context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText(getString(R.string.app_name), text); clipboard.setPrimaryClip(clip); return true; } catch (Exception e) { return false; } } private void onSessionStateChange(final Session session, SessionState state, Exception exception) { if (state.isOpened()) { // Log.i(LOG_TAG, "Logged in..."); setFbButtonsVisibility(false, true); loggedIn = true; } else if (state.isClosed()) { // Log.i(LOG_TAG, "Logged out..."); setFbButtonsVisibility(false, false); loggedIn = false; } } private String convertString(String s, String charToReplaceWith) { if (s.length() == 0) { charToReplaceWith = ""; } s = charToReplaceWith + s.trim().replaceAll(" ", " " + charToReplaceWith) .replaceAll("\n", "\n" + charToReplaceWith).replaceAll(charToReplaceWith + " [^.]*?", " "); return s; } private void sendRequestDialog() { Bundle params = new Bundle(); params.putString("message", "Hey, check out #tagger. #tag #all #your #words!"); WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(getActivity(), Session.getActiveSession(), params)).setOnCompleteListener(new WebDialog.OnCompleteListener() { @Override public void onComplete(Bundle values, FacebookException error) { if (error != null) { if (error instanceof FacebookOperationCanceledException) { Toast.makeText(getActivity().getApplicationContext(), "Request cancelled", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity().getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show(); } } else { final String requestId = values.getString("request"); if (requestId != null) { Toast.makeText(getActivity().getApplicationContext(), "Request sent", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity().getApplicationContext(), "Request cancelled", Toast.LENGTH_SHORT).show(); } } } }).build(); requestsDialog.show(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int id = buttonView.getId(); if (id == R.id.switchMode) { if (plainOutput) { outputTv.setText(convertString(inputEt.getText().toString(), "#")); } else { outputTv.setText(convertString(inputEt.getText().toString(), "")); } plainOutput = !plainOutput; } } }