Tuesday, 2 July 2013

Android Tutorial Index

How to develop a Graphical User Interface ( GUI ) application for an Android



Hello Friends,
Welcome you all in the Android Tutorial.
Today we will learn how we can develop a GUI application for an Android.


            To develop a GUI app for an android is very easy.
            There are two main things we need to think before creating any GUI application.
            1)        User Interface
            2)        Layout
           
            1) User Interface:-
                        What are the interfaces you are providing to the user as a part of your GUI application?
                        These UI (user interface) interacts with user directly.
                        User Interfaces are like buttons, text fields, list, radio-button etc.
                       
            2) Layout:-
                        The second important thing is how we are positioning the UI in our GUI app.
                        Like you want to put all the UIs in a linear format, vertical format or grid format etc.
                       
            In our Fist GUI application, we are going to use two UIs. They are text field and button.
            And layout we are going to use is Linear Layout.
           
                       
            To build a GUI application for an android we use View and ViewGroup Objects.
            Views are like UI widgets. Example button, textbox, radio button etc.
            ViewGroup are invisible containers. This defines how the views are laid out. Example in grid format or in a linear format, or like vertical format.
           
            Let's start with creating a new Project:-
           
            Step 1: Create a New Project
           
                        File --> New --> Android Application Project
                       Give "FirstGUI" as your application name.
                        and Press Finish.
           
Your "FistGUI" application has been created with default “BlankActivity".
                       
            Step 2: Create a Layout
           
                        Open the activity_main.xml file from the layout directory.
                        Replace the Relativelayout with the LinearLayout.
                        Add the "vertical" orientation.
                        Delete the TextView from the activity_main.xml file. We do not need    this in our current project.
                        So the modified activity_main.xml file will be looking like as follows:-


      

           Step 3:  Add User Interface widgets
           
                        Add a TextField. We will use it for “FirstName”.
                       
                        To create a user editable text field we use will use <EditText> element.
                        Add the following code into your activity_main.xml inside the LinearLayout.

 
  
                      Add another TextField. We will use it for “LastName”.

 
                        

            Let’s have a brief info of some contents:-
           
            a)        android:id: This provides a unique identifier for the view, which we can use to reference the object from the code. Example to read and manipulate the object.
           
                        @ sign is required when we are referring to any resource object from XML.
                        + sign before the resource type is needed only when we are defining a resource ID for a first time.
                       
                        When we compile the app, the SDK use the ID name to create a new resource ID in your project's gen/R.java.
                       
            b)        android:layout_width and android:layout_height:
                        We are not specifying any size for the width and height. We are using the "wrap_content".
                        So the textfield size only as big as needed to fit the contents.
                       
            c)         android:hint
                        We can put the default string to display when the text field is empty.
                        We can hardcode the default value or we can use “@string/first_name" value refers to a string resource defined in a separate file.
                       
       
        Step 4: Add the default string
       
            Open the strings.xml file from the /res/values directory
           Add the following string name, so that we can access it from the other files:-           

First Name
Last Name
Send
                       
            Step 5: Add a Button
           
                      Copy the following code int the activity_main.xml. The following code will add a button into your application.

                       
           
           

 Your final activity_main.xml /res/layout will look like as follows:-


    
    
    
    
    
    




           
Your final strings.xml /res/values will look like as follows:-


    FirstGUI
    Hello world!
    Settings
    First Name
     Last Name
    Send




           
Your "FirstGUI" application is ready, run it and enjoy it ...
Your application will look like as follows :---


              
Do not forgot to share !!!

Friday, 21 June 2013

Contact Us



 "Do you have any questions to ask ??" , if yes this is the place where you can ask if you have any queries regarding to any post.


        This is the place where you can ask programming related question of C, C++ and Java.


        I will be very happy if i can help you to resolve your doubts.

    

       You can also suggest the topic on which you want some details. I will try to make a post in a simple and explained manner.

        Like someone has suggested me to write some important things of C++ 11.



Name


Email


Message






Thursday, 6 June 2013

C++ 11 ( some important features ) static_assert and type_traits

Hello friends,
            Welcome you all in the C++ 11 Part5. In the Part4 we have discussed about lambda function.

In this part we will learn about static_assert and type_traits.

static_assert:
                       
            static_assert performs compile time assertion checking. If the assertion is false, the complier shows the specified error message.

syntax: static_assert(constant_expression, error_message)

