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;
}
Related
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 have tried Google Translate and Microsoft Translator. Both give the error:
[microsoft-translator-api] Error retrieving translation : null
Caused by: android.os.NetworkOnMainThreadException
I've set everything up according to references and tutorials. The only difference is that instead of calling Translate.execute() on click of a button, I'm trying to have it call as the JSON string data starts coming in.
Here's what I have:
In My Data Model Class
public String getName() throws Exception {
String trans = Translate.execute(prod_name, Language.ENGLISH, Language.fromString(Locale.getDefault().getLanguage()));
return trans;
}
I've also tried this:
In My Data Model Class
public String getName(){
return prod_name;
}
Along with this:
Main Activity
JsonArrayRequest request = new JsonArrayRequest(FEAT_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString()); try {
for(int i=0;i<response.length();i++){
String pid=response.getJSONObject(i).getString("pid");
String name=response.getJSONObject(i).getString("prod_name");
String img = response.getJSONObject(i).getString("prod_pic");
String lang = Locale.getDefault().getLanguage();
Log.d("Response: ", name);
String trans = Translate.execute(name, Language.SPANISH, Language.fromString(lang));
fdata.add(new FeaturedModel(pid, trans, img));
}
} catch (Exception e) {
e.printStackTrace();
} featAdapt=new FeaturedAdapter(MainActivity.this, fdata);
pageView.setAdapter(featAdapt);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
VolleyController.getInstance().addToRequestQueue(request, TAG);
I have seen other SO questions regarding Translate API's on Android but all of them referred to clicking a view to get the translation. I haven't found anything that gives an example of translating the JSON string response from a Volley request. Any ideas? What would be the proper way to do this without overloading the main thread?
PER COMMENTS BELOW
I've added this AsyncTask class to my MainActivity:
class TranslateAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... inTxt) {
try {
String lang = Locale.getDefault().getLanguage();
translatedText = Translate.execute(inTxt, Language.fromString(lang));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Translate Error", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
And now getting an error that it can't resolve method setText(String[]) on this line in my adapter class:
holder.ftitle.setText(feature.get(position).getName());
Looking at both the Google and Microsoft Translator API's, they require String[]
I have an Android application I'm working on, I've got the code working I'm just trying to clean it up a bit by moving certain functions into separate files. Whenever i try to call one of the functions from a separate file, however, it crashes saying FATAL EXCEPTION: AsyncTask #5. I have made a constructor in the separate file and I thought I was doing it correctly but I guess not. Any help is appreciated.
Here is my code:
DatabaseManager database;
public class loginTask extends AsyncTask<String, String, String> {
//check if server is online
protected String doInBackground(String... params) {
Log.d("test", "1");
String username = params[0];
String password = params[1];
URI absolute = null;
Log.d("test", "2");
try {
Log.d("test", "3");
absolute = new URI("http://link.com/webservice/");
} catch (URISyntaxException e) {
Log.d("test", "4");
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("test", "5");
database.test();//crashes at this line
return postHttpResponse(absolute,username,password);
}
//set status bar to offline if flag is false
protected void onPostExecute(String jsonstring) {
try {
//get values from jsonobject
JSONObject jsonobj=new JSONObject(jsonstring);
checkResponse(jsonobj);
//errorMessage.setText(checkResponse(jsonobj));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
DatabaseManager.java
private final String LOGIN_TAG = "Login";
public DatabaseManager(){
}
public void test(){
Log.d(LOGIN_TAG, "this is a test");
}
You never instantiate DatabaseManager - so it stays null the entire time. Class scoped references stay null until they are given something to reference (either by pointing the new reference to an existing one or by making a new Object)
Consider doing
database = new DatabaseManager();
Log.d("test", "5");
database.test();//shouldn't crash at this line now
I am basically stuck with my DOM object with the data I want and I'm trying to output that to a string. Here here the code I am using to parse my xml file:
public ORGRTools insertUserNameAndPassword(String userName, String password)
{
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
docBuilder = factory.newDocumentBuilder();
dom = docBuilder.parse (new File("/mnt/sdcard/Commands.xml"));
NodeList items = dom.getElementsByTagName("login");
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("userName")) {
property.getFirstChild().setNodeValue(userName);
}
if (name.equalsIgnoreCase("password")) {
property.getFirstChild().setNodeValue(password);
}
}
}
} catch (SAXException e) {
// TODO Auto-generated catch block
//invalid character in xml
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
That being said, I have the following function that uses the member variable dom from the previous code above to try to get its string representation:
public String serialize()
{
try
{
DOMSource domSource = new DOMSource(dom);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
String retVal= writer.toString();
return retVal;
}
catch(TransformerException ex)
{
//exception here but does not print stack trace... weird
ex.printStackTrace();
return null;
}
}
However, I get the following exception(see comment). Does anyone have a clue what's going on? Whys is transformation to string failing? I've been stuck in this for a few hours so any help would be good. Any API level is ok.
Thanks!
--Edit--
Here is the structure I am trying to process. Basically, the idea is to have one of these models installed with the .apk and have these models communicate with a server. So I need to fill in the user credential data:
<commands>
<login>
<userName>itemstr</userName>
<password>itemstr</password>
</login>
<analyse>
<imageName>itemstr</imageName>
<imageHeight>itemnum</imageHeight>
<imageWidth>itemnum</imageWidth>
<recordID>itemstr</recordID>
</analyse>
<retrieve>
<record>itemnum</record>
</retrieve>
Refer to simple xml framework it will be more easy to work with serializing xml to object.
Here is sample to explain u about its use...
Serializing a simple object
In order to serialize an object to XML a series of annotations must be placed within that object. These annotations tell the persister how the object should be serialized. For example take the class shown below. Here there are three different annotations, one used to describe the name of the root element, one that describes an XML message element, and a final annotation for an id attribute.
#Root
public class Example {
#Element
private String text;
#Attribute
private int index;
public Example() {
super();
}
public Example(String text, int index) {
this.text = text;
this.index = index;
}
public String getMessage() {
return text;
}
public int getId() {
return index;
}
}
To serialize an instance of the above object a Persister is required. The persister object is then given an instance of the annotated object and an output result, which is a file in this example. Other output formats are possible with the persister object.
Serializer serializer = new Persister();
Example example = new Example("Example message", 123);
File result = new File("example.xml");
serializer.write(example, result);
Hope this answers ur question..
I have a rss feed reader application. The goal is to store the title and image for each item in a custom object named RSSItem, and oll the RSSItem objects in another object named RSSFeed. The problem is that if an item element does not have an enclosure element SaxException is thrown. How should I handle the errors with this parser? Here is the parser code:
public class Parser {
private final String RSS_ELEMENT = "rss";
private final String CHANNEL_ELEMENT = "channel";
private final String ITEM_ELEMENT = "item";
private final String ENCLOSURE_ELEMENT = "enclosure";
private final String TITLE_ELEMENT = "title";
private final String URL_ATTRIBUTE = "url";
private final String TYPE_ATTRIBUTE = "type";
private final String IMAGE_TYPE = "image/jpeg";
RSSItem rssItem;
RSSFeed rssFeed;
final URL mFeedUrl;
public Parser(String feedUrl) {
try {
mFeedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
Log.e(e.getClass().getSimpleName(), e.getMessage());
throw new RuntimeException(e);
}
rssFeed = new RSSFeed();
}
protected InputStream getInputStream() {
try {
return mFeedUrl.openConnection().getInputStream();
} catch (IOException e) {
Log.e(e.getClass().getSimpleName(), e.getMessage());
return null;
}
}
public RSSFeed parse() {
InputStream istream = getInputStream();
RootElement root = new RootElement(RSS_ELEMENT);
Element channel = root.requireChild(CHANNEL_ELEMENT);
Element itemElement = channel.requireChild(ITEM_ELEMENT);
Element enclosure = itemElement.requireChild(ENCLOSURE_ELEMENT);
Element title = itemElement.requireChild(TITLE_ELEMENT);
enclosure.setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
String imageType = attrs.getValue(TYPE_ATTRIBUTE);
if (imageType.equals(IMAGE_TYPE)) {
try {
String imageUrl = attrs.getValue(URL_ATTRIBUTE);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
rssItem.setImage(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
title.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
rssItem.setTitle(body);
}
});
itemElement.setStartElementListener(new StartElementListener() {
public void start(Attributes arg0) {
rssItem = new RSSItem();
}
});
itemElement.setEndElementListener(new EndElementListener() {
public void end() {
rssFeed.addItem(rssItem);
}
});
try {
Xml.parse(istream, Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
e.printStackTrace();
}
return rssFeed;
}
}
I would not recommend trying to implement your own RSS parser , but rather using a standard library for that.
It's fairly easy to setup an implementation of a SAX parser but the hard part is to be able to parse any and every feed under the sun.
You need to cater to all formats RSS 1, RSS 2, Atom etc. Even then you will have to contend with poorly formatted feeds.
I had faced similar problems in the past so decided to do my feed parsing on a server and just get the parsed contents. This allows me to run more complex libraries and parser which I can modify without pushing out updates for my app.
I have the following service running on AppEngine which allows for a much simpler XML / JSON parsing at your end. There is a fixed and simple structure to the response. You can use this for parsing
http://evecal.appspot.com/feedParser
You can send both POST and GET requests with the following parameters.
feedLink : The URL of the RSS feed response : JSON or XML as the response format
Examples:
For a POST request
curl --data-urlencode "feedLink=http://feeds.bbci.co.uk/news/world/rss.xml" --data-urlencode "response=json" http://evecal.appspot.com/feedParser
For GET request
evecal.appspot.com/feedParser?feedLink=http://feeds.nytimes.com/nyt/rss/HomePage&response=xml
My android app "NewsSpeak" uses this too.