Java program won't write to firebase [duplicate] - java

I'm trying to write a simple test of the Firebase user creation and authentication routines so that I can test my Firebase security settings. The code runs smoothly but the callbacks are not invoked and no users are created on the Firebase side.
The output of below with the print statements is:
Begin process
Start Create User
Creating User
End Creating User
End process
Process finished with exit code 0
The code is using the firebase-client-android-2.2.3.jar file for the Firebase classes though I'm just running my test as a java application on a Mac OS. Later this will go into an Android app but I'd like to be able to run it inside my IDE for now. Any insights from experienced Firebase coders much appreciated.
import com.firebase.client.Firebase;
import com.firebase.client.AuthData;
import com.firebase.client.FirebaseError;
import java.util.*;
public class FireRulesTest {
static String firebase_baseUrl = "https://<myfirebase>.firebaseio.com/";
public static void main(String[] args)
throws FirebaseException {
System.out.println("Begin process");
FireRulesTest tester = new FireRulesTest();
tester.createUser();
System.out.println("End process");
}
private void createUser()
throws FirebaseException {
try {
System.out.println("Start Create User");
final String mEmail = "me#email.com";
final String mPassword = "password";
final Firebase ref = new Firebase(firebase_baseUrl);
System.out.println("Creating User");
ref.createUser(mEmail, mPassword,
new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
ref.authWithPassword(mEmail, mPassword, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
//success, save auth data
HashMap<String, Object> authMap = new HashMap<String, Object>();
authMap.put("uid", authData.getUid());
authMap.put("token", authData.getToken());
authMap.put("email", mEmail);
authMap.put("password", mPassword);
Firebase currentUserRef = new Firebase(firebase_baseUrl + "movo/users/" + authData.getUid());
authMap.put("currentUser", currentUserRef);
System.out.println("User ID: " + authData.getUid() +
", Provider: " + authData.getProvider() +
", Expires:" + authData.getExpires());
System.out.println("Authentication complete");
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
System.out.println("Authentication Error authenticating newly created user. This could be an issue. ");
System.out.println(firebaseError.getMessage());
}
});
}
#Override
public void onError(FirebaseError firebaseError) {
System.out.println("On Error authenticating newly created user. This could be an issue. ");
System.out.println(firebaseError.getMessage());
}
});
System.out.println("End Creating User");
} catch (Exception fbe) {
System.out.println("Exception: " + fbe.getMessage());
fbe.printStackTrace();
}
}
}

You'll want to add a Thread.sleep at the end of the program. Likely your program exits before Firebase gets a chance to send anything to the server.
A more proper solution would be to introduce actual lifecycle management into your app, e.g. waiting for the createUser call to finish. But given that you'll be migrating this to Android (which handles app lifecycle completely different anyway) that might not be worth the effort.

Related

Waiting until boolean value is changed without blocking main JavaFX thread?

