No login screen in Facebook integration in blackberry - facebook

I am working on an blackberry application in which I am using 3rd party application Facebook.
Now, my problem is when i post the message first time i will be redirected to facebook login screen and message posted .But once i logout from my application and login again to post message to facebook it posts message directly without asking for cerdential information.
The below code to login to facebook:
public class FacebookMain implements ActionListener{// extends MainScreen implements ActionListener {
// Constants
public final static String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
public final static String APPLICATION_ID ="261890490596037";
private final static long persistentObjectId = 0x854d1b7fa43e3577L;
//APPLICATION SECRET ID="f7e096af696ef81e72268f49a6381a8d"
static final String ACTION_ENTER = "updateStatus";
static final String ACTION_SUCCESS = "statusUpdated";
static final String ACTION_ERROR = "error";
private ActionScreen actionScreen;
private PersistentObject store;
private LoginScreen loginScreen;
private LogoutScreen logoutScreen;
private HomeScreen homeScreen;
private UpdateStatusScreen updateStatusScreen;
private RecentUpdatesScreen recentUpdatesScreen;
private UploadPhotoScreen uploadPhotoScreen;
private FriendsListScreen friendsListScreen;
private PokeFriendScreen pokeFriendScreen;
private PostWallScreen postWallScreen;
private SendMessageScreen sendMessageScreen;
private String postMessage;
private FacebookContext fbc;
public static boolean isWallPosted=false;
public FacebookMain(String postMessge) {
this.postMessage=postMessge;
checkPermissions();
init();
if ((fbc != null) && fbc.hasValidAccessToken()) {
/*homeScreen = new HomeScreen(fbc);
homeScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(homeScreen);*/
try {
new FBUser("me", fbc.getAccessToken()).setStatus(postMessage);
actionScreen=new ActionScreen();
actionScreen.fireAction(ACTION_SUCCESS);
Dialog.alert("Wall Posted ");
isWallPosted=true;
//UiApplication.getUiApplication().popScreen(loginScreen);
} catch (Exception e) {
actionScreen.fireAction(ACTION_ERROR, e.getMessage());
//UiApplication.getUiApplication().popScreen(loginScreen);
}
} else {
loginScreen = new LoginScreen(fbc,postMessge);
loginScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(loginScreen);
}
}
private void init() {
store = PersistentStore.getPersistentObject(persistentObjectId);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new FacebookContext(NEXT_URL, APPLICATION_ID));
store.commit();
}
}
fbc = (FacebookContext) store.getContents();
}
private void checkPermissions() {
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if ((original.getPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_INTERNET) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_EMAIL) == ApplicationPermissions.VALUE_ALLOW)) {
return;
}
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_AUTHENTICATOR_API);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_WIFI);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if (acceptance) {
// User has accepted all of the permissions.
return;
} else {
}
}
public void saveContext(FacebookContext pfbc) {
synchronized (store) {
store.setContents(pfbc);
System.out.println(pfbc);
store.commit();
}
}
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}
public void saveAndExit() {
saveContext(fbc);
exit();
}
private void exit() {
AppenderFactory.close();
System.exit(0);
}
public void onAction(Action event) {/*
if (event.getSource() == loginScreen) {
if (event.getAction().equals(LoginScreen.ACTION_LOGGED_IN)) {
try {
fbc.setAccessToken((String) event.getData());
try {
new FBUser("me", fbc.getAccessToken()).setStatus(postMessage);
actionScreen=new ActionScreen();
actionScreen.fireAction(ACTION_SUCCESS);
Dialog.alert("Wall Posted ");
} catch (Exception e) {
actionScreen.fireAction(ACTION_ERROR, e.getMessage());
}
try {
if (homeScreen == null) {
homeScreen = new HomeScreen(fbc);
homeScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(homeScreen);
} catch (Exception e) {
e.printStackTrace();
Dialog.alert("Error: " + e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
Dialog.alert("Error: " + t.getMessage());
}
} else if (event.getAction().equals(LoginScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == logoutScreen) {
if (event.getAction().equals(LogoutScreen.ACTION_LOGGED_OUT)) {
exit();
}
} else if (event.getSource() == homeScreen) {
if (event.getAction().equals(UpdateStatusScreen.ACTION_ENTER)) {
if (updateStatusScreen == null) {
updateStatusScreen = new UpdateStatusScreen(fbc);
updateStatusScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(updateStatusScreen);
try {
new FBUser("me", fbc.getAccessToken()).setStatus("");
actionScreen=new ActionScreen();
actionScreen.fireAction(ACTION_SUCCESS);
} catch (Exception e) {
actionScreen.fireAction(ACTION_ERROR, e.getMessage());
}
} else if (event.getAction().equals(RecentUpdatesScreen.ACTION_ENTER)) {
if (recentUpdatesScreen == null) {
recentUpdatesScreen = new RecentUpdatesScreen(fbc);
recentUpdatesScreen.addActionListener(this);
}
recentUpdatesScreen.loadList();
UiApplication.getUiApplication().pushScreen(recentUpdatesScreen);
} else if (event.getAction().equals(UploadPhotoScreen.ACTION_ENTER)) {
if (uploadPhotoScreen == null) {
uploadPhotoScreen = new UploadPhotoScreen(fbc);
uploadPhotoScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(uploadPhotoScreen);
} else if (event.getAction().equals(FriendsListScreen.ACTION_ENTER)) {
if (friendsListScreen == null) {
friendsListScreen = new FriendsListScreen(fbc);
friendsListScreen.addActionListener(this);
}
friendsListScreen.loadList();
UiApplication.getUiApplication().pushScreen(friendsListScreen);
} else if (event.getAction().equals(PokeFriendScreen.ACTION_ENTER)) {
if (pokeFriendScreen == null) {
pokeFriendScreen = new PokeFriendScreen(fbc);
pokeFriendScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(pokeFriendScreen);
} else if (event.getAction().equals(PostWallScreen.ACTION_ENTER)) {
if (postWallScreen == null) {
postWallScreen = new PostWallScreen(fbc);
postWallScreen.addActionListener(this);
}
postWallScreen.loadList();
UiApplication.getUiApplication().pushScreen(postWallScreen);
} else if (event.getAction().equals(SendMessageScreen.ACTION_ENTER)) {
if (sendMessageScreen == null) {
sendMessageScreen = new SendMessageScreen(fbc);
sendMessageScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(sendMessageScreen);
}
} else if (event.getSource() == updateStatusScreen) {
if (event.getAction().equals(UpdateStatusScreen.ACTION_SUCCESS)) {
Dialog.inform("Status updated");
try {
UiApplication.getUiApplication().popScreen(updateStatusScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(UpdateStatusScreen.ACTION_SUCCESS)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == recentUpdatesScreen) {
if (event.getAction().equals(RecentUpdatesScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(recentUpdatesScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(RecentUpdatesScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == uploadPhotoScreen) {
if (event.getAction().equals(UploadPhotoScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(uploadPhotoScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(UploadPhotoScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == friendsListScreen) {
if (event.getAction().equals(FriendsListScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(friendsListScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(FriendsListScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == pokeFriendScreen) {
if (event.getAction().equals(PokeFriendScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(pokeFriendScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(PokeFriendScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == postWallScreen) {
if (event.getAction().equals(PostWallScreen.ACTION_SUCCESS)) {
Dialog.inform("Wall posted");
try {
UiApplication.getUiApplication().popScreen(postWallScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(PostWallScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == sendMessageScreen) {
if (event.getAction().equals(SendMessageScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(sendMessageScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(SendMessageScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
}
*/}
}
and the below code to clear credential
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}