constant_expression must be a constant expression that can be converted to bool.
Error_message must be a string literal. You can give the error message what you want to display.


Let’s see how we can use static_assert in our c++ code.
//author: shobhit upadhyaya

template < class T, size_t length >
class String
{
   static_assert(length < 100, "length is too big");
   T str_data[length];
};

int main()
{
   String< int, 101 > a1;
   String< int, 90 > a2;
   return 0;
}

The above code gives you the following error at compile time, because in the static_assert we have a condition string length should be less than 100. But we are trying to give a string length greater than 100.

error C2338: length is too big
  : see reference to class template instantiation 'String<int,101>' being compiled


Static_assert becomes more powerful when used together with the type_traits.
<type_traits> header files provide various classes that give information about types at compile time.

<type_traits> header is categorized into three classes:
            Helper classes: for creating compile time constants.
            Type traits: to get type information at compile time.
            Type transformation: for getting new types by applying specific transformations to existing types.


Let’s see the example how type_traits can help us:-

//author: shobhit upadhyaya

#include 
#include 
using namespace std;

template < class T1, class T2 >
auto mul(T1 a, T2 b) -> decltype(a * b) 
{
  static_assert(is_integral::value,"T1, please input integral value");
  static_assert(is_integral::value,"T2, please input integral value");

   return a * b;
};

int main()
{
   mul(1,3.14);
   mul(1,5);    
   return 0;
}
//


The above code gives the following error at compile time. Because in the static_assert we are using a type_trait is_integral. is_integral checks the type and return false if it is not an integral type. But in our code we are trying to pass a floating point value.

: error C2338: T2, please input integral value
 : see reference to function template instantiation 'T2 mul<int,double>(T1,T2)' being compiled
        with
        [
            T2=double
,            T1=int
        ]


Following are some example of type_traits:-
1.     is_array :-
This check type is an array or not. If not returns false.
2.     is_class:-
This check type is a class or not. If not returns false.
3.     is_enum:-
This check type is an enum or not. If not returns false.
4.     is_floating_point:-
This checks type is a floating point or not. If not returns false.
5.     is_function:-
This checks type is a function or not. If not returns false.
6.     is_integral:-
This checks type is an integral or not. If not returns false.
7.     is_lvalue_reference:-
This checks type is lvalue_reference or not. If not returns false.
8.     is_member_function_pointer:-
This checks type is a pointer to member function or not. If not returns false.
9.     is_member_object_pointer:-
This checks type is a pointer to member object or not. If not returns false.
10.  is_pointer:-
This checks type is a pointer or not. If not returns false.
11.  is_rvalue_reference:-
This checks type is an rvalue reference or not. If not returns false.
12.  is_union:-
This checks type is a union or not. If not returns false.
13.  is_void:-
This checks type is a void or not. If not returns false.

            There are so many others type_traits that I have not covered here. With the help of all there type_traits we can improve the static_assert.






Feel free to give your valuable comments and feedback.
Do not forgot to share J

Tuesday, 4 June 2013

C++ 11 ( some important features ) Part4

Hello friends,
            Welcome you all in the C++ 11 Part4. In the Part3 we have discussed about range-based for statement and override virtual methods.

In this part we will learn about lambda functions.


Lambda function:-
            Anonymous functions are known as lambda function.     
Syntax:
            [capture] (parameters) -> return-type {body}

          body:                     This represent the function body.
return-type:             This can be omitted. If not present it's implied by the function return statements ( or void if it doesn't return any value) 
          parameters:             List of parameters as like named functions.
           

          Let’s have a look of the following code that demonstrates lambda function.
//author: shobhit upadhyaya
#include 
using namespace std;
int main()
{

int ret= [] () -> int {return 5; } ();
printf("ret = %d\n",ret);

// we can omit the return-type -> int, it is implied by the function return statement
int ret1= [] () {return 5;} ();
printf("ret1 = %d\n",ret1);

//parameter demonstration. 
int ret2= [] (int input) -> int { return (input * input * 5 ); } (5);
printf("ret2 = %d\n",ret2);

   return 0;
}
//

A lambda function can refer to identifiers declared outside the lambda function. The set of these variables is commonly called as closure. Closures are defined between square brackets [ and ] in the declaration of lambda expression. The mechanism allows these variables to be captured by value or by reference.

         capture: 
              Let's understand how to use the external variables inside the lambda function.