I have been reading for hours about different multi-threading techniques for JavaFX and cannot seem to find what I'm looking for. The application being worked on is the "Messenger" which part of a bigger application to provide a trading marketplace for a game.
A breakdown of the process I am having trouble with:
A window with a 'Contact Seller' button is displayed
The user clicks 'Contact Seller', and the Messenger window should be displayed
Using the seller's name from the main window, the Messenger should check if a chat already exists with that name
If the chat already exists, get the index of that chat in the Messenger's ListView, and select the chat so the Messenger's text area is populated with the corresponding messages
If the chat doesn't exist, create one
The issue:
Chats are stored server-side
Messages between clients are stored in a message 'cache' on the server when being processed from one user to the other (they are sorted to their respective chats, inserted into the chats, and pushed to the database upon client disconnection)
Messages received on the client are stored locally in the respective chat
When the Messenger is opened, it requests a list of chats for the signed-in user
The server sends an ArrayList of chats, and upon receiving the client builds the Messenger's ListView with these objects
Now when I need to open the Messenger in order to 'Contact Seller', I need to make sure the sync with the server is complete. Without doing so, I won't be able to properly check if a chat already exists with that name since I won't have the most up-to-date list.
The 'RequestWorker' thread that handles incoming server messages is NOT on the JavaFX thread.
The RequestWorker 'gets' the Messenger instance if it is currently open, and populates the ListView with the newly received chat list. (This needs to happen on the JavaFX thread, since I am working in the Messenger GUI)
What I am trying to do is set a static AtomicBoolean syncInProgress to true when the Messenger initiates a sync upon being displayed. When the RequestWorker receives the latest list back from the server and finishes populating the Messengers ListView, it sets syncInProgress to false.
The sync takes longer than opening the Messenger and making it check if a chat exists. Doing it this way it has no items populated yet in the ListView and the method is ineffective.
Calling a while loop to wait until the boolean is changed, blocks the JavaFX thread which means the RequestWorker cannot do what it needs to in the JavaFX thread.
How can I continuously check for this variable to be set false, then continue to 'Contact Seller' once the ListView has been properly populated?
Contact Seller method: The while loop in here causes a block on the JavaFX thread, thus not enabling RequestWorker to properly populate the ListView.
public static void contactSeller(Messenger messenger, String destination, String itemName)
{
while (TarkovTrader.syncInProgress.get())
{
; // Wait until sync is complete to check the latest chat list for an existing chat
}
if (messenger.chatExists(destination))
{
// Chat exists, select the chat for the user
for (Chat openChat : messenger.chatListView.getItems())
{
if (openChat.getName(TarkovTrader.username).equals(destination))
{
messenger.chatListView.getSelectionModel().select(openChat);
messenger.unpackChatMessages(openChat.getMessages());
break;
}
}
}
else
{
messenger.buildNewChat(destination);
}
messenger.chatInput.setText("Hey " + destination + ". Interested in your '" + itemName + "'.");
messenger.chatInput.setOnMouseClicked(e -> messenger.chatInput.clear());
}
RequestWorker process chat block:
switch(receivedFromServer)
case "chatlist":
// Client requested a chat list, results were returned from the server, and now we need to populate the messenger list
ChatListForm chatlistform = (ChatListForm)processedRequest;
if (Messenger.isOpen)
{
FutureTask<Void> updateChatList = new FutureTask(() -> {
Messenger tempMessenger = trader.getMessenger();
int currentIndex = tempMessenger.chatListView.getSelectionModel().getSelectedIndex();
tempMessenger.populate(chatlistform.getChatList());
tempMessenger.chatListView.getSelectionModel().select(currentIndex);
}, null);
Platform.runLater(updateChatList); // RequestWorker needs access to the JavaFX application thread
try {
updateChatList.get(); // Wait until the ListView has been populated before setting 'syncInProgress' to false again
}
catch (InterruptedException e) {
Alert.display(null, "Sync interrupted.");
}
catch (ExecutionException e) {
Alert.display(null, "Sync failed.");
}
TarkovTrader.syncInProgress.compareAndSet(true, false); // The value of syncInProgress should be true, change to false. Sync complete
}
else
{
Platform.runLater(() -> Alert.display(null, "New chat received."));
TarkovTrader.syncInProgress.compareAndSet(true, false);
}
break;
Contact Seller button logic: If a messenger is not open, create it and pass to static contactSeller method to use.
contactButton.setOnAction(e -> {
Messenger messenger;
if (Messenger.isOpen)
{
// Get messenger
messenger = trader.getMessenger();
}
else
{
messenger = new Messenger(worker);
messenger.display();
trader.setMessenger(messenger);
}
Messenger.contactSeller(messenger, item.getUsername(), item.getName());
itemdisplay.close();
});
EDIT:
Partially using Slaw's idea (AtomicBoolean is still being used since I'm not sure how to do this without it), this is what I came up with...
public static void contactSeller(Messenger messenger, String destination, String itemName)
{
Task<Void> waitForSync = new Task<Void>() {
#Override
public Void call()
{
while (TarkovTrader.syncInProgress.get())
{
; // Wait until sync is complete
}
return null;
}
};
waitForSync.setOnSucceeded(e -> {
while (TarkovTrader.syncInProgress.get())
{
; // Wait until sync is complete to check the latest chat list for an existing chat
}
if (messenger.chatExists(destination))
{
// Chat exists, select the chat for the user
for (Chat openChat : messenger.chatListView.getItems())
{
if (openChat.getName(TarkovTrader.username).equals(destination))
{
messenger.chatListView.getSelectionModel().select(openChat);
messenger.unpackChatMessages(openChat.getMessages());
break;
}
}
}
else
{
messenger.buildNewChat(destination);
}
messenger.chatInput.setText("Hey " + destination + ". Interested in your '" + itemName + "'.");
messenger.chatInput.setOnMouseClicked(me -> messenger.chatInput.clear());
});
Thread t = new Thread(waitForSync);
t.setDaemon(true);
t.start();
}
Which does work, but this doesn't seem like a great solution. Is it fine to do something like this or is there a preferred method over this? I feel like the while loop and using a triggered boolean is sloppy..but is this common practice?
Don't try to handle the opened chat in the same method that schedules the chat retrieval. Instead create a queue of handlers that is executed as soon as the chat is ready.
Simplified Example
public class ChatManager {
private final Map<String, Chat> openChats = new HashMap<>();
// only call from application thread
public void openChat(String user, Consumer<Chat> chatReadyHandler) {
Chat chat = openChats.computeIfAbsent(user, this::createNewChat);
chat.addReadyHandler(chatReadyHandler);
}
private Chat createNewChat(String user) {
return new Chat(user);
}
public class Chat {
// list keeping track of handlers any used for synchronisation
private final ArrayList<Consumer<Chat>> readyHandlers = new ArrayList<>(1);
private boolean ready = false;
private final String user;
public String getUser() {
return user;
}
private void addReadyHandler(Consumer<Chat> chatReadyHandler) {
synchronized (readyHandlers) {
// if already ready, immediately execute, otherwise enqueue
if (ready) {
chatReadyHandler.accept(this);
} else {
readyHandlers.add(chatReadyHandler);
}
}
}
private void chatReady() {
synchronized (readyHandlers) {
ready = true;
}
// execute all handlers on the application thread
Platform.runLater(() -> {
synchronized (readyHandlers) {
for (Consumer<Chat> readyHandler : readyHandlers) {
readyHandler.accept(this);
}
readyHandlers.clear();
readyHandlers.trimToSize();
}
});
}
private Chat(String user) {
this.user = user;
new Thread(() -> {
try {
Thread.sleep(10000); // simulate time required to acquire chat
} catch (InterruptedException ex) {
}
chatReady();
}).start();
}
}
}
The following code creates a Chat with a user when Enter is pressed after typing the user name in the TextField and prints a message to the TextArea when the chat is ready.
#Override
public void start(Stage primaryStage) throws Exception {
ChatManager worker = new ChatManager();
TextField userName = new TextField();
TextArea textArea = new TextArea();
textArea.setEditable(false);
userName.setOnAction(evt -> {
String user = userName.getText();
userName.clear();
textArea.appendText("opening chat for " + user + "\n");
worker.openChat(user, chat -> textArea.appendText("chat for " + chat.getUser() + " ready\n"));
});
Scene scene = new Scene(new VBox(10, userName, textArea));
primaryStage.setScene(scene);
primaryStage.show();
}

