Hi I am using smack api to build a chat application in android. I am displaying all my buddy list names in a page. I need to edit the buddy name of a particular buddy. When I long press a purticular buddy, I am displaying a new screen where there is an EditText to enter the new name and when an edit button is there. When I press the edit button I am calling the following button to edit the buddy name.
public boolean editName(String jid, String name) {
try {
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
RosterPacket.Item item = new RosterPacket.Item(jid, name);
packet.addRosterItem(item);
connection.sendPacket(packet);
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
Then the edit page is closed and the buddy list is refreshed. But the new name is not reflected unless i relogin to the application.
I am loading the buddy list using the following code:
public static Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
Log.i("XMPPChat", "Name: " + entry.getName());
}
Can anybody tell me the reason?
Related
I am creating an simple one to one chat app, I've done with the message send and receive. Now I am trying to show the status of the user to another(contacts) like "online/offline" etc. For that I have to use Presence and Roster.But I don't know where and how to use that, I mean the complete flow of subscription request and accept and after the subscription, the status of the users i.e. Online/Offline etc.
First of all you need to send and accept contact request
From Open-fire you can also do it from back-end
Steps :
First click on Users/Groups >> click on "UserName" >> click on roster >> add roster
Here i attach screen of steps
click on add new item
add roster
edit roster and select subscription both
then after you will get roster list using this code
ArrayList<RosterEntry> rosterLists = new ArrayList<>();
public List<RosterEntry> getFriendsList() throws SmackException.NotLoggedInException, InterruptedException, SmackException.NotConnectedException {
rosterLists = new ArrayList<>();
roster = Roster.getInstanceFor(Config.conn1);//connection object of AbstractXMPPConnection
if (!roster.isLoaded()) {
roster.reloadAndWait();
Log.e("Roster :", "Reload and wait");
}
Collection<RosterEntry> entries = roster.getEntries();
Log.e("Size of Roster :", entries.size() + "");
for (RosterEntry entry : entries) {
rosterLists.add(entry);
Log.d("Buddies", "Here: " + entry.toString());
Log.d("Buddies", "User: " + entry.getUser());//get userinfo
Log.d("Buddies", "User Name:" + entry.getName());//get username
Log.d("Buddies", "User Status: " + entry.getStatus());//get status of user
}
listAdapter = new FriendUserListAdapter(UserListActivity.this, rosterLists);
user_list.setAdapter(listAdapter);
return rosterLists;
}
what is the difference between subscription type both and from???
When any user add bot has his/her contact, then in the end of whole process, subscription status of ofRoster(openfire) table is set to ‘from’. The desired result of this process is ‘both’
I am working on a chatting application in which i can send messages , images , videos etc
i have done this in one to one chat also fulfill it in group chat .
But the issue is :-
I have to always join the each group everytime i login otherwise i am not been able to recieve message from different groups .
here is the way i join group each time .
MultiUserChat muc= new MultiUserChat(mConnection,"hsjsmqb#conference.11.111.111.111");
String userNAme ="222222222";
muc.join(userNAme);
if i do not join group everytime i do not recieve messages .
if i join group i started recieving messages .
My Question is is this the only solution or all group chatting works this way.
or am i doing some thing wrong
i googled but did not find any solution .
if it is duplicate question or any answer related to my question please share the link
thanks
This is the code :-
public boolean createChatRoom() {
String name = edtGroupName.getText().toString();
if (!(connection.isConnected() && name.length() != 0)) {
return false;
}
try {
// Create a MultiUserChat
String userName = Utils.covertIntoSubString(connection.getUser(), Constant.AT);
roomName = (name + md5String(getDateTime()) + userName + Constant.CONFERENCE + connection.getServiceName()).replaceAll(" ", "");
MultiUserChat muc = new MultiUserChat(connection, roomName);
// Create a chat room
muc.create(roomName);
// set Room Name as room subject
muc.changeSubject(name);// RoomName room name
// To obtain the chat room configuration form
Form form = muc.getConfigurationForm();
// Create a new form to submit the original form according to the.
Form submitForm = form.createAnswerForm();
// To submit the form to add a default reply
for (Iterator<FormField> fields = form.getFields(); fields
.hasNext(); ) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType())
&& field.getVariable() != null) {
// Set default values for an answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
// Set the chat room of the new owner
List<String> owners = new ArrayList<String>();
owners.add(connection.getUser());// The user JID
// submitForm.setAnswer("muc#roomconfig_roomowners", owners);
// Set the chat room is a long chat room, soon to be preserved
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
// chat room is public
submitForm.setAnswer("muc#roomconfig_publicroom", true);
// Allows the user to modify the nickname
submitForm.setAnswer("x-muc#roomconfig_canchangenick", true);
// Allows the possessor to invite others
// submitForm.setAnswer("muc#roomconfig_allowinvites", true);
// submitForm.setAnswer("muc#roomconfig_enablelogging", true);
// Only allow registered nickname log
// submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
// Allows the user to register the room
// submitForm.setAnswer("x-muc#roomconfig_registration", true);
muc.sendConfigurationForm(submitForm);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void inviteFriends(String userJid) {
try {
String groupName = edtGroupName.getText().toString();
Message msg = new Message();
msg.setBody(groupName);
MultiUserChat muc = new MultiUserChat(connection, roomName);
if (muc != null) {
muc.grantMembership(userJid);
muc.invite(msg, userJid, groupName);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void invitationrecvd(){
MultiUserChat chatRoom = new MultiUserChat(con, rum);
try {
chatRoom.join(userName);
saveGroupsToDb(userName + Constant.AT + Constant.HOST + Constant.SLASHSMACK, rum, group);
} catch (Exception e) {
e.printStackTrace();
}
}
And This is the group message Listener on home screen
PacketFilter filter = new MessageTypeFilter(Message.Type.groupchat);
groupMessagesListeners = new GroupMessagesListeners();
mConnection.addPacketListener(groupMessagesListeners,filter);
The groupchat is addressed to a XMPP muc (multi user chat) so you would need to join the muc in order to receive messages sent in that particular group. You can read more about this in https://xmpp.org/extensions/xep-0045.html.
Here is an excerpt from the link:
7.2.1 Groupchat 1.0 Protocol
In order to participate in the discussions held in a multi-user chat
room, a user MUST first become an occupant by entering the room. In
the old groupchat 1.0 protocol, this was done by sending presence with
no 'type' attribute to , where "room" is the room
ID, "service" is the hostname of the chat service, and "nick" is the
user's desired nickname within the room:
More or less I already had answered this kind of answer, but your code it's much cleaner (Can't able to receive group chat messages using smack-android:4.1.4).
1) When you create a multiuserchat, to finalize it you must JOIN this chat or the room it's just configurated but not still active.
muc.sendConfigurationForm(submitForm);
muc.join("My Nickname","password"); //omit password if not needed
2) To automatically join your groupchats, you can use PubSub feature
A snippet with Smack can looks like:
BookmarkManager bookmarkManager = BookmarkManager.getBookmarkManager(mConnection);
bookmarkManager.addBookmarkedConference
("My roomname label",
roomName,
true,
"My Nickname",
password);
add this code when:
you create a groupchat
you accept an groupchat's invitation.
(To remove a bookmark, just:
this.bookmarkManager.removeBookmarkedConference(roomName)
)
Finally, after login, add a method to autojoin the groupchat:
List<BookmarkedConference> list = BookmarkManager.getBookmarkManager(mConnection).getBookmarkedConferences();
MultiUserChat muc;
for (BookmarkedConference conference : list)
{
System.out.println("- Conference with bookmark: " + conference.getName() +
" and jid: " + conference.getJid());
if ( (muc = multiUserChatManager.getMultiUserChat(conference.getJid()) ) != null
&& conference.isAutoJoin())
{
muc.join("My Nickname");
//foo
}
}
After this you have all to config and manage your groupchats. Personally I don't like to add to mConnection a generic PacketListener due to the consequent difficoulty to synchronyze messages receveid with front end, but this will be eventually another branch.
I am writing a chat application. On click of a button I am trying to remove selected friend from list And its working properly but on removing the friend the UI is not getting updated
private void removeFriend(String remfri) {
removefri = remfri;
{
try {
Constants.connection.getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
Constants.connection.getRoster().createEntry(removefri, removefri, null);
Collection<RosterEntry> entries = Constants.connection.getRoster().getEntries();
for (RosterEntry entry : entries)
{
System.out.println("name..."+entry.getUser()+"...type.."+entry.getType());
if(entry.getType()==ItemType.none)
{
Presence unsubscribe = new Presence(Presence.Type.unsubscribe);
unsubscribe.setTo(removefri);
Constants.connection.sendPacket(unsubscribe);
// usersList.clear();
usersList.remove(removefri);
Log.d("removed"," the best friend " + removefri);
Pasting code for refrence :http://pastie.org/8744959
Use adapter.notifyDataSetChanged(); after removal
I am trying to develop a Registration screen from Android XML. As in every Registration form, I would need to display the list of countries. I am able to do this using string-array in strings.xml file.
The greater part of the problem is, when a user selects a country, the phone number field just below it should be initially filled with its respective country code, which may or may not be editable. Here, my problem is how do I get the country code when the country is selected. Do I need to use a database or is it achievable using xml itself?
Besides that, when user submits the Register form, I would have to send the abbreviated code of the country, not the full country name. Now, again this would require either a database or xml?
My app doesn't use database till now, it would not be so good to use database for this purpose. Moreover, almost any application that uses a registration needs this thing to be done, but I cannot find any resources on how to do this in Android.
Also, I would like to tell you that my minimum sdk is version 7.
Please help.
I was finally able to do it without using database. I'm writing down the steps so that it may help anyone else who needs the same thing to be done.
First I downloaded the CSV available at: https://github.com/mledoze/countries/blob/master/countries.csv
I removed all other fields, except those I needed. It left me with 3 fields: name, abbreviation and calling code.
Next, I downloaded the CSVReader from: http://code.google.com/p/secrets-for-android/source/browse/trunk/src/au/com/bytecode/opencsv/CSVReader.java
Got the items from the CSV as mentioned in How to parse the CSV file in android application? by "Kopfgeldjaeger" as:
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("countries.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
Next I added an ArrayList for each of the values like:
ArrayList<String> countryNames = new ArrayList<String>();
ArrayList<String> countryAbber = new ArrayList<String>();
ArrayList<String> countryCodes = new ArrayList<String>();
for(int i=0; i < list.size(); i++)
{
countryNames.add(list.get(i)[0]); // gets name
countryAbber.add(list.get(i)[1]); // gets abbreviation
countryCodes.add(list.get(i)[2]); // gets calling code
}
Then added it to the spinner in the XML layout as:
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, countryNames);
spinner.setAdapter(countryAdapter);
// adding event to display codes when country is selected
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// display the corresponding country code
TextView tvCountryCode = (TextView) findViewById(R.id.country_code);
tvCountryCode.setText("+"+list.get(pos)[2]);
countryPosition = pos;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
This way, I was able to display country code in the xml file, when a country was selected from the dropdown list.
Remember to add the setOnItemSelectedListener() to achive that.
I hope this helps somebody in future.
I would advise you to use a database. API level 7 supports SQLite databases (I used them in android 2.1 myself). Create one table that has all the required info:
create table countries (
_id integer primary key autoincrement,
country_code char(2),
country_name varchar,
phone_code char(4),
editable integer
);
Then store your country information into this table. When populating your list of countries, use this table instead of XML; display country names and associate country codes with each corresponding list item. Then on selection, use the country code to get the phone code and the 'editable' flag - and act upon this info.
I am creating local database I want to send all data sent to web service.
For example product name one column. Lots of product name is there. I want to send it.
& Product name = briyani,egg,rice
I got all details from database below i have mention code:
public String fetchMyRowid(String column_name)
{
String query = "select "+column_name+" From " + TABLErestaurant;
mCursor =db.rawQuery(query, null);
StringBuffer buf = new StringBuffer();
if (mCursor.moveToNext()) {
buf.append(mCursor.getString(0));
String str = buf.toString();
System.out.println("**************"+str);
}
return buf.toString();
}
}
return buf.toString();
}
In class :
HashMap<String, String> paramsvalue = new HashMap<String, String>(); paramsvalue.put("product_name", dataBase.fetchMyRowid(DatabaseHelper.columnproductname));
But I have some issue. I got only one product name. I need all product name. Can any one suggest solution for this.
wel come to stackoveflow,
Please check below link in that i have first select all table's recode then i have created one another method for get all columns value by row. after that i have marge all data in to JSON. this is idea you have to do similar way...
https://stackoverflow.com/a/10600440/1168654