[]:        // no variables defined. We cannot use any external variables is the lambda function.
[ a, &b]:                     a is captured by value, b is captured by reference.
[&]:     any external variable is implicitly captured by reference if used.
[=]:     any external variable is implicitly captured by value if used.
[&, a]:            a is explicitly captured by value. Other variables will be captured by reference
[=, &b]:         b is explicitly captured by reference. Other variables will be captured by value

Following code gives the demonstration about how to use captures :-


//author: shobhit upadhyaya
#include 
#include 
using namespace std;

int main ()
{

 vector my_list (1,5);                       // five ints with value 1
 int sum = 0;
 
 // demonstration of captures
 /*
    lambda function:
      [&sum] (int x) { sum += x; }
      
      here we captured variable "sum" by reference ,so we can change the value of variable also.
 */
 printf("before, sum = %d\n",sum);
 
 for_each(begin(my_list), end(my_list), [&sum](int x) {
  sum += x;
});
 
  printf("after, sum = %d\n",sum);
  return 0;
}
//



Following code gives the demonstration of how we use STL without and with lambda function:-
//author: shobhit upadhyaya
#include 
#include 
#include 

using namespace std;

bool compare(int i,int j){return (i > j);}

using namespace std;
int main()
{
	int n = 10;

	vector v(n);
	//initialize the vector with values from 0 to 9
	for(int i=0; i < n; i++)
        {
          v[i] = i;
        }
	
	for(int i = 0; i < n; i++)
           printf("v[%d] == %d\n",i,v[i]);

	printf("\n");

	//sort the vector, with the help of compare function
	sort(v.begin(), v.end(), compare); // C++98 style
	
        for(int i = 0; i < n; i++)
	    printf("v[%d] == %d\n",i,v[i]);

	printf("\n");

        //sort the vector, with the help of lambda function
        sort(v.begin(),v.end(),[](int i, int j) -> bool{ return (i < j);}); //C++11 style
   
  
	for(int i = 0; i < n; i++)
           printf("v[%d] == %d\n",i,v[i]);

        printf("\n");

	return 0;
}


//





Give your comments and feedback.

Do not forgot to share J




Wednesday, 29 May 2013

C++ 11 ( some important features ) Part3

Hello friends,
            Welcome you all in the C++ 11 Part3. In the Part2 we have discussed about nullptr and enum.
In this part we will learn about range-based for statement and override virtual methods.


Range-based for statement:-
            Syntax: -        for (for-range-declaration :  expression)
                                                Statement
            Range-based for statement executes statement repeatedly for each element in the expression. 

You can use range-based for statements for vector or any other STL sequence whose range is defined by a begin() and end().
The name that is declared in the for-range-declaration portion is local to the for statement and cannot re-declared in the expression or statement.


Let’s check out the following code to know more how to use:-

// range-based-for.cpp
// author: shobhit upadhyaya

#include 
#include 
using namespace std;

int main() 
{
    //array of integer.
    int iarr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Range-based for loop to iterate through the array.
    
/* Accessing values using a copy declared as int type */
    for( int i : iarr ) { 
                                     
        cout << i << " ";
    }
    cout << endl;


/* Using auto keyword that causes type inference to be used. */
    for( auto i : iarr ) { 
        cout << i << " ";
    }
    cout << endl;

/*When you want to modify the iarr, one way to use is as follows */
    for( auto &i : iarr ) { // Type inference by reference.
       
        cout << i << " ";
    }
    cout << endl;

/*We can prevent modification with the help of const */
    for( const auto &i : iarr ) { // Type inference by reference.

        cout << i << " ";
    }
    
    cout << endl;
    
    
    // Vector of integer 
    vector v;
    
    for (int i = 0; i < 10; ++i) {
        v.push_back(i);
    }

    for( const auto &value : v ) {
        cout << value << " ";
    }
    cout << endl;
}
/**/


Override Virtual methods:-

            In C++ there is no mandatory mechanism to figure it out the overridden virtual method in derived classes.
Virtual keyword is also optional that makes the code bit difficult to understand, you may need to look through the top hierarchy to check if the method is virtual or not.

Let's see some virtual methods error scenarios :-

Scenario 1:-

// author: shobhit upadhyaya

class Base
{
public:
   virtual void func(short) {std::cout << "Base -> func(short)" << std::endl;}
};

class Derived : public Base
{
public:
   virtual void func(int) {std::cout << "Derived -> func(int)" << std::endl;}
};

