Friday, June 12, 2015

Java : Excellent Interface Example

 Excellent Interface Example


//Using interface user need not have to think about child parent relation
//any class which implements an interface, can be assigned to that implementing interface instance variable

//Ex: Itree= Interface
//Apple and mango class implements Itree
//Once implemented , I can Use Interface variable to reference both apple and mango
//Also use Interface Array List for looping the same

//Note : Even when there is a new tree ,ex:Strawberry , I can just create a strawberry class implementing Itree and add it to Itree_ArrayList
//this way the code changes is very minimal and I dont need to touch other code.


interface Itree{
public void fruit();
}

class apple implements Itree{
public void fruit() { System.out.println("apple"); }
public void children(){System.out.println("apple a day keeps doctor away"); }
}

class mango implements Itree{
public void fruit() {System.out.println("mango"); }
}




public class tree {
public static void main(String[] args){
ArrayList<Itree> Itree_ArrayList=new ArrayList<Itree>(); // Itree_ArrayList = Interface Array List
Itree tree1=new apple();
Itree tree2=new mango();
Itree_ArrayList.add(tree1);
Itree_ArrayList.add(tree2);
for(Itree t_count:Itree_ArrayList)
t_count.fruit();
apple app=(apple)Itree_ArrayList.get(0);//user can access other methods by casting to apple varibale
app.children();
}
}


Output :
 apple
mango
apple a day keeps doctor away


----------------------------------------------------------------------------------------------------------------------------------

I think it works best for me to create Util library s.But only downside is Static variables are considered to be final.In this case use cannot create getter methods to  change the value of i

public class tree {
public static void main(String[] args){
Itree.static_method();
}
}

interface Itree{
static String i="";
public static void static_method(){ System.out.print("hi"); }
}

Output :
hi 

Monday, May 11, 2015

Java : Sorting ArrayList

Sorting ArrayList


Ref :how-to-sort-an-arraylist-in-java

import java.util.ArrayList;
import java.util.Collections;
 
public class SortingArrayList {
 
    public static void main(String args[]){
 
       ArrayList<String> al = new ArrayList<String> ();
 
            al.add("22");
            al.add("33");
            al.add("11");
            al.add("cc");
            al.add("bb");
            al.add("aa");
 
            System.out.println("Printing List before sorting......");
             for(String value: al){
                 System.out.println(value);
             }
 
             //Sorting...
             Collections.sort(al);
 
             System.out.println("Printing List after sorting......");
             for(String value: al){
                System.out.println(value);
             }
}
}
 

Output

Printing List before sorting……
22
33
11
cc
bb
aa
Printing List after sorting……
11
22
33
aa
bb
cc
 

Saturday, March 7, 2015

Android :Unable to instantiate activity ComponentInfo

Unable to instantiate activity ComponentInfo





You may be trying to find the view before onCreate() which is incorrect.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }
  ...
}

Sunday, March 1, 2015

Android : Creating a new Activity (new screen)

Creating a new Activity


Creating new activity and navigating onclick button (Explicit Activity)
    1. goto res/layout > rt ck > select "new xml file" and "new_layout"
    2. Add objects,make modifications to new layout xml file in graphical view
    3. Manifest file : add below code  inside "<application> </application>"
   
            <activity android:name=".new_Activity">
 
       
    4. Goto src/package > rt ck and select new>Class
    5. give name as "new_Activity" ,ck OK and add below code in "new_Activity"
   
   
        import android.app.Activity;
        public class  new_Activity extends Activity
        {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.new_layout);
                }
        }


    6. Goto activity_main.xml ,create a button and in properties>view>On click-"method_name" and save
    7. Goto Mainactivity>add below method inside the class :
        public void method_name(View V)
        {
            Intent intent=new Intent(this,new_Activity.class);
            startActivity(intent);
        }

Android : Change SDK in Android Studio

Change SDK in Android Studio


To do this, on the menu choose File -> Project Structure. Select the Libraries option and click the green + to add your library.

Saturday, February 28, 2015

Android :How to auto import the necessary classes in Android Studio with shortcut?

Android :How to auto import the necessary classes in Android Studio with shortcut?


Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:
Select Insert imports on paste value to All
Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*


 Screenshot

Thursday, February 12, 2015

Ranorex : String into object

String into object

To convert a string of xpath into object in Ranorex :

1) Include the library above the namespace -- using Ranorex.Core;

2)
            RxPath path="/dom[@domain='localhost']//div[#'silverlightControlHost']//button[@name~'.*supplinvcs.*']";
              Ranorex.Button button = Host.Local.FindSingle(path); 
            WinForms.MessageBox.Show(button.Text.ToString()
);