Related

DeveloperError Exception of type 'Google.GoogleSignIn+SignInException', googleplaystore, unity, google login?

I have weird behaviour for my SignInWithGoogle.
I have everything set up for QAuth, SSH, WebClieng etc.
And when I sent a build to my phone directly. All work fine. I can SignIn, LogIn etc.
But when I made an aab build and uploaded it to google console and downloaded it from GooglePlay, as a tester, I received DeveloperError Exception of type 'Google.GoogleSignIn+SignInException.
Is there maybe something I need to change on QAuth to fix that?
public class SignInWithGoogle : MonoBehaviour
{
public static string slaveUserEmail;
public static string slaveUserPassword;
string webClientId = "536446807232-vh3olku8c637olltqlge92p17qmsqmtl.apps.googleusercontent.com";
private GoogleSignInConfiguration configuration;
FirebaseAuth _auth;
bool _initialized = false;
void Awake()
{
FireBaseInit.OnInitialized += OnFirebaseInit;
configuration = new GoogleSignInConfiguration
{
WebClientId = webClientId,
RequestIdToken = true
};
}
public void OnFirebaseInit()
{
if (_initialized) return;
_auth = FirebaseAuth.DefaultInstance;
_initialized = true;
Debug.Log("GoogleAuth Initialized");
}
public void OnSignIn()
{
Debug.Log("Calling SignIn");
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
var signInCompleted = new TaskCompletionSource<FirebaseUser>();
Debug.Log("SignInInit");
try
{
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(task =>
{
if (task.IsFaulted)
{
using (IEnumerator<Exception> enumerator =
task.Exception.InnerExceptions.GetEnumerator())
{
if (enumerator.MoveNext())
{
GoogleSignIn.SignInException error =
(GoogleSignIn.SignInException)enumerator.Current;
Debug.Log("Got Error: " + error.Status + " " + error.Message);
}
else
{
Debug.Log("Got Unexpected Exception?!?" + task.Exception);
}
}
}
else if (task.IsCanceled)
{
Debug.Log("Canceled");
}
else
{
Debug.Log("Welcome in Google: " + task.Result.DisplayName + "!");
Debug.Log("GEt Ceds");
Credential credential = GoogleAuthProvider.GetCredential(task.Result.IdToken, null);
Debug.Log("Creds added");
Debug.Log("Firebase Log In try!");
FirebaseAuth.DefaultInstance.SignInWithCredentialAsync(credential).ContinueWith(authTask =>
{
if (authTask.IsCanceled)
{
Debug.Log("Auth Canceld");
signInCompleted.SetCanceled();
}
else if (authTask.IsFaulted)
{
Debug.Log("Auth Faulted");
signInCompleted.SetException(authTask.Exception);
}
else
{
Debug.Log("Auth Coplited");
signInCompleted.SetResult(((Task<FirebaseUser>)authTask).Result);
}
});
}
});
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
The full error:
Got Error: DeveloperError Exception of type 'Google.GoogleSignIn+SignInException' was thrown. <>c__DisplayClass8_0:b__0(Task`1) System.Threading.ThreadPoolWorkQueue:Dispatch()

file scheme for route.uri field

like this:
spring:
cloud:
gateway:
routes:
- id: static-file
uri: file:///data/pub/
predicates:
- Path=/file/**
Does it support?
I want to replace ResourceHandlerRegistry.addResourceHandler in this way.
My implementation is like this:
#Component
public class GlobalFileRoutingFilter implements GlobalFilter, Ordered {
private static final Log log = LogFactory.getLog(GlobalFileRoutingFilter.class);
private final DispatcherHandler dispatcherHandler;
public GlobalFileRoutingFilter(DispatcherHandler dispatcherHandler) {
this.dispatcherHandler = dispatcherHandler;
}
#Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
#Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
Route route = (Route)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
if (route == null) {
return chain.filter(exchange);
} else {
log.trace("GlobalFileRoutingFilter start");
URI routeUri = route.getUri();
String scheme = routeUri.getScheme();
if (isAlreadyRouted(exchange) || !"file".equals(scheme)) {
return chain.filter(exchange);
}
setAlreadyRouted(exchange);
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String filePath = routeUri.getPath() + File.separator + request.getURI().getPath();
if (log.isTraceEnabled()) {
log.trace("Reading from file: "+filePath);
}
if ("HEAD".equalsIgnoreCase(request.getMethod().toString())) {
response.getHeaders().set(HttpHeaders.ACCEPT_RANGES, "none");
} else {
File file = new File(filePath);
if (!file.exists()) {
response.setStatusCode(HttpStatus.NOT_FOUND);
} else {
DataBuffer dataBuffer = response.bufferFactory().allocateBuffer();
try {
dataBuffer.write(IOUtils.toByteArray(new FileInputStream(file)));
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error(e);
}
}
return response.writeAndFlushWith(Flux.just(Flux.just(dataBuffer)));
}
}
return Mono.empty();
}
}
}

In socket programming exe file memory increasing gradually and also socket remain open

When received sting from multiple client at time some socket remain open so created mis file size increasing gradually so at time exe file become 2 GB from 35 kb so how can i reduce open sockect
private void Server_Load(object sender, EventArgs e)
{
try
{
this.tcpListener = new TcpListener(IPAddress.Any, port);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
catch (Exception ex)
{ }
finally
{
if (this.tcpListener != null)
{
this.tcpListener.Stop();
}
}
}
Mangae Client request by server continuously from load method
private void ListenForClients()
{
TcpClient client = null;
try
{
this.tcpListener.Start();
while (true)
{
client = this.tcpListener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClientComm),
client);
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("ListenForClients: " + ex.Message);
this.tcpListener.Stop();
}
finally
{
if(this.tcpListener != null)
{
this.tcpListener.Stop();
}
if (client != null)
{
client.Close();
}
}
}
Take data from client and insert into table and mange pass tcpclient and networkstream with close connection
private void HandleClientComm(object client)
{
TcpClient tcpClient = null;
NetworkStream clientStream = null;
try
{
tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
string InsertedRecord = string.Empty;
byte[] messageBytes = new byte[4096];
int bytesRead;
bool end = false;
while (!end)
{
bytesRead = 0;
try
{
if (clientStream != null)
{
bytesRead = clientStream.Read(messageBytes, 0,
messageBytes.Length);
}
}
catch (SocketException ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
catch (Exception ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
if (bytesRead <= 0)
{
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
string Datareceived = encoder.GetString(messageBytes, 0, bytesRead);
if (!string.IsNullOrEmpty(Datareceived))
{
string[] Multistrings = Datareceived.Split('!');
for (int i = 0; i < Multistrings.Length; i++)
{
if (!string.IsNullOrEmpty(Multistrings[i]))
{
if (Multistrings[i].Length >= 90)
{
InsertedRecord = InsertRawData(Multistrings[i]);
}
else
{
InsertedRecord =
InsertRawDataGarbage(Multistrings[i]);
}
}
}
}
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("While loop: " + ex.Message);
}
finally
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
}
}

Chat not continue when reconnect with internet in SMACK

This is my code :
There is two condition is happening :
1.Not getting chat continued when i received pending message form other side:
2.When internet goes when i disconnecting the XMPP connection then pending message has not coming but chat will continued
public void init(String userId, String pwd) {
Log.i("XMPP", "Initializing!");
mPassword = DatabaseManager.Session.getClientPassword(this);
HOST = "xm3.conversity.net";
xMppUserName = DatabaseManager.Session.getXmppUserName(this);
xMppOnlyUserName = xMppUserName.split("#")[0];
agentId = DatabaseManager.Session.getAgentNameId(this);
PORT = DatabaseManager.Session.getPortNumber(this);
Log.e("xmpp", "mPassword:" + mPassword);
Log.e("xmpp", "HOST:" + HOST);
Log.e("xmpp", "xMppOnlyUserName:" + xMppOnlyUserName);
Log.e("xmpp", "xMppUserName:" + xMppUserName);
Log.e("xmpp", "agentId:" + agentId);
Log.e("xmpp", "PORT:" + String.valueOf(PORT));
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(xMppUserName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
configBuilder.setSendPresence(true);
configBuilder.setDebuggerEnabled(true);
configBuilder.setCompressionEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
// ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();
// connection.setPacketReplyTimeout(10000);
// PingManager.setDefaultPingInterval(600);
// PingManager.getInstanceFor(connection).registerPingFailedListener((PingFailedListener) this);
chatmanager = ChatManager.getInstanceFor(connection);
chatmanager.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, final Message message) {
Log.e("Xmpp", String.valueOf(chat) + " === " + message.toString() + "MESSAGE: " + message.getBody());
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
Log.e("Xmpp", "RECIVE MESSAGE: " + message.getBody() + message.getFrom() + "StanzaID: " + message.getBodies());
String[] strings = {message.getBody(), "2", Utility.getCurrentTime(), message.getThread(), "A", "6", "7", DatabaseManager.Message.START_CHAT, ""};
DatabaseManager.Message.insertValues(getApplicationContext(), strings);
Intent i = new Intent(ChatActivity.CHAT_BROADCAST);
i.putExtra(ChatActivity.KEY_ACTION, ChatActivity.NEW_MESSAGE);
getApplicationContext().sendBroadcast(i);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
// disconnectConnection();
}
}, 3000);
}
});
}
});
}
});
}
// Disconnect Function
public void disconnectConnection() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
Log.e("xmpp", "connection.disconnect();");
}
}).start();
}
public void connectConnection() {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
final ScheduledExecutorService scheduleTaskExecutor = Executors.newSingleThreadScheduledExecutor();
scheduleTaskExecutor.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
Log.d("xmpp", "inside run()");
Log.d("xmpp", "isconnect: " + connection.isConnected() + " Auth: " + connection.isAuthenticated());
/* if(!Utility.isNetworkAvailable(getApplicationContext())){
// disconnectConnection();
}
else */
if (connection.isConnected()) {
sendMessagesToServer();
} else {
try {
connection.connect();
login();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
}, 0, 2, TimeUnit.SECONDS);
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
private void sendMessagesToServer() {
try {
connection.sendPacket(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
// Log.e(TAG,"in side sendMessagesToServer()");
DatabaseManager dbManager = new DatabaseManager(this);
dbManager.open();
Cursor c = dbManager.getMessages();
while (c.moveToNext()) {
//Read the message details
String status = c.getString(DatabaseManager.Message.INDEX_STATUS);
// Log.e("PREM", status + String.valueOf(status.equalsIgnoreCase("P")));
if (status.equalsIgnoreCase("P")) {
String message = c.getString(DatabaseManager.Message.INDEX_MESSAGE);
String id = c.getString(0);
sendMsg(message);
dbManager.updateMessageStatus(id, jid);
}
}
c.close();
dbManager.close();
}
public void sendMsg(String message) {
if (connection.isConnected() == true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat(agentId);
try {
newChat.sendMessage(message);
jid = newChat.getThreadID();
Log.i("Xmpp", "message send to server");
Log.i("Xmpp", "thread: " + newChat.getThreadID() + " Listner: " + newChat.getListeners() + " participant" + newChat.getParticipant());
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(xMppOnlyUserName, DatabaseManager.Session.getClientPassword(this));
Log.i("Xmpp", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
your question is not clear, but from what I understood, you have to save the messages in sqlite database on android, and then load from database everytime you open the chat page

I am working with facebook game request

I finished working with sending the request with android reading https://developers.facebook.com/docs/howtos/androidsdk/3.0/send-requests/
but i'm having a problem with handling requests.
https://developers.facebook.com/docs/howtos/androidsdk/3.0/app-link-requests/
I think I did what it told me to do, but I can't get the uri and the requestid
they are all null.
I thing the problem is that when I receive a request I can't click the accept button.
It says that the playstore can't find the app. So the request doesn't disappear.
How can I solve the problem?
public class MainActivity extends Activity {
private static final List<String> PERMISSIONS = Arrays
.asList("read_requests");
private Bundle SIS;
private Session.StatusCallback logincallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
updateview();
getp();
loginlogoutbutton.setText("Login");
onSessionStateChange(session, state, exception);
} else {
}
}
};
public void updateview() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
tt.setText(user.getId());
}
}
});
} else
{
tt.setText("Login");
}
}
private Button loginlogoutbutton;
private Button sendrequestbutton;
private Button testbtn;
private TextView tt;
private String app_id = "APP ID";
private String requestId;
public void getp() {
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
return;
}
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS)
.setCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
}
}));
} else {
}
}
#Override
public void onResume() {
super.onResume();
checkforrequest();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SIS = savedInstanceState;
tt = (TextView) findViewById(R.id.tex);
loginlogoutbutton = (Button) findViewById(R.id.loginlogoutbtn);
loginlogoutbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLoginLogout();
}
});
sendrequestbutton = (Button) findViewById(R.id.sendrequest);
sendrequestbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendRequestDialog();
}
});
testbtn = (Button) findViewById(R.id.button1);
testbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
checkforrequest();
}
});
ConfirmLogin(app_id);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
public boolean ConfirmLogin(String iappid) {
app_id = iappid;
Session session = Session.getActiveSession();
boolean dd = true;
if (session == null) {
if (SIS != null) {
session = Session.restoreSession(this, null,
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
// TODO Auto-generated method stub
}
}, SIS);
}
if (session == null) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
dd = true;
} else {
dd = false;
}
}
return dd;
}
public void onClickLoginLogout() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else if (session.isClosed()) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else {
session.closeAndClearTokenInformation();
loginlogoutbutton.setText("Login");
}
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message",
"Learn how to make your Android apps social");
params.putString("data", "{\"badge_of_awesomeness\":\"1\","
+ "\"social_karma\":\"5\"}");
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
} else {
}
} else {
final String requestId = values
.getString("request");
if (requestId != null) {
maketoast(requestId);
} else {
}
}
}
}).build();
requestsDialog.show();
}
public void checkforrequest() {
maketoast("0");
Uri intentUri = this.getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
maketoast("1 : " +requestIdParam);
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
}
}
else
{
maketoast("uri = null");
}
}
public void maketoast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
maketoast("2");
Request request = new Request(Session.getActiveSession(), inRequestId,
null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the
// key/value info
JSONObject dataObject = new JSONObject(
(String) graphObject
.getProperty("data"));
// Get the value for the key -
// badge_of_awesomeness
String badge = dataObject
.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma = dataObject
.getString("social_karma");
// Get the sender's name
JSONObject fromObject = (JSONObject) graphObject
.getProperty("from");
String sender = fromObject
.getString("name");
String title = sender + " sent you a gift";
// Create the text for the alert based on
// the sender
// and the data
message = title + "\n\n" + "Badge: "
+ badge + " Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
maketoast(message);
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
// Check if the user is authenticated and
// an incoming notification needs handling
if (state.isOpened() && requestId != null) {
maketoast("3");
getRequestData(requestId);
requestId = null;
} else if (requestId == null) {
maketoast("4");
}
if (state.isOpened()) {
} else if (state.isClosed()) {
}
}
}
this is the code.