/**
* Copyright 2010-present Facebook.
*
* 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.
*/
package com.ved.musicmapapp;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.ved.musicmapapp.Objects.User;
import com.ved.musicmapapp.providers.PostSongToServerTask;
//import com.ved.musicmapapp.providers.SyncSongTask;
import com.ved.musicmapapp.utils.Statics;
@SuppressLint("NewApi")
public class LoginAcitivity extends FragmentActivity implements OnClickListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public static String ACCESS_TOKEN = "CAACEdEose0cBAMkiWNRi0GPLtlEwMZAittxx0EtcIAEHhJegYiqdIVVu2ZCiF8GyZBNq6moFWtsZC2y6b7A4pqSdIaL0ZBV3ky5BOQV5xDk8T0MNH8SYzPM8eP005dVgB5rscPKTJYjXd25UIaKrgIKMzhTro3IfTBZCS6nX4KkZBCE0KKTuifFKG5InsW8W2JcYVKkf12wmKPfo1ZAG7AZBB";
private List<String> readPermissions = Arrays.asList("email",
"user_friends", "user_about_me", "user_birthday", "user_hometown",
"user_location", "user_actions.books", "user_actions.video",
"user_education_history", "user_games_activity", "user_interests",
"user_videos", "user_actions.music", "user_activities",
"user_likes");
// private List<String> readPermissions = Arrays.asList("email");
private View btnLogin;
private Session.StatusCallback statusCallback;
private ProgressDialog pd;
private SharedPreferences prefs;
private Editor edt;
private boolean isMusics, isMovies, isBooks, isGames, isMe;
private JSONObject objectMusics, objectMovies, objectBooks, objectGames,
objectMe;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login_facebook);
checkGooglePlayService();
isMusics = false;
isMovies = false;
isBooks = false;
isGames = false;
isMe = false;
prefs = getSharedPreferences("MUSIC_MAP", MODE_PRIVATE);
edt = prefs.edit();
btnLogin = findViewById(R.id.btn_login);
TextView discover_heading = (TextView) findViewById(R.id.discover_heading);
Typeface tf = Typeface.createFromAsset(getAssets(), "open_sans_regular.ttf");
discover_heading.setTypeface(tf);
btnLogin.setOnClickListener(this);
pd = new ProgressDialog(this);
pd.setMessage("Logging...");
pd.setCancelable(false);
if (getIntent().getBooleanExtra("LOGOUT", false)) {
onClickLogout();
}
initFacebook(savedInstanceState);
try {
PackageInfo info = getPackageManager().getPackageInfo(
getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.i("PXR", com.ved.musicmapapp.utils.Base64.encodeBytes(md
.digest()));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
updateView();
}
private boolean checkGooglePlayService() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
// errorDialog.setCancelable(false);
// errorDialog.setCanceledOnTouchOutside(false);
if (errorDialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(),
"Location Updates");
}
return false;
}
}
private void initFacebook(Bundle savedInstanceState) {
statusCallback = new SessionStatusCallback();
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback,
savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
// if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED))
// {
// session.openForRead(new Session.OpenRequest(this)
// .setCallback(statusCallback));
// }
}
}
private boolean checkHasPermisson() {
Session session = Session.getActiveSession();
for (String permistion : readPermissions) {
if (!session.getPermissions().contains(permistion))
return false;
}
return true;
}
@Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
@Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
checkGooglePlayService();
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void updateView() {
if (prefs.getString("FB_ID", "").length() > 0) {
// Go to home page
goToHome();
return;
}
if (!Statics.isNetworkConnected(this)
&& prefs.getString("FB_ID", "").length() == 0) {
Statics.showToast(this, "No internet connection!");
return;
}
final Session session = Session.getActiveSession();
if (session.isOpened()) {
// if (!checkHasPermisson()) {
// // session.requestNewPublishPermissions(new
// // Session.NewPermissionsRequest(
// // this, readPermissions));
// session.requestNewReadPermissions(new Session.NewPermissionsRequest(
// this, readPermissions));
// return;
// }
if (session != null && session.isOpened()) {
// If the session is open, make an API call to get user data
// and define a new callback to handle the response
/*
* if (prefs.getString("FB_ID", "").length() > 0) { finish();
* Intent i = new Intent(LoginAcitivity.this,
* MainActivity.class); i.putExtra("FOLLOW_FBID",
* getIntent().getStringExtra("FOLLOW_FBID")); startActivity(i);
* return; }
*/
pd.show();
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user,
Response response) {
// If the response is successful
if (user != null) {
GraphObject obj = response.getGraphObject();
String userId = user.getId()/* "605855975" */;
// edt.putString("USER_ID", user.getId());
// String username = obj
// .getProperty("username") == null ? userId
// : obj.getProperty("username")
// .toString();
String username = getUsername(obj
.getProperty("name").toString());
// /////////////
// /////////////
if (username.trim().length() == 0
|| userId.trim().length() == 0) {
Statics.showToast(LoginAcitivity.this,
"Couldn't get your Facebook information!");
return;
}
edt.putString("FB_ID", userId);
edt.putString("FB_NAME", user.getName());
edt.putString("FB_USERNAME", username);
edt.commit();
Log.i("User", username);
getFaceAccInfo(userId);
Statics.curUser = new User();
Statics.curUser.setFullName(user.getName());
Statics.curUser.setUserName(username);
Statics.curUser.setFirstName(user
.getFirstName());
Statics.curUser.setLastName(user
.getLastName());
Statics.curUser.setFbid(userId);
/*
* pd.dismiss();
*
* finish(); startActivity(new
* Intent(LoginAcitivity.this,
* MainActivity.class));
*/
}
}
});
Request.executeBatchAsync(request);
}
}
}
public String unAccent(String s) {
String temp = Normalizer.normalize(s, Normalizer.Form.NFD);
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return pattern.matcher(temp).replaceAll("").replaceAll("Đ", "D")
.replace("đ", "");
}
private String getUsername(String name) {
return unAccent(name.replace(" ", "."));
}
private void getFaceAccInfo(String userid) {
if (!pd.isShowing())
pd.show();
/*
* Bundle parameters = new Bundle();
* parameters.putString("access_token",
* "CAACEdEose0cBAHWbwnvUKIE4sSZBy8sfcyxwSC0m4gumpeS9QJpQb4QuAvmdAjDQK0bUgYDZAHiaJAahxlrS6UBIaG81CUttBhyzgYqO2AxUExwaETq7duVTCrz2FUrtYedZBnNcBrGgdgEuHREmgYQzwosxBpiB9QOpV0ZA1y2nvfZCgdNViN22vI6e08QxUySYA1ISDYXCaGpzZAjOsv"
* );
*
* parameters.putString("fields",
* "work,education,languages,games,books,music,movies"); new
* Request(Session.getActiveSession(), "me", parameters, null, new
* Request.Callback() {
*
* @Override public void onCompleted(Response response) { GraphObject
* graphObject = response.getGraphObject(); objectGames =
* graphObject.getInnerJSONObject(); isWork = true; isEducation = true;
* isLanguage = true; if (isMovies && isBooks && isMusics && isMe &&
* isWork && isLanguage && isEducation) { setFbJson(objectMe,
* objectBooks, objectGames, objectMovies,
* objectMusics,objectEducation,objectWork,objectLanguage); } }
* }).executeAsync();
*/
// Bundle postParams = new Bundle();
// postParams
// .putString(
// "access_token",
// "CAACEdEose0cBAFXGQpFZCO3uGEcFM4dp0FKB3w2hztaUFpRtuCUWogF3fjXByTMZCdul5ZBybDPy37xB7yJXN0rUZCcCyyQrYmdrw6ehYSmsZAAsZAxypf6JHifZAhZAtCzHIlgwf7AldZBbyrSnHvhzC97Wex4PBj6z3SgkbzNmIoZCQYerQZAjOdwI7xjX77aWgJhkTBGhZBWt1CuhBmerqZBCz");
Bundle postParams = new Bundle();
// postParams.putString("access_token", ACCESS_TOKEN);
postParams.putString("access_token", Session.getActiveSession().getAccessToken());
new Request(Session.getActiveSession(), "/me", null, HttpMethod.GET,
new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphObject graphObject = response.getGraphObject();
Log.i("Quang", "" + objectMe);
objectMe = graphObject.getInnerJSONObject();
} catch (Exception e) {
e.printStackTrace();
}
isMe = true;
if (isBooks && isGames && isMovies && isMusics) {
setFbJson(objectMe, objectBooks, objectGames,
objectMovies, objectMusics);
if (!prefs.getBoolean("first_login", false)) {
try {
if (objectMe.getString("name").length() > 0) {
edt = prefs.edit();
edt.putBoolean("first_login", true);
edt.commit();
getUserID();
} else {
showDialogRestart();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).executeAsync();
// MUSIC
new Request(Session.getActiveSession(), "/me/music", postParams,
HttpMethod.GET, new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphObject graphObject = response.getGraphObject();
Log.i("Music", "" + objectMusics);
objectMusics = graphObject.getInnerJSONObject();
} catch (Exception e) {
e.printStackTrace();
}
isMusics = true;
if (isBooks && isGames && isMovies && isMe) {
setFbJson(objectMe, objectBooks, objectGames,
objectMovies, objectMusics);
if (!prefs.getBoolean("first_login", false)) {
try {
if (objectMe.getString("name").length() > 0) {
edt = prefs.edit();
edt.putBoolean("first_login", true);
edt.commit();
getUserID();
} else {
showDialogRestart();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).executeAsync();
// MOVIES
new Request(Session.getActiveSession(), "/me/movies", postParams,
HttpMethod.GET, new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphObject graphObject = response.getGraphObject();
Log.i("Movie", "" + objectMovies);
objectMovies = graphObject.getInnerJSONObject();
} catch (Exception e) {
e.printStackTrace();
}
isMovies = true;
if (isBooks && isGames && isMusics && isMe) {
setFbJson(objectMe, objectBooks, objectGames,
objectMovies, objectMusics);
if (!prefs.getBoolean("first_login", false)) {
try {
if (objectMe.getString("name").length() > 0) {
edt = prefs.edit();
edt.putBoolean("first_login", true);
edt.commit();
getUserID();
} else {
showDialogRestart();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).executeAsync();
// BOOKS
new Request(Session.getActiveSession(), "/me/books", postParams,
HttpMethod.GET, new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphObject graphObject = response.getGraphObject();
Log.i("Book", "" + objectBooks);
objectBooks = graphObject.getInnerJSONObject();
} catch (Exception e) {
e.printStackTrace();
}
isBooks = true;
if (isMovies && isGames && isMusics && isMe) {
setFbJson(objectMe, objectBooks, objectGames,
objectMovies, objectMusics);
if (!prefs.getBoolean("first_login", false)) {
try {
if (objectMe.getString("name").length() > 0) {
edt = prefs.edit();
edt.putBoolean("first_login", true);
edt.commit();
getUserID();
} else {
showDialogRestart();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).executeAsync();
// GAMES
new Request(Session.getActiveSession(), "/me/games", postParams,
HttpMethod.GET, new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphObject graphObject = response.getGraphObject();
Log.i("Game", "" + objectGames);
objectGames = graphObject.getInnerJSONObject();
} catch (Exception e) {
e.printStackTrace();
}
isGames = true;
onGetLikeComplete();
}
}).executeAsync();
// getLikesMovie(null);
// getLikesMusic(null);
// getLikesGame(null);
// getLikesBook(null);
// getLikesMovie(postParams);
// getLikesMusic(postParams);
// getLikesGame(postParams);
// getLikesBook(postParams);
}
private void getLikesMovie(Bundle params) {
new Request(Session.getActiveSession(), "/me/movies", params,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try {
objectMovies = response.getGraphObject()
.getInnerJSONObject();
Log.i("Like", "" + objectMovies);
} catch (Exception e) {
e.printStackTrace();
}
isMovies = true;
onGetLikeComplete();
}
}).executeAsync();
}
private void getLikesMusic(Bundle params) {
new Request(Session.getActiveSession(), "/me/music", params,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try {
objectMusics = response.getGraphObject()
.getInnerJSONObject();
Log.i("Like", "" + objectMusics);
} catch (Exception e) {
e.printStackTrace();
}
isMusics = true;
onGetLikeComplete();
}
}).executeAsync();
}
private void getLikesBook(Bundle params) {
new Request(Session.getActiveSession(), "/me/books", params,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try {
objectBooks = response.getGraphObject()
.getInnerJSONObject();
Log.i("Like", "" + objectBooks);
} catch (Exception e) {
e.printStackTrace();
}
isBooks = true;
onGetLikeComplete();
}
}).executeAsync();
}
private void getLikesGame(Bundle params) {
new Request(Session.getActiveSession(), "/me/games", params,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try {
objectGames = response.getGraphObject()
.getInnerJSONObject();
Log.i("Like", "" + objectGames);
} catch (Exception e) {
e.printStackTrace();
}
isGames = true;
onGetLikeComplete();
}
}).executeAsync();
}
public void getUserID() {
/*GetDataTask dataTask = new GetDataTask(this, getIntent().getStringExtra("FOLLOW_FBID") != null ? getIntent().getStringExtra("FOLLOW_FBID") : "", true) {
@Override
public void onSuccess(User followUser) {*/
if (null != Statics.curUser) {
Statics.curUser = null;
}
if (null != Statics.hashUsers) {
Statics.hashUsers = null;
}
if (null != Statics.lstFriends)
Statics.lstFriends = null;
finish();
Intent i = new Intent(
LoginAcitivity.this,
MainActivity.class);
i.putExtra("FOLLOW_FBID", getIntent()
.getStringExtra("FOLLOW_FBID"));
startActivity(i);
//};
/*}; dataTask.execute();*/
}
private void onGetLikeComplete() {
if (isMovies && isGames && isMusics && isMe) {
setFbJson(objectMe, objectBooks, objectGames, objectMovies,
objectMusics);
if (!prefs.getBoolean("first_login", false)) {
if (!prefs.getBoolean("first_login", false)) {
try {
if (objectMe.getString("name").length() > 0) {
edt = prefs.edit();
edt.putBoolean("first_login", true);
edt.commit();
getUserID();
} else {
showDialogRestart();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private void setFbJson(JSONObject jSONObjectme, JSONObject jSONObjectbooks,
JSONObject jSONObjectgames, JSONObject jSONObjectmovies,
JSONObject jSONObjectmusics) {
try {
String music = "";
JSONArray musicArray = jSONObjectmusics.getJSONArray("data");
if (musicArray.length() > 0) {
music = musicArray.getJSONObject(0).getString("name");
}
for (int i = 1; i < musicArray.length(); i++) {
music += "," + musicArray.getJSONObject(i).getString("name");
}
jSONObjectme.put("music", music);
} catch (Exception e) {
}
try {
String movies = "";
JSONArray moviesArray = jSONObjectmovies.getJSONArray("data");
if (moviesArray.length() > 0) {
movies = moviesArray.getJSONObject(0).getString("name");
}
for (int i = 1; i < moviesArray.length(); i++) {
movies += "," + moviesArray.getJSONObject(i).getString("name");
}
jSONObjectme.put("movies", movies);
} catch (Exception e) {
}
try {
String books = "";
JSONArray booksArray = jSONObjectbooks.getJSONArray("data");
if (booksArray.length() > 0) {
books = booksArray.getJSONObject(0).getString("name");
}
for (int i = 1; i < booksArray.length(); i++) {
books += "," + booksArray.getJSONObject(i).getString("name");
}
jSONObjectme.put("books", books);
} catch (Exception e) {
}
try {
String games = "";
JSONArray gamesArray = jSONObjectgames.getJSONArray("data");
if (gamesArray.length() > 0) {
games = gamesArray.getJSONObject(0).getString("name");
}
for (int i = 1; i < gamesArray.length(); i++) {
games += "," + gamesArray.getJSONObject(i).getString("name");
}
jSONObjectme.put("games", games);
} catch (Exception e) {
}
Log.i("check", "jSONObjectme : /// " + jSONObjectme);
try {
String data = Base64.encodeToString(jSONObjectme.toString()
.getBytes(), Base64.DEFAULT);
edt.putString("FB_JSON", data);
edt.commit();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (pd != null && pd.isShowing())
pd.dismiss();
} catch (Exception ex) {
}
// Go to home page
goToHome();
}
private void getFaceAccInfo1(String userid) {
if (!pd.isShowing())
pd.show();
String fqlQuery = "SELECT uid,first_name,last_name,name,email,birthday_date,current_location,"
+ "about_me,sex,religion,languages, music, movies, books,games,work,education, "
+ "favorite_athletes,inspirational_people,favorite_teams "
+ "FROM user WHERE uid='" + userid + "'";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
params.putString("access_token", ACCESS_TOKEN);
Session session = Session.getActiveSession();
Request request = new Request(session, "/fql", params, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
JSONObject jsonObject = graphObject
.getInnerJSONObject();
try {
JSONObject obj = jsonObject.getJSONArray("data")
.getJSONObject(0)
.getJSONObject("current_location");
Toast.makeText(getApplicationContext(),
"" + jsonObject.getJSONArray("data"),
Toast.LENGTH_LONG).show();
Log.i("json", jsonObject.getJSONArray("data") + "");
edt.putString("LAST_LONGITUDE",
obj.getString("longitude"));
edt.putString("LAST_LATITUDE",
obj.getString("latitude"));
Log.i("JSON_DATA", jsonObject.toString());
edt.commit();
} catch (JSONException e) {
e.printStackTrace();
}
//
try {
String data = Base64.encodeToString(jsonObject
.toString().getBytes(), Base64.DEFAULT);
edt.putString("FB_JSON", data);
edt.commit();
} catch (Exception e) {
e.printStackTrace();
}
pd.dismiss();
// Go to home page
goToHome();
}
});
Request.executeBatchAsync(request);
}
public void goToHome() {
if (prefs.getString("FB_ID", "").length() == 0) {
Statics.showToast(this,
"Cannot get your Facebook infor. Please try again!");
return;
}
if (prefs.getString("FB_USERNAME", "").length() == 0
|| prefs.getString("FB_USERNAME", "") == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Message");
builder.setMessage("Unable to log into app. Please try again!");
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
edt = prefs.edit();
edt.putString("FB_ID", null);
edt.commit();
finish();
}
});
builder.setNeutralButton("Try again",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
edt = prefs.edit();
edt.putString("FB_ID", null);
edt.commit();
finish();
Intent i = new Intent(LoginAcitivity.this,
LoginAcitivity.class);
startActivity(i);
}
});
builder.show();
return;
}
if (!prefs.getBoolean("first_login", false))
return;
finish();
Intent i = new Intent(LoginAcitivity.this, MainActivity.class);
i.putExtra("FOLLOW_FBID", getIntent().getStringExtra("FOLLOW_FBID"));
startActivity(i);
/*
* if(Statics.curUser != null && (Statics.curUser.getFbid() != null &&
* (Statics.curUser != null && Statics.curUser.getFullName() != null &&
* Statics.curUser.getFullName().length() > 0))){ finish(); Intent i =
* new Intent(LoginAcitivity.this, MainActivity.class);
* i.putExtra("FOLLOW_FBID", getIntent().getStringExtra("FOLLOW_FBID"));
* startActivity(i); }else{ AlertDialog.Builder builder = new
* AlertDialog.Builder(this); builder.setTitle("Message");
* builder.setMessage("Unable to log into app. Please try again!");
* builder.setNegativeButton("Cancel", new
* DialogInterface.OnClickListener() {
*
* @Override public void onClick(DialogInterface dialog, int which) { //
* TODO Auto-generated method stub edt.putString("FB_ID", null);
* edt.commit(); finish(); } }); builder.setNeutralButton("Try again",
* new DialogInterface.OnClickListener() {
*
* @Override public void onClick(DialogInterface dialog, int which) { //
* TODO Auto-generated method stub edt.putString("FB_ID", null);
* edt.commit(); finish(); Intent i = new Intent(LoginAcitivity.this,
* LoginAcitivity.class); startActivity(i); } }); builder.show(); }
*/
}
private void onClickLogin() {
Session session = Session.getActiveSession();
// performFacebookPermisson();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setPermissions(readPermissions)
.setCallback(statusCallback));
} else {
openActiveSession(this, true, statusCallback,readPermissions);
}
}
public static Session openActiveSession(Activity activity,
boolean allowLoginUI, Session.StatusCallback callback,
List<String> permissions) {
Session.OpenRequest openRequest = new Session.OpenRequest(activity)
.setPermissions(permissions).setCallback(callback);
Session session = new Session.Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState())
|| allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
private void onClickLogout() {
edt.putString("USER_ID", "");
edt.putString("FB_ID", "");
edt.putString("FB_NAME", "");
edt.putString("FB_USERNAME", "");
edt.putString("DATA_UPLOAD", "");
edt.putString("FB_JSON", "");
edt.commit();
SharedPreferences settings = this.getSharedPreferences("MUSIC_MAP",
Context.MODE_PRIVATE);
settings.edit().clear().commit();
// if (SyncSongTask.exists != null) {
// SyncSongTask.exists.clear();
// }
if (PostSongToServerTask.exists != null) {
PostSongToServerTask.exists.clear();
}
Session session = Session.getActiveSession();
if(session != null){
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
}
private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state,
Exception exception) {
updateView();
}
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_login) {
onClickLogin();
} /*else if (v.getId() == R.id.tab_join) {
tab_join.setBackgroundResource(R.drawable.bg_tab_press);
tab_about.setBackgroundResource(R.drawable.bg_btn_tab);
} else if (v.getId() == R.id.tab_about) {
tab_join.setBackgroundResource(R.drawable.bg_btn_tab);
tab_about.setBackgroundResource(R.drawable.bg_tab_press);
}*/
}
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
public void showDialogRestart() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Message");
builder.setMessage("Unable to log into app. Please try again!");
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
edt = prefs.edit();
edt.putString("FB_ID", "");
edt.commit();
finish();
}
});
builder.setNeutralButton("Try again",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
edt = prefs.edit();
edt.putString("FB_ID", "");
edt.commit();
finish();
Intent i = new Intent(LoginAcitivity.this,
LoginAcitivity.class);
startActivity(i);
}
});
builder.show();
}
}