Ref:
http://www.ranorex.com/forum/add-regular-expression-when-using-a-variable-t2874.html

Tuesday, January 27, 2015

Android :Working with DB

Android :Working with DB


You will be needing 3 user defined class files.
  1. File A which extends sqlitehelper (compulsory)
  2. File B which contains all methods like - create table,Insert data,Select etc.,
  3. File C , for Getter and Setter Class which is more for making your code more classy.

Let File A =sqllitehelperclass
Let File B = DBOperations
Let File C= Persons


sqllitehelperclass.java

public class sqllitehelperclass extends SQLiteOpenHelper
 {

    public sqllitehelperclass(Context context)
    {
        super(context, "test_db", null, 1);
    }
   
    @Override 
// onCreate() is only run when the database file did not exist and was just created    
 public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("CREATE TABLE Persons( PersonID INTEGER PRIMARY KEY AUTOINCREMENT,FirstName TEXT, Age INT)");
    }

    @Override 
//    onUpgrade() is only called when the database file exists but the stored version number is lower than requested in //constructor.    
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}


DBOperations.java

public class DBOperations {
  
    SQLiteOpenHelper sql_helper;
  
    DBOperations(Context context){  
        sql_helper=new sqllitehelperclass(context);
        //Downcasting SQLiteOpenHelper instance with the user defined class "SQLiteOpenHelperclass"
    }
  
    void create_table(){
        sql_helper.getWritableDatabase().execSQL("CREATE TABLE Persons( PersonID INTEGER PRIMARY KEY AUTOINCREMENT,FirstName TEXT, Age INT)");      
        Log.d("db","New db created");
        sql_helper.getWritableDatabase().close();
    }
  
    void delete_table(){
        sql_helper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS Persons");  
        Log.i("db", "database deleted");
        sql_helper.getWritableDatabase().close();
    }

    void insert(){
   //     sql_helper.getWritableDatabase().rawQuery("INSERT INTO Persons (FirstName,Age) VALUES ('Deepak','100');", null);


sql_helper.getWritableDatabase().execSQL("INSERT INTO Persons (FirstName,Age) VALUES ('Deepak','100');");
        sql_helper.getWritableDatabase().close();
    }
  
    List<persons> db_getall_data()
    {  
        int record_count;
        List<persons> query_res=new ArrayList<persons>();

        String[] args={"5P"};
        Cursor resultSet=sql_helper.getReadableDatabase().rawQuery("SELECT * FROM Persons", args);
        Log.d("db", "No of Records present="+String.valueOf(resultSet.getCount()));
        record_count=resultSet.getCount();
        resultSet.moveToFirst();
       
        if(record_count>0){
            while (record_count!=0)
            {
                persons Persons=new persons();
                Persons.put_age(resultSet.getInt(resultSet.getColumnIndex("Age")));
                Persons.put_name(resultSet.getString(resultSet.getColumnIndex("FirstName")));
                query_res.add(Persons);  
                resultSet.moveToNext();
                record_count=record_count-1;
            }
        }      
        sql_helper.getReadableDatabase().close();
        return query_res;
    }
  
  
    public boolean isTableExists()
    {
        try{
            Cursor cursor = sql_helper.getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+"Persons"+"'", null);
            Log.d("DB","rows="+cursor.getCount());
            cursor.close();
        }catch(Exception e){
            sql_helper.getReadableDatabase().close();
            Log.d("Db","Table does not exist ");
            return false;
        }
       
        sql_helper.getReadableDatabase().close();
       return true;
    }
  
  }


person.java

public class persons {
   
    int age;
    String name;
   
    int get_age(){
        return age;
    }
   
    String get_name(){
        return this.name;
       
    }
   
    void put_name(String name){
        this.name=name;
       
    }
   
    void put_age(int age){
        this.age=age;
    }
}
 


Tuesday, January 6, 2015

Android : To Animate a picture file

To Animate a picture file


1.Create a new folder "anim" inside res folder
2.Goto folder res\anim and rt ck , select "Android XML File"
3.Give a resource ="Tween Animation" and File name="rotator" , root element ="rotate"
4.Open rotator.xml , delete all its contents and copy paste the below code inside :
************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:interpolator="@android:anim/linear_interpolator" >

    <!-- Use startOffset to give delay between animations -->


    <!-- Move -->
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromXDelta="0%p"
        android:startOffset="300"
        android:toXDelta="75%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromYDelta="0%p"
        android:startOffset="1100"
        android:toYDelta="70%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromXDelta="0%p"
        android:startOffset="1900"
        android:toXDelta="-75%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromYDelta="0%p"
        android:startOffset="2700"
        android:toYDelta="-70%p" />

    <!-- Rotate 360 degrees -->
    <rotate
        android:duration="1000"
        android:fromDegrees="0"
        android:interpolator="@android:anim/cycle_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:startOffset="3000"
        android:repeatCount="infinite"
        android:repeatMode="restart"
        android:toDegrees="360" />