Discord java bot verify user by name

in my current Discord (java) bot im trying to apply a command to a user name. how can i make sure this is an actual existing user ?
in psuedo code:
if User "A" exists {
User "A" types something at all
send message "hello"+ user "A"
}
else
{
this is no valid user;
}
i can't figure out how to write the 'check if exist code'.
This is from JDA-Utilities which is a really useful tool when building discord bots.
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
public class Example extends Command {
public Example() {
this.name = "'isBot";
this.help = "Tells you if the user is a bot!";
}
#Override
protected void execute(CommandEvent e) {
if (e.getAuthor().isBot()) {
e.reply("Hey you're not a person!!");
} else {
e.reply("Hey " + e.getAuthor().getName() + ", you're not a bot!");
}
}
}

Waiting for asynchronous I/O on Android

I have been trying for awhile to figure out an issue with Asynchronous i/o in an android application that I am working on.
This application is required to download data to from a series of tables from Microsoft Dynamics CRM.
Once the data has been down it must preform a series of operations on the data to fill out some forms.
My problem is that I must wait for the downloads to be complete in order to start the update process.
If I add a any form of wait to my code it seems that it blocks indefinitely and never executes the callback.
I have tried methods using AtomicBooleans, AtomicIntegers, and CountDownLatchs with no success.
Here is an example using an AtomicInteger.
final CountDownLatch latch = new CountDownLatch(1);
OrganizationServiceProxy orgService;
orgService = new OrganizationServiceProxy(Constant.ENDPOINT, CRMLogin.getRequestInterceptor());
ColumnSet columnSet = new ColumnSet();
columnSet.AddColumns(AccountEntry.FETCH_COLS);
orgService.Retrieve(AccountEntry.ENTITY, UUID.fromString(accountid), columnSet, new Callback<Entity>() {
#Override
public void success(Entity entity, Response response) {
Account account = new Account();
//Load the existing fields for the account
account.load(index);
String activityid = account.getValue(AccountEntry.ACTIVITY_ID);
String recordid = account.getValue(AccountEntry.RECORD_ID);
String name = account.getValue(AccountEntry.ACCOUNT_NAME);
//Overload the fields for the account
account.load(entity);
//Reset overloaded fields on the account.
account.setValue(AccountEntry.ACTIVITY_ID, activityid);
account.setValue(AccountEntry.RECORD_ID, recordid);
account.setValue(AccountEntry.ACCOUNT_NAME, name);
//overwrite the record in the database.
account.setValue(AccountEntry.SYNCED, "1");
account.update();
Log.d("pullAccount>>>", accountid + " " + "pulled.");
latch.countDown();
}
#Override
public void failure(RetrofitError error) {
Log.d("pullAccount>>>", accountid + " " + error.getMessage());
latch.countDown();
}
});
try{
latch.await(); //THIS BLOCKS FOREVER AND EVER
}
catch (Exception e){
}
Of note is the CallBack is implemented using Retrofit.
Any guidance would be greatly appreciated.
Thank you.
Look at AsyncTask it will handle what you want in a way that Android is optimized for. There is example usage here
http://developer.android.com/reference/android/os/AsyncTask.html
EDIT:
I kinda threw this together, let me know if it works as you would expect
public class AsyncOrganizationService extends AsyncTask<Void, Void, Entity> {
#Override
protected Entity doInBackground(Void... params) {
final CountDownLatch blocker = new CountDownLatch(1);
OrganizationServiceProxy orgService;
orgService = new OrganizationServiceProxy(Constant.ENDPOINT, CRMLogin.getRequestInterceptor());
ColumnSet columnSet = new ColumnSet();
columnSet.AddColumns(AccountEntry.FETCH_COLS);
final SettableFuture<Entity> result = SettableFuture.create();
orgService.Retrieve(AccountEntry.ENTITY, UUID.fromString(accountid), columnSet, new SortedList.Callback<Entity>() {
#Override
public void success(Entity entity, HttpHelper.Response response) {
result.set(entity);
blocker.countDown();
}
});
try {
blocker.await();
return result.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onPostExecute(Entity entity) {
Account account = new Account();
//Load the existing fields for the account
account.load(index);
String activityid = account.getValue(AccountEntry.ACTIVITY_ID);
String recordid = account.getValue(AccountEntry.RECORD_ID);
String name = account.getValue(AccountEntry.ACCOUNT_NAME);
//Overload the fields for the account
account.load(entity);
//Reset overloaded fields on the account.
account.setValue(AccountEntry.ACTIVITY_ID, activityid);
account.setValue(AccountEntry.RECORD_ID, recordid);
account.setValue(AccountEntry.ACCOUNT_NAME, name);
//overwrite the record in the database.
account.setValue(AccountEntry.SYNCED, "1");
account.update();
Log.d("pullAccount>>>", accountid + " " + "pulled.");
}
Im using Guava's SettableFuture class (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/SettableFuture.html). Guava is quite an amazing library - if you're not using it you should consider doing so. Otherwise, you could whip something up really quick

twitch java google spreadsheet

Okay, here goes nothing, I've been working on a twitch bot for my channel for some time now, making stupid little functions and stuff just to keep me coding and learning new things. I've taken on a project that seems to have gotten very complicated for me. If you have been to twitch I'm sure you have seen a loyalty bot that gives digital play money for time spent in the channel, so I wanted to add that feature with a twist. rather then use a local spreadsheet or MySQL or something that I've never used before I wanted to use the Google docs API to update an online spreadsheet so that the information could be seen by my viewers without the need for constant chat spamming for how many currency they have. (if I've already made a huge mistake in the planning phase don't hesitate to send me in the right direction with this)
so the basics, I'm using Pircbot to create a chat bot for twitch (irc based chat system). I want only two columns for now A being usernames and B being currency.
So first plan was when people join the chat look to see if they are on the spread sheet already and add them if they are not there, then implement a system for every ten minutes pushing out a value++ to anyone who is in the chat.
so on join run a function, simple enough:
#Override
protected void onJoin(String channel, String sender, String login, String hostname) {
//attempt to add new person to the spread sheet if they are not already listed.
//cells(0,0) (a,1)
try {
ss.addUser(sender);
}catch (IOException w) {
System.out.println(w);
}
catch (ServiceException q){
System.out.println(q);
}
now comes the part I'm getting really lost on, I can't seem to figure out if this is working, but I have a strong feeling the code I found and was following is old and no longer right. here is the class for handling the spread sheet:
class ss{
public static final String GOOGLE_ACCOUNT_USERNAME = "xxxx#gmail.com";
public static final String GOOGLE_ACCOUNT_PASSWORD = "xxxx";
public static final String SPREADSHEET_URL = "https://spreadsheets.google.com/feeds/spreadsheets/"code after my sheet"";
public static void addUser(String user) throws IOException, ServiceException {
/** Our view of Google Spreadsheets as an authenticated Google user. */
SpreadsheetService service = new SpreadsheetService("Print Google Spreadsheet Demo");
// Login and prompt the user to pick a sheet to use.
service.setUserCredentials(GOOGLE_ACCOUNT_USERNAME, GOOGLE_ACCOUNT_PASSWORD);
// Load sheet
URL metafeedUrl = new URL(SPREADSHEET_URL);
SpreadsheetEntry spreadsheet = service.getEntry(metafeedUrl, SpreadsheetEntry.class);
URL listFeedUrl = ((WorksheetEntry) spreadsheet.getWorksheets().get(0)).getListFeedUrl();
// Creating a local representation of the new row.
ListEntry row = new ListEntry();
row.getCustomElements().setValueLocal("Name", user);
row.getCustomElements().setValueLocal("Currency", "0");
}
}
as you can see, I got as for as trying to add new users as they enter the channel, but unfortunately all it does is throw errors:
java.lang.NoClassDefFoundError: Could not initialize class
com.google.gdata.client.spreadsheet.SpreadsheetService
at ss.addUser(didbot.java:30)
at didbot.onJoin(didbot.java:186)
at org.jibble.pircbot.PircBot.handleLine(PircBot.java:1000)
at org.jibble.pircbot.InputThread.run(InputThread.java:92)
total code if you are brave enough to see the mass text wall of my failure in coding xD
import org.jibble.pircbot.PircBot;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.ServiceException;
/**
* Created by Evan on 11/4/2014.
*/
class ss{
public static final String GOOGLE_ACCOUNT_USERNAME = "*email*#gmail.com"; // Fill in google account username
public static final String GOOGLE_ACCOUNT_PASSWORD = "*password*"; // Fill in google account password
public static final String SPREADSHEET_URL = "https://spreadsheets.google.com/feeds/spreadsheets/*code*"; // Fill in google spreadsheet URI
public static void addUser(String user) throws IOException, ServiceException {
/** Our view of Google Spreadsheets as an authenticated Google user. */
SpreadsheetService service = new SpreadsheetService("Print Google Spreadsheet Demo");
// Login and prompt the user to pick a sheet to use.
service.setUserCredentials(GOOGLE_ACCOUNT_USERNAME, GOOGLE_ACCOUNT_PASSWORD);
// Load sheet
URL metafeedUrl = new URL(SPREADSHEET_URL);
SpreadsheetEntry spreadsheet = service.getEntry(metafeedUrl, SpreadsheetEntry.class);
//Here we are working with worksheet 0, if you have multiple worksheet, then change this value to get the corresponding worksheet
URL listFeedUrl = ((WorksheetEntry) spreadsheet.getWorksheets().get(0)).getListFeedUrl();
// Creating a local representation of the new row.
ListEntry row = new ListEntry();
row.getCustomElements().setValueLocal("Name", user);
row.getCustomElements().setValueLocal("Credits", "0");
// Sending the new row for insertion into worksheet.
}
}
public class didbot extends PircBot {
public didbot() {
this.setName("didbot");
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
public class ClassExecutingTask {
long delay = 10 * 1000; // 600000 = 10 minutes
LoopTask task = new LoopTask();
Timer timer = new Timer("TaskName");
public void start() {
timer.cancel();
timer = new Timer("TaskName");
Date executionDate = new Date(); // no params = now
timer.scheduleAtFixedRate(task, executionDate, delay);
}
public void addCredits (String veiwer, int a){
}
private class LoopTask extends TimerTask {
public void run() {
//add credits here to add one credit every 10 minutes
//sendMessage(channel, sender + ", thank you for checking out the channel!");
// getUsers("");
}
}
}
#Override
public void onMessage(String channel, String sender, String login, String hostname, String message) {
/* if (message.equalsIgnoreCase("time")) {
String time = new java.util.Date().toString();
sendMessage(channel, sender + ": The time is now " + time);
}*/
if (message.contains("!songrequest ")) {
String songRequest = message.substring(13);
if (!songRequest.isEmpty()) {
try {
PrintStream srout = new PrintStream("C:/Users/songRequest.txt");
srout.println(songRequest);
System.out.println(songRequest);
srout.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}
}
#Override
protected void onJoin(String channel, String sender, String login, String hostname) {
//attempt to add new person to the spread sheet if they are not already listed.
//cells(0,0) (a,1)
try {
ss.addUser(sender);
}catch (IOException w) {
System.out.println(w);
}
catch (ServiceException q){
System.out.println(q);
}
// getUsers("");
}
}

How to display the login information in different layout?

I have created an application which needs sign in from Facebook/Twitter/Google to get started. In a layout I have created three switches each for Facebook, Twitter and Google which has options ON and OFF. I want to make the switch of the particular account as 'ON' if the user is logged in from that corresponding account. Example if the user is logged in from Facebook, only the switch beside Facebook should be ON. How can I do that?
Any suggestions would be appreciated, and also if somebody know then please refer me to any tutorial related to this.
Below is my code for the login page. I have shown the login for Facebook part:
Thanx :)
private OnClickListener loginButtonListener = new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick( View v ) {
String[] permissions = { "offline_access", "publish_stream", "user_photos", "publish_checkins","photo_upload" };
if(v.getId() == R.id.button1 )
{
facebookSwitch = true;
twitterSwitch = false;
googleSwitch = false;
if( !mFacebook.isSessionValid() ) {
Toast.makeText(Login.this, "Authorizing", Toast.LENGTH_SHORT).show();
mFacebook.authorize(Login.this, permissions, new LoginDialogListener());
}
else {
Toast.makeText( Login.this, "Has valid session", Toast.LENGTH_SHORT).show();
try {
JSONObject json = Util.parseJson(mFacebook.request("me"));
//Log.d("Login", "11111111111111111");
String facebookID = json.getString("id");
//Log.d("Login", "22222222222222");
String firstName = json.getString("first_name");
//Log.d("Login", "3333333333333333333");
String lastName = json.getString("last_name");
//Log.d("Login", "4444444444444444444444");
Toast.makeText(Login.this, "You already have a valid session, " + firstName + " " + lastName + ". No need to re-authorize.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login.this,MainActivity.class);
startActivity(intent);
}
catch( Exception error ) {
Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();
}
catch( FacebookError error ) {
Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
}
Try it this way....
- First create a Singleton Class with 3 booleanvariables for 3 logins info, and thereGetter-Setter`. Singleton is needed over here so that only One object of that class is formed no matter from where that class is called in the whole application. So now you have a single point of info.
- Always check Singleton Class's variables in the beginning of another Activity or when needed by you, to know that whether the user is logged into one or two or all the social networking sites.
////////////////////////////////Edited Part/////////////////////////////
A simple way of creating a Singleton is below, thought there are few more:
public class Test{
public static Test uniqueInstance = new Test();
private Test(){}
public static Test getInstance(){
return uniqueInstance;
// No matter what but always u will get the same instance.
}
}
Now To call this object in another class do as below...
public class Main{
Test t = Test.getInstance(); // Now use t to call the fields and methods of class T.
}

Categories

Resources