How to get real time inbox and notifications from Facebook SDK android - android

I am developing an application that when it opens it get inbox and facebook notifications. I am able to get inbox and notification messages from Facebook in my android application every minute using Alarm Manager. But this consumes a lot of battery of the smartphone. Is there a way to get notifications and inbox in real time so It doesn't have to be requesting every minute?
This is my code:
MainFragment class
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private Activity context;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private UiLifecycleHelper uiHelper;
private TextView InboxMessage,NotificationMessage,text1,text2;
private LoginButton authButton;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_login, container, false);
authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setPublishPermissions(Arrays.asList("manage_notifications"));
InboxMessage= (TextView) view.findViewById(R.id.InboxTextView);
NotificationMessage= (TextView) view.findViewById(R.id.NotificationsMessageTextView);
text1= (TextView) view.findViewById(R.id.textView1);
text2= (TextView) view.findViewById(R.id.textView2);
context=this.getActivity();
onClickNotifications();
return view;
}
private void onSessionStateChange(final Session session, final SessionState state, final Exception exception) {
if (state.isOpened()) {
final Calendar TIME = Calendar.getInstance();
am.setRepeating(AlarmManager.RTC,TIME.getTime().getTime(), 1000*60, pi);
} else {
Log.i(TAG, "Logged out...");
text1.setVisibility(View.INVISIBLE);
InboxMessage.setVisibility(View.INVISIBLE);
NotificationMessage.setVisibility(View.INVISIBLE);
text2.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
public void onClickNotifications(){
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
final Session session =Session.getActiveSession();
if(session.isOpened()){
String aaa=new String();
aaa="SELECT title_text,updated_time FROM notification WHERE recipient_id=me() AND is_unread=1";
Bundle params = new Bundle();
params.putString("q", aaa);
new Request(session,"/fql",params,HttpMethod.GET,new Request.Callback() {
public void onCompleted(Response response) {
try
{
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
String splitting=arr.toString().replaceAll("\\\\|\\{|\\}|\\[|\\]", "");
String[] arrayresponse=splitting.split("\\,");
String s = "";
for (int i = 0; i < arrayresponse.length; i++) {
if (arrayresponse[i].length()>13){
if (arrayresponse[i].substring(1,13).equals("updated_time"))
s+="* "+getDate(Long.valueOf(arrayresponse[i].substring(15,arrayresponse[i].length())))+"\n";
else
s+=" "+arrayresponse[i].substring(14,arrayresponse[i].length()-1)+"\n\n";
}
}
text2.setVisibility(View.VISIBLE);
NotificationMessage.setVisibility(View.VISIBLE);
NotificationMessage.setMovementMethod(new ScrollingMovementMethod());
NotificationMessage.setText(s);
readMailBox(session);
}catch ( Throwable t )
{
t.printStackTrace();
}
}
}
).executeAsync();
}
else{
NotificationMessage.setVisibility(View.INVISIBLE);
Log.i(TAG, "Logged out...");
}
}
};
this.getActivity().registerReceiver(br, new IntentFilter("com.authorwjf.wakeywakey") );
pi = PendingIntent.getBroadcast( this.getActivity(), 0, new Intent("com.authorwjf.wakeywakey"), 0 );
am = (AlarmManager)(this.getActivity().getSystemService( Context.ALARM_SERVICE ));
}
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
time=time*1000;
cal.setTimeInMillis(time);
return DateFormat.format("dd-MM-yyyy hh:mm:ss aa", cal).toString();
}
public void readMailBox(Session session){
String aaa=new String();
aaa="SELECT timestamp,sender,body FROM unified_message where thread_id in (select thread_id from unified_thread where folder = 'inbox') and unread=1";
Bundle params = new Bundle();
params.putString("q", aaa);
new Request(session,"/fql",params,HttpMethod.GET,new Request.Callback() {
public void onCompleted(Response response) {
try
{
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
String splitting=arr.toString().replaceAll("\\\\|\\{|\\}|\\[|\\]", "");
String[] arrayresponse=splitting.split("\\,");
String s = "";
for (int i = 0; i < arrayresponse.length; i++) {
if (arrayresponse[i].length()>10){
if (arrayresponse[i].substring(1,10).equals("timestamp"))
s+=getDate(Long.valueOf(arrayresponse[i].substring(13,arrayresponse[i].length()-4)))+"\n";
else if (arrayresponse[i].substring(1,5).equals("name"))
s+="* "+arrayresponse[i].substring(8,arrayresponse[i].length()-1)+"\n";
else if (arrayresponse[i].substring(1,5).equals("body"))
s+=arrayresponse[i].substring(7,arrayresponse[i].length())+"\n\n";
}
}
text1.setVisibility(View.VISIBLE);
InboxMessage.setVisibility(View.VISIBLE);
InboxMessage.setMovementMethod(new ScrollingMovementMethod());
InboxMessage.setText(s);
}catch ( Throwable t )
{
t.printStackTrace();
}
}
}
).executeAsync();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
uiHelper.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
Session session =Session.getActiveSession();
List<String> permissions = session.getPermissions();
if (!permissions.contains("read_mailbox")) {
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(context, Arrays.asList("read_mailbox"));
session.requestNewReadPermissions(newPermissionsRequest);
readMailBox(session);
} else {
readMailBox(session);
}
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
uiHelper.onDestroy();
am.cancel(pi);
this.getActivity().unregisterReceiver(br);
super.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
In another words my question is: Is there a way to keep listening to inbox and notifications and automatically get new messages instead of requesting every minute?

The best and perhaps the latest way of fetching notifications is to use FQL Facebook Query Language) and for your AGAIN WITHOUT OPENING APP part. You have to write your notification method in a service and the update it using some timer.I used Alarm Manager for that case.so that once you attain permission from the user to view his noifications, you can then continously fetch them in the background using the service. here is my method that I used to fetch notifications and then there conversion into json aswell.
public void onClickNotifications(){
Session session =Session.getActiveSession();
if(session.isOpened()){
// session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
String aaa=new String();
aaa="SELECT title_text FROM notification WHERE recipient_id=me() AND is_unread=1";
Bundle params = new Bundle();
params.putString("q", aaa);
new Request(
session,
"/fql",
params,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
try
{
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
for ( int i = 0; i < arr.length() ; i++ )
{
JSONObject json_obj = arr.getJSONObject( i );
adv.add(json_obj.getString( "title_text" ));
}
}
catch ( Throwable t )
{
t.printStackTrace();
}
}
}
).executeAsync();
}
else{
Toast.makeText(getApplicationContext(), "You are not logged in", Toast.LENGTH_LONG).show();
}
}