</set>

***************************************************************************

5.Click next ...next and Finish
6.Copy paste method in your MainActivity

        public void rotateit(View v){
        final ImageView myImage = (ImageView)findViewById(R.id.imageView2);
                final Animation myRotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotator);
                myImage.startAnimation(myRotation);
    }

7.Copy Paste any image inside your res/drawable-hdpi
8.Goto layout xml (ex: layout/activity_main.xml)
9.Select tab - Graphical Layout
10.Drag and Drop Image View  , Select the the image you pasted in "res/drawable-hdpi"
11. Select the image ,goto properties
12.Make On Click ="rotateit"
13.Save and Run



more animations in http://www.androidhive.info/2013/06/android-working-with-xml-animations/

Monday, January 5, 2015

Android: Gif animations part 2

Gif animations part 2

1.Addthis in your Manifest file inside activity "android:hardwareAccelerated="false"
Example :
        <activity
                    android:hardwareAccelerated="false"
                    android:name="foo.GifActivity"
                    android:label="The state of computer animation 2014">
        </activity>

2.Code for Main_Activity

        public class GifActivity extends Activity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(new GifView(this));
            }
       
            static class GifView extends View {
                Movie movie;
       
                GifView(Context context)
                {
                    super(context);
                    movie = Movie.decodeStream(context.getResources().openRawResource(R.drawable.some_gif));
                }
                              
                // inHeriting onDraw of View Class
                @Override
                protected void onDraw(Canvas canvas) {  
                    if (movie != null) {
                        movie.setTime((int) SystemClock.uptimeMillis() % movie.duration());
                        canvas.scale((this.getWidth()/movie.width()), (this.getHeight()/movie.height()));// Size
                        movie.draw(canvas, 0, 0);//Location
                        invalidate();
                    }
                }
            }
        }

       
3.Paste the gif file in "res/hdpi or res/xhdpi"
4.Run the Code

Android:Creating Gif Animation in Android

Creating Gif Animation in Android


1. Create a new Android Project.
2. Add the below code in your Main_activity

//******************Main_activity*************************
public class Your_Class extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Gif_loading_View view = new Gif_loading_View(this);
        setContentView(view);
    }

}

//Adding the webView
public class Gif_loading_View extends WebView{

    public Gif_loading_View(Context context) {

        super(context);    
        loadUrl("file:///android_asset/loading_position.html");

        }
}
//**************************************************************


3.Create a file "loading_position.html" and add the below code inside and svae it.

<html>
<body bgcolor="white">
    <table width="100%" height="100%">
        <tr>
            <td align="center" valign="center">               
                <br/>
                <br/>
                <br/>
                <font size="6">Please wait...</font>
                <br/>
                <br/>
                <img src="your_gif_filename.gif" />

            </td>
        </tr>
    </table>
</body>

4. Copy paste the html file inside "assets" folder in your project.
5. Copy paste any gif file from the internet and rename it as "your_gif_filename"
6. Paste it inside the same assets folder
7.Run the project

Friday, November 21, 2014

Vbs: Reflection in vbs or Converting String into Function Name

  Reflection in vbs or Converting String into Function Name



Output:
tc1
tc2

SQL :Important Queries

SQL Server : Important Queries


1.To display all tables in a database
SELECT * FROM information_schema.tables
 
2. To display table information
 sp_help table_name

Tuesday, November 18, 2014

TestComplete : UserForms

TestComplete : UserForms





Dim sPath,sBrowser,oDialog,form,mr

sub a
    Set form = UserForms.UserForm1
    Set oDialog = form.OpenDialog1        
     
      do
        mr=form.ShowModal     'Show GUI
        Select Case mr
            Case mrOK          'Ok button , In properties set the ModalResult as mrOK 
           
                   if( (form.cxRadioGroup1.ItemIndex=0 or form.cxRadioGroup1.ItemIndex=1) and sPath<>"" )then
                      if(form.cxRadioGroup1.ItemIndex=0) then
                        sBrowser="FireFox"
                        else
                        sBrowser="IE"
                      end if   
                      exit do
                   end if
                             
            Case mrCancel     'Cancel Button .'Ok button , In properties set the ModalResult as mrCancel      
                  exit sub
                     
             Case mrYes         'BrowserButton , In properties set the ModalResult as mrYes
                     oDialog.Execute           'Trigger TOpenBrowser
                     sPath=oDialog.FileName
                     form.Path.Text=sPath
      End Select
    Loop  While (1<2)
   
    msgbox("Browser="&sBrowser&vblf&"File Path="&sPath)
     
