i am new in asmack. i am writing a chat application and when i add a user by send him/her a subscription packet an he accept, i check openFire server nikename and other properties is ok for new user and mode is both.
but when i try to get friends data nickname is empty.
if i debug the code nickname receive correctly but in run mode can not?
code to receive friends :
public static void getContacts(final Context ctx)
{
try
{
try
{
Thread.sleep(1000);
}
catch(Exception ex)
{
}
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
if(globalVars.friends == null)
globalVars.friends = new ArrayList<globalVars.UserList>();
globalVars.friends.clear();
for(RosterEntry entry: entries)
{
String user = entry.getUser();
String username = user.split("#")[0];
Presence presence = roster.getPresence(entry.getUser());
int status = R.drawable.offline;
if(presence.getType().equals(Presence.Type.available))
status = R.drawable.online;
//String fromto = presence.getFrom() + " "+presence.getTo();
globalVars.UserList ul = new UserList(username, status, globalVars.smallImageAddress(ctx, username));
String wathsUp = "";
try
{
if(presence.getStatus() != null)
wathsUp = presence.getStatus();
}
catch(Exception ex)
{
}
ul.setComment(wathsUp);
ul.setFriend(true);
ul.setNikName(entry.getName());
globalVars.friends.add(ul);
}
can anyone help me?
Use vCard for setting nickname or other details of a user.
Use this code for getting Vcard information from a jid
VCard mVCard = new VCard();
mVCard.load(your xmppconnection,user jid);
String name = mVCard.getNickName();
Just an update on this matter: VCard load() method is now deprecated.
Instead you can use this method:
/**
* retrieves an user VCard
*
* #param userJid the user jid
* #return the VCard object
*/
public VCard getVCard(String userJid) {
VCard vCard = null;
VCardManager vCardManager = VCardManager.getInstanceFor(connection);
boolean isSupported;
try {
//remove resource name if necessary
if (!TextUtils.isEmpty(userJid) && userJid.contains("/")) {
userJid = userJid.split("/")[0];
}
isSupported = vCardManager.isSupported(userJid);
if (isSupported) // return true
vCard = vCardManager.loadVCard(userJid);
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (IllegalArgumentException iAE) {
iAE.printStackTrace();
}
return vCard;
}
As you can see, the method checks if the user understands the vCard-XML format and exchange. If it does, it returns the VCard.
Then just retrieve the user nickname from VCard.
Related
My android application is supposed to get data from an Azure SQL database, but the queries keep responding with
Reference to database and/or server name is not supported in this
version of SQL Server
On the server side audit log it just states
Reference to database and/or server name in 'delivery.dbo.upload' is
not supported in this version of SQL Server
Code:
public class CheckDeliveries extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
private ArrayList<ModelU> arrayList;
//#Override
protected void onPostExecute(String r) {
if (z == "ok") {
GetDeliveries adapter = new GetDeliveries(ViewUpcoming.this, arrayList);
mRecyclerView.setAdapter(adapter);
}
Context context = getApplicationContext();
CharSequence text = "2 " + z;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
protected String doInBackground(String... strings)
{
try
{
con = connectionclass();
if (con == null)
{
z = "Internet Issue";
}
else
{
String query = "SELECT * FROM [delivery].[dbo].[upload]";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
z = "ok";
if(rs.next()) {
do {
#SuppressLint("Range") ModelU modelu = new ModelU(
"" + rs.getInt(rs.getInt("ID")),
"" + rs.getString(rs.getInt("Name")),
"" + rs.getString(rs.getInt("Address")),
"" + rs.getString(rs.getInt("Status"))
);
arrayList.add(modelu);
}
while (rs.next());
}
else {
z = "Invalid Query";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://2033051.database.windows.net:1433;database=delivery;user=XXXXXXXX;password=XXXXXXXX;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;ssl=request;loginTimeout=30;";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error 1", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error 2", e.getMessage());
}
catch (Exception e)
{
Log.e("error 3", e.getMessage());
}
return connection;
}
}
Toastbox output
Azure database
Any help is greatly appreciated!
This error occurs because Azure does not allow to alter the master database. To resolve this, you need to connect directly to the Azure database you are going to use.
Delete the SQL Azure linked server that we created and create a new one.
Under the Server type section of the General tab, choose the Other data source radio button. The name for the linked server in the Linked server text box can be, this time, whatever you like (e.g. AZURE SQL DATABASE). Under the Provider drop down box, choose the Microsoft OLE DB Provider SQL Server item. In the Data source text box, enter the name of the SQL Azure (e.g. server.database.windows.net). The most important setting in order to correctly create a linked server to an Azure SQL database is to enter the name in the Catalog text box (e.g. TestDatabase) of an Azure SQL database for which you want to create a linked server to an Azure SQL database. Otherwise, if this field is left empty, we will encounter the same 40515 error when trying to get a list of the tables under the Catalogs folder.
Refer this article by Marko Zivkovic
I'm using JavaMail API to read emails in my Android app. I debugged my app to find that the number of Message objects in the array are equal to the number of emails I have in my inbox but I'm always getting null when trying to use getContent on the message object. I'm using the jars found here. I'm using imap.gmail.com with all the correct details. I even tried a different email service called mail.com but the error still remains. I'm providing only the method I use to read emails. You can assume everything else is correct.
Code:-
private void initMail(String hostval, String mailStrProt, String uname, String pwd, String authEmail, int mode)
{
uriArrayList = new ArrayList<>();
try {
Log.d("LOGCAT","initMail");
//Set property values
Properties propvals = new Properties();
propvals.put("mail.store.protocol", mailStrProt);
propvals.put("mail.imap.user", uname);
propvals.put("mail.imap.ssl.enable", "true");
propvals.put("mail.imap.host", hostval);
propvals.put("mail.imap.port", "993");
propvals.put("mail.imap.starttls.enable", "true");
Session emailSessionObj = Session.getInstance(propvals, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(uname, pwd);
}
});
//Create POP3 store object and connect with the server
Store storeObj = emailSessionObj.getStore(mailStrProt);
storeObj.connect(hostval, uname, pwd);
//Create folder object and open it in read-only mode
Folder emailFolderObj = storeObj.getFolder("INBOX");
emailFolderObj.open(Folder.READ_ONLY);
//Fetch messages from the folder and print in a loop
Message[] messageobjs = emailFolderObj.getMessages();
for (Message message : messageobjs) {
if(message.getFrom()[0].toString().equals(authEmail)) {
if(message.getContent() instanceof String) { Log.d("LOGCAT","String"); uriArrayList.add(stringToUri(message.getContent().toString())); }
else if(message.getContent() instanceof Multipart) {
Multipart multipart = (Multipart) message.getContent();
MimeBodyPart mimeBodyPart;
for(int i = 0 ; i < multipart.getCount() ; i++) {
if(MimeBodyPart.ATTACHMENT.equalsIgnoreCase(multipart.getBodyPart(i).getDisposition())) {
mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i);
File file = new File(mimeBodyPart.getFileName());
mimeBodyPart.saveFile(file);
uriArrayList.add(Uri.fromFile(file));
}
}
}
lastReceivedMailDate = message.getSentDate().toString();
}
}
//Now close all the objects
emailFolderObj.close(false);
storeObj.close();
} catch (NoSuchProviderException exp) {
exp.printStackTrace();
} catch (MessagingException exp) {
exp.printStackTrace();
} catch (Exception exp) {
exp.printStackTrace();
}
}
EDIT:
for (Message message : messageobjs) {
Multipart multipart = (Multipart) message.getContent();
MimeBodyPart mimeBodyPart;
for(int i = 0 ; i < multipart.getCount() ; i++) {
mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i);
File file = new File(mimeBodyPart.getFileName()); //line number 204
mimeBodyPart.saveFile(file);
uriArrayList.add(Uri.fromFile(file));
} }
private void setOauthParameter() {
GoogleOAuthParameters oauthParam = new GoogleOAuthParameters();
oauthParam.setOAuthConsumerKey(ClientId);
oauthParam.setOAuthConsumerSecret(ClientSecrate);
oauthParam.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH);
// Init the service and set the auth
service = new ContactsService("chat.com.contactssharing");
try {
service.setOAuthCredentials(oauthParam, new OAuthHmacSha1Signer());
service.getRequestFactory().setHeader("User-Agent", "chat.com.contactssharing");
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void queryEntries() throws IOException, ServiceException {
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(50);
myQuery.setStartIndex(1);
myQuery.setStringCustomParameter("showdeleted", "false");
myQuery.setStringCustomParameter("requirealldeleted", "false");
myQuery.setStringCustomParameter("sortorder", "ascending");
try {
// Execution of this line i'm getting an exception
ContactFeed resultFeed = (ContactFeed) this.service.query(myQuery, ContactFeed.class);
Log.d(TAG, resultFeed.toString());
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
}
System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");
} catch (Exception ex) {
System.err.println("Not all placehorders of deleted entries are available");
}
}
My objective to get the friends contacts list from gmail and i have check no's of post for this Exception but no one is commented by correct solution.It's become blocker for me so please help me to out this problem and guide what is doing wrong at above code.
I am developing a chat application in android. In that i want to send contact from sender to receiver similar to whatsapp/telegram.I know there is Vcard XEP in xmpp. But i do not know how to use it. Please can any one help me.
Thanks in advance.
You will have to send the information as document only. What you can do is send a special key in the document, and if you find that key fire an intent to add the contact using the data from the document. let me know if you need help with code.
for get conttact firest need to save entry in vacrd, to getcontact loadVCard.
public class SmackVCardHelper {
public static final String FIELD_STATUS = "status";
private Context context;
private XMPPConnection con;
public SmackVCardHelper(Context context, XMPPConnection con) {
this.context = context;
this.con = con;
}
public void save(String nickname, byte[] avatar) throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.setNickName(nickname);
if (avatar != null) {
vCard.setAvatar(avatar);
}
vCard.setField(FIELD_STATUS, context.getString(R.string.default_status));
vCard.save(con);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public void saveStatus(String status) throws SmackInvocationException {
VCard vCard = loadVCard();
vCard.setField(FIELD_STATUS, status);
try {
vCard.save(con);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public String loadStatus() throws SmackInvocationException {
return loadVCard().getField(FIELD_STATUS);
}
public VCard loadVCard(String jid) throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.load(con, jid);
return vCard;
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public VCard loadVCard() throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.load(con);
return vCard;
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
}
I am working on GCM.
I am able to send notifications to all registered android devices from my local server.
I have saving regid and userid in database. my requirement is send notifications to particular devices.how to do that?
am using java on server side. Any answers will save me..i posted server side code
server side code
public class GCMNotification extends HttpServlet {
private static final long serialVersionUID = 1L;
// Put your Google API Server Key here
private static final String GOOGLE_SERVER_KEY = "AIzaSyDzlDr2viv-EghBFZGpjwXcDoqh24Wt9yE";
static final String MESSAGE_KEY = "message";
static final String TITLE_KEY = "title";
static final String IMAGE_KEY= "image";
static final String ORDER_KEY= "order";
private List<String> androidTargets = new ArrayList<String>();
public GCMNotification() {
super();
// androidTargets.add(re);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//doPost(request, response);
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
String sql;
sql = "SELECT regid, fname, email FROM my_db.Persons";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("regid");
String first = rs.getString("fname");
String last = rs.getString("email");
androidTargets.add(id);
}
rs.close();
stmt.close();
con .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
//MulticastResult result = null;
//Result result1=null;
Writer writer=null;
Connection con=null;
PrintWriter out = response.getWriter();
String share = request.getParameter("shareRegId");
// GCM RedgId of Android device to send push notification
String reg = "";
String emailId="";
String fname="";
if (share != null && !share.isEmpty()) {
reg = request.getParameter("regId");
emailId=request.getParameter("email");
fname=request.getParameter("name");
System.out.println("regId: " + reg);
System.out.println("mailid " + emailId);
System.out.println("name "+ fname);
try {
//Load the Driver for connection
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
PreparedStatement pst=con.prepareStatement("insert into my_db.Persons(regid,email,fname) values(?,?,?)");
pst.setString(1,reg);
pst.setString(2,emailId);
pst.setString(3,fname);
int i = pst.executeUpdate();
if(i!=0){
pw.println("<br>Record has been inserted");
}
else{
pw.println("failed to insert the data");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MulticastResult result1=null;
String userMessage = request.getParameter("message");
String imageUrl = request.getParameter("image");
String order1=request.getParameter("odt");
String titl=request.getParameter("tit");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(10000)
.delayWhileIdle(false)
.addData(TITLE_KEY, titl)
.addData(MESSAGE_KEY,userMessage)
.addData(IMAGE_KEY, imageUrl)
.addData(ORDER_KEY, order1)
.build();
try {
// use this for multicast messages. The second parameter
HashSet<String> set = new HashSet<String>(androidTargets);
// Create ArrayList from the set.
ArrayList<String> result = new ArrayList<String>(set);
System.out.println("reg2:"+result);
// of sender.send() will need to be an array of register ids.
result1 = sender.send(message, result,1);
/* if (result1.getResults() != null) {
int canonicalRegId = result1.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result1.getFailure();
System.out.println("Broadcast failure: " + error);
}*/
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("pushStatus", result1.toString());
request.getRequestDispatcher("index.jsp")
.forward(request, response);
}
}
Simply add a where clause to your sql query to filter out the exact user you want to deal with. If you want to filter the user by the email then use something like this..
sql = "SELECT regid, fname, email FROM my_db.Persons where email = 'abc#gmail.com'";