Related

How to get Facebook Friends list in android application

I want to get Facebook friends list in my android application (friend picker not required).I have followed the the procedure describe on Facebook application development
I have also run the samples , but confused to get the friends list. your suggestions will be appreciated.
you can get friend list with this code
String returnString = null;
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
for(int i=0;i<jArray.length();i++){
Log.i("log_tag","User Name: "+json_data.getString("name")+
", user_id: "+json_data.getString("id"));
returnString += "\n\t" + jArray.getJSONObject(i);
};
flist.setText(returnString);
progressDialog.dismiss();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
I get just name and id , if you want get different things,
public class MainActivity extends FragmentActivity implements OnClickListener {
private static final String LOGTAG = "MainActivity";
private List<GraphUser> tags;
private Button pickFriendsButton;
Button locationtoast;
private ProfilePictureView profilePictureView;// 2
private LoginButton fb_loginBtn;// loginbtn
private TextView userName, userName2, userName3, userName4, text;
private UiLifecycleHelper uiHelper;
// private Button pickFriendsButton;
Button btnlogin;
String Name;
String Id;
String lastname;
String firstname;
String getUsername;
String get_gender;
GraphPlace location;
String profileid;
String birthday;
String get_email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationtoast = (Button) findViewById(R.id.location_button);
locationtoast.setOnClickListener(this);
btnlogin = (Button) findViewById(R.id.profile_view);
btnlogin.setOnClickListener(this);
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);// 3
text = (TextView) findViewById(R.id.text);
userName = (TextView) findViewById(R.id.user_name);
fb_loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
pickFriendsButton = (Button) findViewById(R.id.add_friend);
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
pickFriendsButton.setEnabled(enableButtons);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void showPickerFragment(FriendPickerFragment fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment,
FacebookException error) {
String text = getString(R.string.exception,
error.getMessage());
Toast toast = Toast.makeText(MainActivity.this, text,
Toast.LENGTH_SHORT);
toast.show();
}
});
}
private void setFriendPickerListeners(
final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(
PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
List<GraphUser> selection = fragment.getSelection();
tags = selection;
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
// showAlert("fghjklkbvbn", results);
showAlert(getString(R.string.you_picked), results);
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(MainActivity.this).setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null).show();
}
});
fb_loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
// Intent intent = new Intent(this, ValuesShow.class);
// startActivity(i);
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
profilePictureView.setProfileId(user.getId());// 4
userName.setText("Hello , " + user.getName()
+ "\n you logged In Uaar Alumni ");
// userName2.setText("frstname"+ user.getFirstName());
// userName3.setText("address"+user.getBirthday());
// userName4.setText("texr"+user.getLocation());
get_email = (String) user.getProperty("email");
Name = user.getName();
Id = user.getId();
lastname = user.getLastName();
firstname = user.getFirstName();
getUsername = user.getUsername();
location = user.getLocation();
get_gender = (String) user.getProperty("gender");
// birthday=user.getBirthday();
// profileid=user.getId();
// profilePictureView.setProfileId(Id.getId());
// text.setText(Name + " \n " + Id + "\n" + firstname +
// "\n"
// + lastname + "\n" + getUsername + "\n" + get_gender);
// profilePicture=user.getId();
} else {
userName.setText("You are not logged");
}
}
});
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
text.setText("");
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = null;
switch (v.getId()) {
// case R.id.fb_login_button:
case R.id.location_button:
i = new Intent(this, LocationGet.class);
break;
// i=new Intent (this,Main_menu.class);
// break;
case R.id.profile_view:
i = new Intent(this, ValuesShow.class);
Log.d(Name, "" + Name);
i.putExtra("Name", Name);
i.putExtra("get_gender", get_gender);
i.putExtra("lastname", lastname);
i.putExtra("firstname", firstname);
i.putExtra("Id", Id);
i.putExtra("birthday", birthday);
i.putExtra("get_email", get_email);
// i.putExtra("profileid",profileid);
break;
}
// profilePictureView.setProfileId(user.getId());
// Intent intent = new Intent(this, ValuesShow.class);
// intent.getBooleanExtra("location", location);
Log.d(lastname, "" + lastname);
Log.d(get_gender, "" + get_gender);
// Log.d(LOGTAG,"Name value name....");
startActivity(i);
}
}