end sub

Saturday, November 15, 2014

Android : Cannot resolve android (Android Studio error)

Cannot resolve android  (Android Studio error)


Make sure you have Andoid SDK in your system :

1- press ctrl+alt+shift+s
2-in the Modules bar click on your project name
3-change the compile sdk version to the newest one
4-click apply and ok then sync your project
5-done , i hope the best for you

Thursday, November 13, 2014

Eclipse: Paste Multiline String

Paste Multiline String


Eclipse has an option so that copy-paste of multi-line text into String literals will result in quoted newlines:


Preferences/Java/Editor/Typing/  enable Escape text when pasting into a string literal"



Wednesday, November 12, 2014

Selenium : Eclipse (java) relative path

Eclipse (java) relative path



Example  1:
String filePath = ".\\images\\NotSet_16x16.png";

Example 2 :
If I have a project with following structure and want to reach excel file "excel.xls" as below .


Project_test
        |
        |
         --- src
            |
            |
             ---com (this is a package)
                |
                |
                ---    library (this is a package)
                    |
                    |
                    ---excel.xls



Path=".\\src\\com\\library\\excel.xls"


where «.\» is a root for Eclipse project, «images» is a folder with user's files inside of Eclipse project. Since we are talking about Windows OS, we have to use «\» and not «/», like in Linux, but «\» is the reserved symbol, so we have to type «\» to get desired result.

Monday, November 10, 2014

Selenium : 2D listin Java

2D list in Java

 

// Create an ArrayList of ArrayLists of Integers
ArrayList<ArrayList<Integer>> my2DArrayList = new ArrayList<ArrayList<Integer>>();
// add in a few ArrayLists. These contain the "rows" of the 2D ArrayList
my2DArrayList.add(new ArrayList<Integer>());
my2DArrayList.add(new ArrayList<Integer>());
my2DArrayList.add(new ArrayList<Integer>());
// you can retrieve rows using get(), then treat that 1D arrayList as the column.
my2DArrayList.get(0).add(1);
my2DArrayList.get(0).add(2);
my2DArrayList.get(1).add(3);
my2DArrayList.get(1).add(4);
my2DArrayList.get(1).add(0);
my2DArrayList.get(2).add(5);
// my2DArrayList now contains this:
// row 0: 1, 2
// row 1: 3, 4, 0
// row 2: 5
// to retrieve a specific element, you need to first get the ArrayList of the row you want, then retrieve the column from that arraylist you want
// get element at row 1 and column 2
int number = my2DArrayList.get(1).get(2);


Friday, November 7, 2014

Selenium : TestNg Dataprovider with DependsonMethod

TestNg Dataprovider with DependsonMethod

public class testng {
       
    @DataProvider
        public Object[][] dp() {
          Object[][] o=new Object[2][2];
          o[0][0]="a";
          o[0][1]="b";
          o[1][0]="c";
          o[1][1]="d";
          return o;
        }
   
    @Test()
    public void a1()
    {
        System.out.println("byei");
    }
   
    @Test(dependsOnMethods= { "a1" },dataProvider="dp")
    public void a2(String a,String b)
    {
        System.out.println(a+b);
    }   
}

 

Output 

byei
ab
cd

Selenium : Retrieve Method information in Testng DataProvider

Retrieve Method information in Testng DataProvider


If you declare your @DataProvider as taking a java.lang.reflect.Method as first parameter, TestNG will pass the current test method for this first parameter. This is particularly useful when several test methods use the same @DataProvider and you want it to return different values depending on which test method it is supplying data for.

For example, the following code prints the name of the test method inside its @DataProvider:

@DataProvider(name = "dp")
public Object[][] createData(Method m) {
  System.out.println(m.getName());  // print test method name
  return new Object[][] { new Object[] { "Cedric" }};
}

@Test(dataProvider = "dp")
  public void test1(String s) {
}

@Test(dataProvider = "dp")
  public void test2(String s) {
}


and will therefore display:

test1
test2

Selenium:TestNG factory class with example

TestNG factory class with example 

 http://roadtoautomation.blogspot.in/2014/08/testng-factory-class-with-example.html


