how to send contacts over xmpp using smack in a chat? - android

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);
}
}
}

Related

MMS After obtaining the address, the download failed

I have obtained the attachment address but the download timeout.
This is my code.
public class MmsSmsReceiver extends BroadcastReceiver {
public static final String MMS_RECEIVE_ACTION = "android.provider.Telephony.WAP_PUSH_RECEIVED";
#Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(MMS_RECEIVE_ACTION)) {
PduParser parser = new PduParser(intent.getByteArrayExtra("data"));
NotificationInd genericPdu = (NotificationInd) parser.parse();
byte[] data=genericPdu.getContentLocation();
try {
String url=new String(data);
Log.e("download url",url);
final byte mms[]= HttpUtils.httpConnection(context,-1L,url,null,HttpUtils.HTTP_GET_METHOD,true, "10.0.0.172", 80);
Log.e("download length", String.valueOf(mms.length));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

How to switch between AndroidElement and WebElement?

I m working on Mobile Web Application Automation. Here I m using Java, Selenium and Appium. There are two fields which I m not able to automate. They are Date and drop down fields. I can able automate text fields, check boxes and radio buttons. When clicking on Date Field, there comes the Android default date picker, in which I cant able to pick a date. Here is my code below:
class openBrowser() {
public static WebDriver driver;
public static AppiumDriver<MobileElement> androidDriver;
#Test
public static void launchBrowser(){
desiredCapabalities(...);
androidDriver = new AndroidDriver<MobileElement>(new
URL("http://localhost:4723/wd/hub", desiredCapabilities));
driver = androidDriver;
}
class pickDate() {
MobileElement element;
try{
element = (MobileElement)
androidDriver.findElementByXPath("//android.view.View[#content-desc='28 May
2017']").click();
}catch(Exception e) {
throw e;
}
}
"findElementByXPath()" looks only for the web element, but not searching for Android/Mobile element. Please refer date picker screenshot: Date picker
Kindly suggest me any solution to switch between Web Element and Android/Mobile Element. Thanks in advance.
I found a solution from the below link:
switch contexts i.e Native App and Web View
public static void switchToContext(String context) throws Exception {
try {
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) androidDriver);
Map<String,String> params = new HashMap<>();
params.put("name", context);
executeMethod.execute(DriverCommand.SWITCH_TO_CONTEXT, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getCurrentContextHandle() throws Exception{
try{
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) androidDriver);
String context = (String) executeMethod.execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE, null);
return context;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static List<String> getContextHandles() throws Exception{
try {
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) androidDriver);
List<String> contexts = (List<String>) executeMethod.execute(DriverCommand.GET_CONTEXT_HANDLES, null);
return contexts;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

upgrading retrofit 1 module to retrofit 2

i am rewriting robospice retrofit module with retrofit 2 .
the problem that i have are in 2 methods(saveData , readCacheDataFromFile) :
import com.octo.android.robospice.persistence.exception.CacheCreationException;
import com.octo.android.robospice.persistence.exception.CacheLoadingException;
import com.octo.android.robospice.persistence.exception.CacheSavingException;
import com.octo.android.robospice.persistence.file.InFileObjectPersister;
public class RetrofitObjectPersister<T> extends InFileObjectPersister<T> {
// ============================================================================================
// ATTRIBUTES
// ============================================================================================
private final Converter converter;
// ============================================================================================
// CONSTRUCTOR
// ============================================================================================
public RetrofitObjectPersister(Application application, Converter converter, Class<T> clazz, File cacheFolder) throws CacheCreationException {
super(application, clazz, cacheFolder);
this.converter = converter;
}
public RetrofitObjectPersister(Application application, Converter converter, Class<T> clazz) throws CacheCreationException {
this(application, converter, clazz, null);
}
// ============================================================================================
// METHODS
// ============================================================================================
#Override
public T saveDataToCacheAndReturnData(final T data, final Object cacheKey) throws CacheSavingException {
try {
if (isAsyncSaveEnabled()) {
Thread t = new Thread() {
#Override
public void run() {
try {
saveData(data, cacheKey);
} catch (IOException e) {
Ln.e(e, "An error occured on saving request " + cacheKey + " data asynchronously");
} catch (CacheSavingException e) {
Ln.e(e, "An error occured on saving request " + cacheKey + " data asynchronously");
}
};
};
t.start();
} else {
saveData(data, cacheKey);
}
} catch (CacheSavingException e) {
throw e;
} catch (Exception e) {
throw new CacheSavingException(e);
}
return data;
}
private void saveData(T data, Object cacheKey) throws IOException, CacheSavingException {
// transform the content in json to store it in the cache
TypedOutput typedBytes = converter.toBody(data);
FileOutputStream out = null;
try {
out = new FileOutputStream(getCacheFile(cacheKey));
typedBytes.writeTo(out);
} finally {
if (out != null) {
out.close();
}
}
}
#SuppressWarnings("unchecked")
#Override
protected T readCacheDataFromFile(File file) throws CacheLoadingException {
InputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
final byte[] body = IOUtils.toByteArray(fileInputStream);
TypedInput typedInput = new TypedInput() {
#Override
public String mimeType() {
return "application/json";
}
#Override
public long length() {
return body.length;
}
#Override
public InputStream in() throws IOException {
return new ByteArrayInputStream(body);
}
};
return (T) converter.fromBody(typedInput, getHandledClass());
} catch (FileNotFoundException e) {
// Should not occur (we test before if file exists)
// Do not throw, file is not cached
Ln.w("file " + file.getAbsolutePath() + " does not exists", e);
return null;
} catch (Exception e) {
throw new CacheLoadingException(e);
} finally {
IOUtils.closeQuietly(fileInputStream);
}
}
}
how can i rewrite these methods in retrofit 2 ?
what is the equivalent of TypedOutput and TypedInput interfaces in retrofit 2 ?
i asked Jake Wharton about this , and he replied that The equivalents are :
RequestBody and ResponseBody

I can not get nickName from users that currently added

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.

Parametrization of robotium

I have been trying to implement database in robotium so that i can parametrize and make it data oriented but i am completely lost please guide me.My robotium code is mentioned below please guide me on how can i open a database connection with sqlite.
package com.dialog.test;
import android.test.ActivityInstrumentationTestCase2;
import com.jayway.android.robotium.solo.Solo;
public class TestNew extends ActivityInstrumentationTestCase2 {
private Solo solo;
//private Activity Main;
private static Class class1;
static
{
try {
class1=Class.forName("com.botskool.DialogBox.DialogBox");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public TestNew() {
super("com.botskool.DialogBox", class1);
}
#Override
protected void setUp() throws Exception {
super.setUp();
this.solo = new Solo(getInstrumentation(), getActivity());
}
#Override
protected void tearDown() throws Exception{
try {
this.solo.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
public void testDisplay(){
solo.clickOnButton(0);
solo.clickOnButton("Ok");
solo.clickOnButton(2);
}
}
Even the smallest guidance would be of great help thank you
You can use File IO of java to integrate in robotium script. provide the File path as of the path in android device like /system/docs/test1.txt . You can provide the details in a file and push the file to the device using adb push commands. and when the script runs, your parameters will be accessed. I am giving you sample code of robotium test case :
public void test(){
String strLine = "",PHN1="", MSG="", siters="";
File f = null;
try {
f = new File("/system/SendSMS.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
while ((readString = buf.readLine()) != null) {
strLine = strLine + readString;
}
} catch (Exception e) {
Log.e("ERROR", "" + e.getMessage());
e.printStackTrace();
}
PHN1 = strLine.substring(strLine.indexOf("[PHN1]")+"[PHN1]".length(), strLine.indexOf("[$PHN1]"));
MSG = strLine.substring(strLine.indexOf("[MSG]")+"[MSG]".length(), strLine.indexOf("[$MSG]"));
siters = strLine.substring(strLine.indexOf("[ITERS]")+"[ITERS]".length(), strLine.indexOf("[$ITERS]"));
int iters = Integer.valueOf(siters);
Log.i("D2Tech","SMS Contact : "+PHN1);
Log.i("D2Tech","SMS Message : "+MSG);
Log.i("D2Tech","SMS Iterations : "+iters);
PHN1="0183030689,0183030687";
iters=50;
for(int j = 1; j<= iters ; j++ ){
solo.clickOnText("New message");
solo.enterText(0, PHN1);
solo.enterText(1, MSG + j);
solo.goBack();
solo.clickOnButton("Send");
solo.goBack();
Log.i("D2Tech","SMS Message number : "+j);
}
solo.waitForDialogToClose(1000);
}

Categories

Resources