Quickblox android sdk groupchat

I'm using quickblox sdk group chat.
This is my code. But I still wrong. Can anybody guide me, please?
UserListForGroupActivity.java
public class UserListForGroupActivity extends Activity implements QBCallback {
private ListView usersList;
private ProgressDialog progressDialog;
private Button btnChat;
private SimpleAdapter usersAdapter;
private ArrayList<Friend_Users> friends= new ArrayList<Friend_Users>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list_for_group);
usersList = (ListView) findViewById(R.id.usersList);
btnChat=(Button)findViewById(R.id.btnstartGroupChat);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading fiends list");
progressDialog.show();
// ================= QuickBlox ===== Step 4 =================
// Get all users of QB application.
QBUsers.getUsers(this);
}
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
if (progressDialog != null) {
progressDialog.dismiss();
}
// Cast 'result' to specific result class QBUserPagedResult.
QBUserPagedResult pagedResult = (QBUserPagedResult) result;
final ArrayList<QBUser> users = pagedResult.getUsers();
System.out.println(users.toString());
// Prepare users list for simple adapter.
ArrayList<Map<String, String>> usersListForAdapter = new ArrayList<Map<String, String>>();
for (QBUser u : users) {
Map<String, String> umap = new HashMap<String, String>();
umap.put("userLogin", u.getLogin());
umap.put("chatLogin", QBChat.getChatLoginFull(u));
usersListForAdapter.add(umap);
}
// Put users list into adapter.
usersAdapter = new SimpleAdapter(this, usersListForAdapter,
android.R.layout.simple_list_item_multiple_choice,
new String[]{"userLogin", "chatLogin"},
new int[]{android.R.id.text1, android.R.id.text2});
usersList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
usersList.setAdapter(usersAdapter);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checked= usersList.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
{
QBUser friendUser = users.get(position);
String login, password;
int id;
id=friendUser.getId();
login=friendUser.getLogin();
password=friendUser.getPassword();
friends.add(new Friend_Users(id,login, password));
}
}
Friend_Users_Wrapper wrapper= new Friend_Users_Wrapper(friends);
Log.e("UserListForGroupAcitvity friend list pass intent=>", friends.size()+ friends.get(0).getLogin());
Bundle extras = getIntent().getExtras();
Intent intent=new Intent(UserListForGroupActivity.this, GroupChatActivity.class);
intent.putExtra("friends", wrapper);
intent.putExtras(extras);
startActivity(intent);
}
});
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Error(s) occurred. Look into DDMS log for details, " +
"please. Errors: " + result.getErrors()).create().show();
}
}
#Override
public void onComplete(Result result, Object context) { }
}
GroupChatActivity.java
public class GroupChatActivity extends Activity {
private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
private QBUser me;
private GroupChatController groupChatController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
// Load QBUser objects from bundle (passed from previous activity).
Bundle extras = getIntent().getExtras();
Friend_Users_Wrapper wrapper= (Friend_Users_Wrapper) getIntent().getSerializableExtra("friends");
ArrayList<Friend_Users> friendArray= wrapper.getFriend_Users();
me = new QBUser();
me.setId(extras.getInt("myId"));
me.setLogin(extras.getString("myLogin"));
me.setPassword(extras.getString("myPassword"));
System.out.println("user login =>"+extras.getString("myLogin"));
QBUser friends= new QBUser();
for (Friend_Users friend_Users : friendArray) {
friends.setId(friend_Users.getId());
friends.setLogin(friend_Users.getLogin());
friends.setPassword(friend_Users.getPassword());
}
// UI stuff
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
sendMessageButton.setOnClickListener(onSendMessageClickListener);
messageText = (EditText) findViewById(R.id.messageEdit);
// ================= QuickBlox ===== Step 5 =================
// Get chat login based on QuickBlox user account.
// Note, that to start chat you should use only short login,
// that looks like '17744-1028' (<qb_user_id>-<qb_app_id>).
String chatLogin = QBChat.getChatLoginShort(me);
// Our current (me) user's password.
String password = me.getPassword();
if (me != null && friends != null) {
// ================= QuickBlox ===== Step 6 =================
// All chat logic can be implemented by yourself using
// ASMACK library (https://github.com/Flowdalic/asmack/downloads)
// -- Android wrapper for Java XMPP library (http://www.igniterealtime.org/projects/smack/).
groupChatController = new GroupChatController(chatLogin, password);
groupChatController.setOnMessageReceivedListener(onMessageReceivedListener);
// ================= QuickBlox ===== Step 7 =================
// Get friend's login based on QuickBlox user account.
// Note, that for your companion you should use full chat login,
// that looks like '17792-1028#chat.quickblox.com' (<qb_user_id>-<qb_app_id>#chat.quickblox.com).
// Don't use short login, it
String friendLogin = QBChat.getChatLoginFull(friends);
groupChatController.startChat(friendLogin);
}
}
private void sendMessage() {
if (messageText != null) {
String messageString = messageText.getText().toString();
groupChatController.sendMessage(messageString);
messageText.setText("");
showMessage(me.getLogin() + " (me) : "+messageString, true);
}
}
private GroupChatController.OnMessageReceivedListener onMessageReceivedListener = new GroupChatController.OnMessageReceivedListener() {
#Override
public void onMessageReceived(final Message message) {
String messageString = message.getBody();
showMessage(messageString, false);
}
};
private void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(GroupChatActivity.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
#Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
private View.OnClickListener onSendMessageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
};
}
GroupChatController.java
public class GroupChatController {
// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();
private XMPPConnection connection;
private ConnectionConfiguration config;
private Chat chat;
// Multi-User Chat
private MultiUserChat muc2;
private String chatLogin;
private String password;
private String friendLogin;
private ChatManager chatManager;
public GroupChatController(String chatLogin, String password) {
this.chatLogin = chatLogin;
this.password = password;
}
public void startChat(String buddyLogin) {
this.friendLogin = buddyLogin;
new Thread(new Runnable() {
#Override
public void run() {
// Chat action 1 -- create connection.
Connection.DEBUG_ENABLED = true;
config = new ConnectionConfiguration(CHAT_SERVER);
connection = new XMPPConnection(config);
try {
connection.connect();
connection.login(chatLogin, password);
// Chat action 2 -- create chat manager.
chatManager = connection.getChatManager();
// Chat action 3 -- create chat.
chat = chatManager.createChat(friendLogin, messageListener);
// Set listener for outcoming messages.
chatManager.addChatListener(chatManagerListener);
// Muc 2
if(connection != null){
muc2 = new MultiUserChat(connection, "2389_chat1#muc.chat.quickblox.com");
// Discover whether user3#host.org supports MUC or not
// The room service will decide the amount of history to send
muc2.join(chatLogin);
muc2.invite(friendLogin, "Welcome!");
Log.d("friendLogin ->",friendLogin);
// Set listener for outcoming messages.
//chatManager.addChatListener(chatManagerListener);
muc2.addMessageListener(packetListener);
addListenerToMuc(muc2);
//chat1#muc.chat.quickblox.com
}
Message message = new Message(friendLogin + "#muc.chat.quickblox.com");
message.setBody("Join me for a group chat!");
message.addExtension(new GroupChatInvitation("2389_chat1#muc.chat.quickblox.com"));
connection.sendPacket(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
/*** muc */
private void addListenerToMuc(MultiUserChat muc){
if(null != muc){
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Log.i("processPacket", "receiving message");
}
});
}
}
PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message)packet;
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
//System.out.println("got message " + message.toXML());
}
};
private PacketInterceptor packetInterceptor = new PacketInterceptor() {
#Override
public void interceptPacket(Packet packet) {
System.out.println("Sending message: " + packet.toString());
Message message = muc2.createMessage();
message.setBody("Hello from producer, message " +
" ");
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
/***/
private ChatManagerListener chatManagerListener = new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
// Set listener for incoming messages.
chat.addMessageListener(messageListener);
muc2.addMessageListener(packetListener);
}
};
public void sendMessage(String message) {
try {
if (chat != null) {
chat.sendMessage(message);
}
if (muc2 != null) {
muc2.sendMessage(message);
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
private MessageListener messageListener = new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
// 'from' and 'to' fields contains senders ids, e.g.
// 17792-1028#chat.quickblox.com/mac-167
// 17744-1028#chat.quickblox.com/Smack
String from = message.getFrom().split("#")[0];
String to = message.getTo().split("#")[0];
System.out.println(String.format(">>> Message received (from=%s, to=%s): %s",
from, to, message.getBody()));
if (onMessageReceivedListener != null) {
onMessageReceivedListener.onMessageReceived(message);
}
}
};
public static interface OnMessageReceivedListener {
void onMessageReceived(Message message);
}
// Callback that performs when device retrieves incoming message.
private OnMessageReceivedListener onMessageReceivedListener;
public OnMessageReceivedListener getOnMessageReceivedListener() {
return onMessageReceivedListener;
}
public void setOnMessageReceivedListener(OnMessageReceivedListener onMessageReceivedListener) {
this.onMessageReceivedListener = onMessageReceivedListener;
}
}
public void startChat(String buddyLogin) {
...
List<String> usersLogins= new ArrayList<String>();
for(String userLogin: usersLogins){
muc2.invite(userLogin, "Welcome!");
}
...
}

Android TextView doesn't update

I am developing an Android app. Please see the Java code below. Can you please explain why textView doesn't update at specific lines in code but updates at others. I have them commented in the code.
I have updated the code see below.
The idea is to get a facebook profile from a server. When profiling_status equals 2 means that the profile is not ready, so I'll just ping the server until I get profiling_status != 2..
I tried the progress dialog thingy but gave up cause I put my activity in a thread, but then I couldn't get some information because I should have run it in nonUIThread.. Tried that but I failed and I lost patience.. so decided that while I ping the server I should just print "Loading profile. Please wait." No mess, no fuss! Only as said, textView doesn't update. Interestingly enough.. System.out.println("Here"); gets executed. I am running it only on AVD at the moment cause the server is not on the wireless network so I can't use a mobile phone to test it.
public class SelectionFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView userNameView;
private UiLifecycleHelper uiHelper;
private static final int REAUTH_ACTIVITY_CODE = 100;
private TextView textView;
private String username = null;
Context context;
JSONObject json = null;
JSONObject json_facebook = null;
int time = 0;
int time_interval = 3000;
int profiling_status = 2;
String logincode;
String usermessage = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void deleteProfile() throws JSONException {
IDThiefHTTPRequest.deleteProfile();
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
//Facebook logout
Session session2 = Session.getActiveSession();
if (session2 != null) {
session2.close();
}
else {
session2 = new Session(context);
Session.setActiveSession(session2);
session2.close();
}
}
private String readRiskScoreArray(JSONArray json_riskscore) throws NumberFormatException, JSONException{
//get the risk score with only two digits
double risk_score = Double.valueOf(json_riskscore.get(0).toString());
String risk_score2digits = new DecimalFormat("##.##").format(risk_score);
String usermessage = "Your risk score is: ";
usermessage = usermessage + risk_score2digits;
usermessage = usermessage + " which is ranked as: ";
usermessage = usermessage + json_riskscore.get(2).toString();
JSONArray json_reasons = json_riskscore.getJSONArray(1);
for (int i = 0; i < json_reasons.length(); i++){
JSONArray json_reason = json_reasons.getJSONArray(i);
JSONArray json_reasondetails = json_reason.getJSONArray(1);
usermessage = usermessage + "\n\nReason: ";
usermessage = usermessage + json_reasondetails.get(0);
usermessage = usermessage + "\n\nIDThief suggests you to: ";
usermessage = usermessage + json_reasondetails.get(1);
usermessage = usermessage + "\n\nFix it through this link:\n";
usermessage = usermessage + json_reasondetails.get(2);
}
return usermessage;
}
private void displayProfileInfo() throws JSONException {
Session session = Session.getActiveSession();
if (session.isOpened()) {
System.out.println(session.getAccessToken());
}
if (username != null) {
System.out.println("Login stage: Getting profile info for user:" + username);
logincode = username + "!" + session.getAccessToken();
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
System.out.println(json.toString(4));
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
if (profiling_status == 2) {
try {
while (profiling_status == 2 && time < 100000) {
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText("Loading profile. Please wait.");
System.out.println("Here");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
}
if (time >= 100000) {
System.out.println("Time is out");
textView.setText("Server is not responding. Please try again later.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
JSONArray json_riskscore = json_facebook.getJSONArray("risk_score");
System.out.println(json_riskscore.toString(4));
usermessage = readRiskScoreArray(json_riskscore);
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText(usermessage);
}
else System.out.println("username is null");
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection,
container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button deletebutton = (Button) view.findViewById(R.id.ImageButton2);
deletebutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
deleteProfile();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Button button = (Button) view.findViewById(R.id.ImageButton1);
textView = (TextView) view.findViewById(R.id.profiletext);
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setMovementMethod(LinkMovementMethod.getInstance());
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
displayProfileInfo();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
// Check for an open session
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
return view;
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
username = user.getUsername();
//System.out.println("Log in=====================================");
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
makeMeRequest(session);
}
else if (session != null && session.isClosed()) {
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
}
I thing your username is a string . Normally it will be so use !username.equals() dont use != in string comparison. that code may not get executed
if (username != null || !username.equals("")) {
//to do
}
Try out as below to compare the string do not use == use equalsIgnoreCase() or equals() method.
if (profiling_status.equalsIgnoreCase("2")) {
//would not update here either
try {
while (profiling_status.equalsIgnoreCase("2") && time < 100000) {
textView.setText("Loading profile. Please wait.");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
e.printStackTrace();
}

Android: how to get spinner value and check the condition

In my app i have a spinner with two items ..i have to choose the item an do action accordingly
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String Comment = edittext.getText().toString();
String choose = spinner.getSelectedItem()
.toString();
if (Comment != null && Comment.equalsIgnoreCase("")){
post(Comment,choose);
getActivity().finish();
}else{
showToast("Please enter you comment!");
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
} catch (Exception e) {
e.printStackTrace();
getActivity().finish();
}
}
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
-----------------> if(spinner.getSelectedItem().toString().equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
private void publishStory(Bundle postParams,final String comments,final String choose) {
Session session = Session.getActiveSession();
if (session != null){
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Request.Callback callbackRequest= new Request.Callback() {
public void onCompleted(Response response) {
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else
new fbUtils(activity).share(Data, comments, response.getError(),choose);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
};
Request request = new Request(session, Constants.fb.fbId + "/comments", postParams,
HttpMethod.POST, callbackRequest);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
the issue is the post() is not executing when clicking the dailogbutton its going into else part, i want to execute the if condition in post() method, Any help is appreciated
As you are getting the value from the spinner. The value may not be updated one .
You should use item-selected listeners.
String result="";
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
// Your variable should update here
result = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Now use that value in onPost method as:
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
Log.v("TEST",spinner.getSelectedItem().toString());
-----------------> if(result.equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
Try like this:
private Spinner status;
status = (Spinner) findViewById(R.id.status);
final ArrayList<Simplestatus> statusList = new ArrayList<Simplestatus>();
Simplestatus tempstatus = new Simplestatus();
tempstatus.setSimpleStatusName("ZERO");
tempstatus.setSimpleStatusValue("0");
Simplestatus tempstatus1 = new Simplestatus();
tempstatus1.setSimpleStatusName("ONE");
tempstatus1.setSimpleStatusValue("1");
statusList.add(tempstatus);
statusList.add(tempstatus1);
SpinnerAdapter stateAdaptor = new SpinnerAdapter(SettingActivity.this,statusList);
// stateList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
status.setAdapter(stateAdaptor);
status.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
changeStatus(statusList.get(position));
selected = statusList.get(position).getsimpleStatusName();
System.out.println("selected"+selected);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
public class Simplestatus
{
private String simpleStatusName;
private String simpleStatusValue;
public String getSimpleStatusName()
{
return simpleStatusName;
}
public void setSimpleStatusName(String simpleStatusName)
{
this.simpleStatusName = simpleStatusName;
}
public String getsimpleStatusValue()
{
return simpleStatusValue;
}
public void setsimpleStatusValue(String simpleStatusValue)
{
this.simpleStatusValue = simpleStatusValue;
}
}

error code 3 unknown method in android facebook app during post message on wall

Hello I am trying to post a message on wall, using this code.
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("message", "Facebook Dialogs are easy!");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(),null);
But i am getting this error.
Response: {"error_code":3,"error_msg":"Unknown method","request_args":[{"key":"message","value":"Facebook Dialogs are easy!"},{"key":"method","value":"POST"},{"key":"access_token","value":"AAAFby43GVwgBAJctMak5Y6IOaMylCWOFAXfXvsbMrckgZCi5wBZBSFWu02J1OY9ZB9aFLnwghHE72DgKe0YKIqctc5K54uyrA5mO5X2vQZDZD"},{"key":"format","value":"json"}]}
Thanks bro..i tried this but still doesnt works
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("Message Test", new SampleUploadListener());
Here again i am getting error...
GET URL: https://graph.facebook.com/Message Test?access_token=AAAFby43GVwgBAJctMak5Y6IOaMylCWOFAXfXvsbMrckgZCi5wBZBSFWu02J1OY9ZB9aFLnwghHE72DgKe0YKIqctc5K54uyrA5mO5X2vQZDZD&format=json 02-13 16:42:36.027: V/webview(13218): ZoomScale 3 mPreserveZoom: false 02-13 16:42:37.085: D/Facebook-Example(13218): Response: 400 Bad RequestMethod Not ImplementedInvalid method in request
02-13 16:42:37.085: W/Facebook-Example(13218): JSON Error in response
see following coding
public class UpdateStatusResultDialog extends Dialog { private Bundle values;
private TextView mOutput, mUsefulTip;
private Button mViewPostButton, mDeletePostButton;
private Activity activity;
private Handler mHandler;
public UpdateStatusResultDialog(Activity activity, String title, Bundle values) {
super(activity);
this.activity = activity;
this.values = values;
setTitle(title);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.update_post_response);
LayoutParams params = getWindow().getAttributes();
params.width = LayoutParams.FILL_PARENT;
params.height = LayoutParams.FILL_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
mOutput = (TextView) findViewById(R.id.apiOutput);
mOutput.setText(values.toString());
mUsefulTip = (TextView) findViewById(R.id.usefulTip);
mUsefulTip.setMovementMethod(LinkMovementMethod.getInstance());
mViewPostButton = (Button) findViewById(R.id.view_post_button);
mDeletePostButton = (Button) findViewById(R.id.delete_post_button);
final String postId = values.getString("post_id");
mViewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Source tag: view_post_tag
*/
Utility.mAsyncRunner.request(postId, new WallPostRequestListener());
}
});
mDeletePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Source tag: delete_post_tag
*/
Utility.mAsyncRunner.request(postId, new Bundle(), "DELETE",
new WallPostDeleteListener(), null);
}
});
}
public class WallPostRequestListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
try {
JSONObject json = new JSONObject(response);
setText(json.toString(2));
} catch (JSONException e) {
setText(activity.getString(R.string.exception) + e.getMessage());
}
}
public void onFacebookError(FacebookError error) {
setText(activity.getString(R.string.facebook_error) + error.getMessage());
}
}
public class WallPostDeleteListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
if (response.equals("true")) {
String message = "Wall Post deleted" + "\n";
message += "Api Response: " + response;
setText(message);
} else {
setText("wall post could not be deleted");
}
}
public void onFacebookError(FacebookError error) {
setText(activity.getString(R.string.facebook_error) + error.getMessage());
}
}
public void setText(final String txt) {
mHandler.post(new Runnable() {
#Override
public void run() {
mOutput.setText(txt);
}
});
}
}

Categories

Resources