@DataProvider is used to pass different test data to a test method
@Factory is used to create different instance of Test class and is useful annotation when you run test multiple time.
you can find examples with description for both at : http://testng.org/doc/index.html


DataProvider Example:

public class DataProviderDemo {

    @DataProvider(name="myDataProvider")
    public Object[][] data(){
        return new Object[][]{ {"adf",5.0f}, {"dfds",4.0f} };
    }
    
    @Test(dataProvider="myDataProvider")
    public void method1( String strData ,float floatData){
        Reporter.log("String "+strData);
        Reporter.log("float "+floatData);
    }
  
}


Factory Example:

public class FactoryDemo {
   
    String strData;
    float floatData;
   
    public FactoryDemo(String string, float f){    
        strData = string;
        floatData = f;      
    }
   
    @Factory
    public static Object[] data(){
        return new Object[]{  new FactoryDemo("adf",5.0f),  new FactoryDemo("dfds",4.0f)   };
    }
      
    @Test()
    public void method1(){
        Reporter.log("String "+strData);
        Reporter.log("float "+floatData);
    }  
}

Selenium : Using 2 Dataproviders in single test

Selenium : Using 2 Dataproviders in single test


public class testng {
 
 public Object[][] dp1() {
    return new Object[][] {new Object[] { "a", "b" },new Object[] { "c", "d" } };
  }

  public Object[][] dp2() {
    return new Object[][] {  new Object[] { "e", "f" },new Object[] { "g", "h" } };
  }

  @DataProvider
  public Object[][] dp() {
    List result = Lists.newArrayList();
    
    result.addAll(Arrays.asList(dp1()));
    result.addAll(Arrays.asList(dp2()));
    return result.toArray(new Object[result.size()][]);
    
  }

  @Test(dataProvider = "dp")
  public void f(String a, String b) {
    System.out.println( a + " " + b);

  }

}//

Selenium : Testng not running Test Cases

Selenium : Testng not running Test Cases


In the below screenshot , the Testng will executethe test case "m1 ()"



The problem is that all the methods which use Testng annotationsshould be declared " public "  by default :


Tuesday, November 4, 2014

Selenium:Create firefox profile with addons and preferences

Selenium:Create firefox profile with addons and preferences

 

Note : If you already have a profile with Firebug added then use :
System.setProperty("webdriver.firefox.profile", "default");
//to find profile name - Start>Run >firefox -ProfileManager

1. Close all firefox instances ,verify the same if any firefox instance is running in the task manager.
2. Goto Start>Run and type "firefox -ProfileManager"
3. click "OK"
4. Firefox "Choose profile" should open.
5. Click on "Create Profile"button.
6. Click on next button in following screen
7. Enter profile name in the next screen and choose the path where you want to save it (ex. D:\profile)
8. Click on finish.
9.  Now uncheck "use the selected profile without asking at startup"
10. Select the profile which has been created .
11 click on "Start firefox ".

Now the firefox will be open with the selected profile.

12. Do required settings and add any addons needed and restart firefox.
13. Now when firefox opens check "use the selected profile without asking at startup"
14. Select default profile.
15 Click on "Start Firefox".


In your Selenium use the below code :

File profileDir = new File("D:\\profile");  //("path/to/top/level/of/profile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.setPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile);

Sunday, November 2, 2014

Selenium :Sikuli for 64Bit JRE- Solution

Selenium :Sikuli for 64Bit Machine - Solution


If you are using Sikuli for the first time please refer the below link (once done we will port it to 64Bit)  :



Porting for 64Bit :
  1.   Download and install 32Bit JRE (http://filehippo.com/download_jre_32/3868/) .Make sure JRE 6 is installed in a different location to avoid conflicts.
  2. Open Eclipse and configure the following
a)      Project ---> Properties ---> Java Compiler : set compliance level and Source compatibility to 1.6
b)       Project ---> Properties ---> Java Build Path ---> Libraries ---> and change the JRE system library to 1.6
  1. Project ---> Java Build Paths--->Libraries--->Add Library--->Select Jre System Library
a)      Click Next
b)      Select Alternate JRE Radio button in JRE System Library Screen
c)      Click on Installed JREs
d)     In Prefrences window , Click on Search Button
e)      In search window , Select the Parent folder where Java6 is installed(“C:\Program Files (x86)\Java”)    .
f)       Click on OK
  1. Now Jre6 will be added to your Installed JREs window
  2. Now check “jre6” as default and close .
  3. Now check whether JRE6 has been added to your current project.

Now run your SIKULI script to check if the same is working .. .