In the above code Derived::func is supposed to override Base::func. In this case the signature is different , so this became a case of function overloading. In this case it creates another virtual function. If you try to call func() through a pointer to Base it will print Base --> func(short). This is a common problem when user wants to modify the base class.


Scenario 2:-

// author: shobhit upadhyaya
class Base
{
public:
   virtual void func(int) const {std::cout << "Base -> func(int) " << std::endl;}
};

class Derived : public Base
{
public:
   virtual void func(int) {std::cout << "Derived -> func(int)" << std::endl;}
};


In the above code also both func() are overloads not override. If you try to call func() through a pointer to Base it will print Base --> func(int)


Fortunately, C++ 11 has added two identifiers: override and final. 

    override :- we can use override to indicate that a method is suppose to be an override of an base class. 

// author: shobhit upadhyaya
class Base
{
public:
   virtual void func(short) {std::cout << "Base -> func(short)" << std::endl;}
};

class Derived : public Base
{
public:
   virtual void func(int) override {std::cout << "Derived -> func(int)" << std::endl;}
};

When you compile the above code you will get compiler error. Because we have used the override specifier, now the compiler will check the base classes to see if there is a virtual function with this exact signature. And if there is not compiler will indicate an error.

    final :- we can use final to indicate that derived class shall not override a virtual method.

// author: shobhit upadhyaya
class Base
{
public:
   virtual void func(int) {std::cout << "Base -> func(int)" << std::endl;}
};

class Derived : public Base
{
public:
   virtual void func(int) override final {std::cout << "Derived -> func(int)" << std::endl;}
};

class Derived2 : public Derived
{
public:
   virtual void func(int) override {std::cout << "Derived2 -> func(int)" << std::endl;}
};

In the above example, Derived2 class is trying to override func() virtual method. But here we will get compiler error. Because Derived class has used final to prevent further overriding. 




Feel free to give your suggestion and ask question ?
Do not forgot to share it :)


Tuesday, 9 April 2013

C++ 11 ( some important features ) Part2


Hello friends,
            Welcome you all in the C++ 11 Part2. In the Part1 we have discussed about auto and decltype.
In this part we will learn about nullptr and enum classes.


Let’s start with nullptr.

nullptr :-
            nullptr has been introduced in C++ 11. nullptr denotes the null pointer literal.
            nullptr is a of type nullptr_t, which is implicitly convertible and comparable to any pointer type and any pointer to member type.
           
            Let's see this :-

                void fun1(char *i);
                void fun1(int j);
           
                fun1( NULL );           // which function gets called ?
           
            It looks like the first function will be called.
            The trouble is value of NULL is integer 0, so the second fun1(int j) will be called.
           
            With the help of nullptr we can solve this very easily.
           
            fun1 ( nullptr );
            Now the first function fun1(char *i) will be called. nullptr is used to represent NULL pointers,
            and cannot be converted to an integer.
           
enum classes:-

            We have all used enums. Can you tell me is it type safe?

            enums in C++03 are not type safe. They are treated like as integer constant even if the enumeration types are distinct.

            Let see the example:-
#include < iostream>
using namespace std;
 
int main()
{
    enum Song
    {
        track1,
        track2
    };
 
    enum Video
    {
        video1,
        video2
    };
 
    Song s = track1;
    Video v = video1;
  
    if (s == v) // The compiler will compare a and b as integers
        cout << "s and v are equal, no type safe" << endl; // and find they are equal!
    else
        cout << "s and v are not equal, type safe" << endl;
  
    return 0;
}       
  
                    
            C++11 has introduced enum class, which makes enums type safe and strongly scoped.
            Lets take the same example with use of enum class.
           
#include < iostream>
using namespace std;
  
int main()
{
    enum class Song
    {
        track1,
        track2
    };
  
    enum class Video
    {
        video1,
        video2
    };
  
    Song s = Song::track1; // track1 is not accessible, we have to use :: operator
    Video v = Video::video1; // track1 is not accessible, we have to use :: operator
     
    if (s == v) // compile error here, as the compiler doesn't know how to compare different types Song and Video
        cout << "s and v are equal, no type safe" << endl; 
    else
        cout << "s and v are not equal, type safe" << endl;
  
    return 0;
}
         
            
            enum class makes the enums strongly scoped. If you want to access it you have to use :: operator.
            enum class makes the enums type safe. So C++ will look for an explicilty defined comparison function to compare Song and Video. Because we have not defined an operator==(Song, Video) function the compiler won't understand how to compare s and v. That is why it is giving compiler error.