Facebook

Transferring data between two activities

In the last article we saw how to create an activity with text fields , access the data from those text fields and then display that text.

Creating an activity with text fields

If you are learning android from starting and haven't read the first article then I recommend to do so.

Start developing android applications.

To transfer data from one activity to another we need to create another activity. Let's name this activity as DisplayActivity.

To display the transferred text on this activity, create a textview. Set the font size, font color and other parameters.


activity_display.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="mycompany.helloworld.DisplayActivity">

    <TextView
        android:id="@+id/displaymsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:textColor="@android:color/holo_blue_light"
        android:layout_margin="20dp"
        android:layout_centerInParent="true"/>

</RelativeLayout>



TextView will display the text passed to this activity with text size as 20dp and in holo blue color. Margin will leave the 20dp of empty space around the textview.
layout_centerInParent will align the textview in center, vertically and horizontally both.


We will use the MainActivity created in previous article to enter the data. For this article we will modify the code a little bit. Instead of displaying the data, we will start another activity.
MainActivity.xml (modified)


<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView android:text="@string/signin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textColor="@android:color/background_dark"
            android:gravity="center"
            android:padding="10dp"/>

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:hint="Email"
            android:inputType="textEmailAddress"/>

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:hint="Password"
            android:inputType="textWebPassword"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/login"
            android:background="@android:color/holo_blue_dark"
            android:onClick="startAnotherActivity"
            android:layout_margin="10dp"/>



    </LinearLayout>
</RelativeLayout>


Now on click of login button, we will call the function startAnotherActivity.

MainActivity.java (modified)


package mycompany.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

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

    }

    public void startAnotherActivity(View view) {
        String email = getEmail();
        String password = getPassword();
        Intent intent = new Intent( this, DisplayActivity.class);
        intent.putExtra("email", email);
        intent.putExtra("pass",password);
        startActivity(intent);
    }

    public String getEmail() {
        EditText editText = (EditText)findViewById(R.id.email);
        String email = editText.getText().toString();
        return email;
    }

    public String getPassword() {
        EditText editText = (EditText)findViewById(R.id.password);
        String password = editText.getText().toString();
        return password;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Now in DisplayActivity we will collect the data and display it.

DisplayActivity.java


package mycompany.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import org.w3c.dom.Text;

public class DisplayActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        Intent intent = getIntent();
        String email = intent.getStringExtra("email");
        String password = intent.getStringExtra("pass");
        TextView tv = (TextView) findViewById(R.id.displaymsg);
        tv.setText("Email : "+email+"\nPassword : "+password);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

You can also use the captured data for validation purpose. Store the actual email and password in a constants file and match them with entered value. If successful then proceed else redirect them to login screen.

Run the code and comment about your findings.

Creating an activity with text fields


Hello Friends,

This is the third article in this series. In this article we will extend the HelloWorld app a little more. We will add text boxes and will fetch the data from those text boxes, just like web forms.

If you havn't gone through previous article I recommend to do so. These articles are very simple ans small and should not take more than 10 minutes.

Start developing Android App in Android Studio
Understanding the android code

Lets start by adding edit box which will accept email address and another edit box which will take password as input from user.
Then add a button on click of which we will collect the data from edit boxes and will display on a text box.

Edit box contains the editable text while text on a text-box can not be edit directly by user. Any such text has to be manipulated through programming.

To achieve what we said above we will need to add code to activity_main.xml file. After adding the code our file will look like below.


   1:  <RelativeLayout
   2:      xmlns:android="http://schemas.android.com/apk/res/android"
   3:      xmlns:tools="http://schemas.android.com/tools"
   4:      android:layout_width="match_parent"
   5:      android:layout_height="match_parent"
   6:      android:paddingLeft="@dimen/activity_horizontal_margin"
   7:      android:paddingRight="@dimen/activity_horizontal_margin"
   8:      android:paddingTop="@dimen/activity_vertical_margin"
   9:      android:paddingBottom="@dimen/activity_vertical_margin"
  10:      tools:context=".MainActivity">
  11:   
  12:      <LinearLayout
  13:          android:layout_width="match_parent"
  14:          android:layout_height="match_parent"
  15:          android:orientation="vertical">
  16:   
  17:          <TextView android:text="@string/signin"
  18:              android:layout_width="match_parent"
  19:              android:layout_height="wrap_content"
  20:              android:textSize="20dp"
  21:              android:textColor="@android:color/background_dark"
  22:              android:gravity="center"
  23:              android:padding="10dp"/>
  24:   
  25:          <EditText
  26:              android:id="@+id/email"
  27:              android:layout_width="match_parent"
  28:              android:layout_height="wrap_content"
  29:              android:padding="10dp"
  30:              android:hint="Email"
  31:              android:inputType="textEmailAddress"/>
  32:   
  33:          <EditText
  34:              android:id="@+id/password"
  35:              android:layout_width="match_parent"
  36:              android:layout_height="wrap_content"
  37:              android:padding="10dp"
  38:              android:hint="Password"
  39:              android:inputType="textWebPassword"/>
  40:   
  41:          <Button
  42:              android:layout_width="match_parent"
  43:              android:layout_height="wrap_content"
  44:              android:text="@string/login"
  45:              android:background="@android:color/holo_blue_dark"
  46:              android:onClick="getEmailAndPassword"
  47:              android:layout_margin="10dp"/>
  48:   
  49:          <TextView
  50:              android:id="@+id/result"
  51:              android:layout_width="match_parent"
  52:              android:layout_height="wrap_content"
  53:              android:text="@string/result"
  54:              android:gravity="center"
  55:              android:textSize="15dp"/>
  56:   
  57:      </LinearLayout>
  58:  </RelativeLayout>

When you type this code in xml file, you can see the preview of activity in preview pane on right side.


We will read more about Layouts in upcoming articles.
We defined ID for each view in above xml. ID is required to access and manipulate that view from program. Every view should have unique Id.
Width and height parameter may take any of the below value -
match_parent : fill the parent view completely.
wrap_content : Occupy space required to keep the content e.g. text within itself.
DP : we can define width with some integer value. dp, in, px, pt are different such units. Always use DP when building application for multiple screens.

Hint parameter works as placeholder in web. It displays a hint in the edit box and as soon as user starts typing it vanishes away.
InputType parameter restrict the input content. If number is selected than only numbers can be entered in that edit box. Setting input-type save us the effort of validating the input text. Explore the more values that can be set for input-type parameter.

We can call a function on click of a button. Name of the to be called function is defined in onClick parameter of button view.
We do not write any string literal directly in this layout xml file. All such strings are defined in res/values/strings.xml file
Gravity parameter defines the alignment of text in that view. Apart from center it can takes left and right as values.

If you wants to know about any other parameter than please comment in the comment section.

Strings.xml

   1:  <resources>
   2:      <string name="app_name">HelloWorld</string>
   3:   
   4:      <string name="hello_world">Hello world!</string>
   5:      <string name="action_settings">Settings</string>
   6:   
   7:      <string name="login">Login</string>
   8:      <string name="signin">Sign In</string>
   9:      <string name="result">Result will appear here.</string>
  10:  </resources>


Now lets see how to access the data in code.

ActivityMain.java

   1:  package mycompany.helloworld;
   2:   
   3:  import android.support.v7.app.AppCompatActivity;
   4:  import android.os.Bundle;
   5:  import android.view.Menu;
   6:  import android.view.MenuItem;
   7:  import android.view.View;
   8:  import android.widget.EditText;
   9:  import android.widget.TextView;
  10:   
  11:  import org.w3c.dom.Text;
  12:   
  13:  public class MainActivity extends AppCompatActivity {
  14:   
  15:      @Override
  16:      protected void onCreate(Bundle savedInstanceState) {
  17:          super.onCreate(savedInstanceState);
  18:          setContentView(R.layout.activity_main);
  19:   
  20:      }
  21:   
  22:      public void getEmailAndPassword(View view) {
  23:          String email = getEmail();
  24:          String password = getPassword();
  25:          displayResult(email,password);
  26:      }
  27:   
  28:      public String getEmail() {
  29:          EditText editText = (EditText)findViewById(R.id.email);
  30:          String email = editText.getText().toString();
  31:          return email;
  32:      }
  33:   
  34:      public String getPassword() {
  35:          EditText editText = (EditText)findViewById(R.id.password);
  36:          String password = editText.getText().toString();
  37:          return password;
  38:      }
  39:   
  40:      public void displayResult(String email, String password) {
  41:          String result = "Entered Email : "+ email + "\n";
  42:          result = result+ "Entered Password : "+password;
  43:          TextView tv = (TextView) findViewById(R.id.result);
  44:          tv.setText(result);
  45:      }
  46:   
  47:      @Override
  48:      public boolean onCreateOptionsMenu(Menu menu) {
  49:          // Inflate the menu; this adds items to the action bar if it is present.
  50:          getMenuInflater().inflate(R.menu.menu_main, menu);
  51:          return true;
  52:      }
  53:   
  54:      @Override
  55:      public boolean onOptionsItemSelected(MenuItem item) {
  56:          // Handle action bar item clicks here. The action bar will
  57:          // automatically handle clicks on the Home/Up button, so long
  58:          // as you specify a parent activity in AndroidManifest.xml.
  59:          int id = item.getItemId();
  60:   
  61:          //noinspection SimplifiableIfStatement
  62:          if (id == R.id.action_settings) {
  63:              return true;
  64:          }
  65:   
  66:          return super.onOptionsItemSelected(item);
  67:      }
  68:  }


In the snapshot below you can see if some keyword is not found by the IDE then it show the warning. We can correct these errors by including relevant packages. Just press the Alt+enter and required package will be imported.


When you run the application [How to run application] on your device, following screen will appear. Enter the text and press the 'Login' button.



On click of 'Login' Button getEmailAndPassword function is called which in turn call other functions and display the result.


Go through the code and let us know if you face any difficulty by commenting.

In the next article we will see how to transfer the data between two activities.


Understanding the android code

This is the second article in the series android application programming. If you haven't gone through the first article, I strongly recommend to do so.
In previous post we learned how to start developing android app in android studio and how to compile and run the application using android device.

For the sake of simplicity, we started with simple HelloWorld app which doesn't have any functionality so far and only displays text 'Hello World' on the screen.
In this article we will explain the source code which helped us display the text 'Hello World' on screen.

This code is generated by-default  by the android studio.

MainActivity.java

   1:  package mycompany.helloworld;
   2:   
   3:  import android.support.v7.app.AppCompatActivity;
   4:  import android.os.Bundle;
   5:  import android.view.Menu;
   6:  import android.view.MenuItem;
   7:   
   8:  public class MainActivity extends AppCompatActivity {
   9:   
  10:      @Override
  11:      protected void onCreate(Bundle savedInstanceState) {
  12:          super.onCreate(savedInstanceState);
  13:          setContentView(R.layout.activity_main);
  14:      }
  15:   
  16:      @Override
  17:      public boolean onCreateOptionsMenu(Menu menu) {
  18:          // Inflate the menu; this adds items to the action bar if it is present.
  19:          getMenuInflater().inflate(R.menu.menu_main, menu);
  20:          return true;
  21:      }
  22:   
  23:      @Override
  24:      public boolean onOptionsItemSelected(MenuItem item) {
  25:          // Handle action bar item clicks here. The action bar will
  26:          // automatically handle clicks on the Home/Up button, so long
  27:          // as you specify a parent activity in AndroidManifest.xml.
  28:          int id = item.getItemId();
  29:   
  30:          //noinspection SimplifiableIfStatement
  31:          if (id == R.id.action_settings) {
  32:              return true;
  33:          }
  34:   
  35:          return super.onOptionsItemSelected(item);
  36:      }
  37:  }

Lets go line by line and see what is achieved by that part of code.

Line 1 : This is the fully qualified name of package where your source files are kept.

Line 3-6 : These are the import statements. Whenever you use something new in your source code, studio gives warning that this class or variable can not be found and suggests to import the relevant class or package. Pressing the alt+enter after bringing cursor on text highlighted in red imports the required package automatically.

Line 8 : Your activity class starts from here. Class override 3 default methods.

Line 10-14 : onCreate is the method which is called when an activity is loaded. We will discuss the activity lifecycle in detail in upcoming articles.

Line 16-21 :  onCreateOptionMenu method is used to create the menu options like settings etc.

Line 23-36 :  onOptionItemSelected method handle the code related to menu item click. For example what activity to call or what code to execute when a menu item is clicked.

Example menu item in the figure below. Like 'settings' there might be other menu items.


This is the screenshot of my first app. This is a simple android app named as 'All In One Utility Offline'. It it include some commonly used converters ans some not-to-be-found-anywhere-else utilities like flip coin, roll a dice, weight on other planets etc. One feature I implemented in this app is adaptive UI. Most heavily used utility will be on the top of list.
Please give it a try.

In the next article we will create activity with more fields, accessing data from those fields and displaying that data.


Unix is very simple


Open your terminal. Use cntrl+shift+t.
Type the below command and hit enter.

curl -L http://git.io/unix

What do you see ?


Unix is very simple. It just needs a genius to understand its simplicity.

This is the famous quote by father of Unix and C - Dennis Ritchie

Start developing Android App in Android Studio

Hello Friends,

In the upcoming series of articles we will write about android application development using Android Studio.

This is the first article of this series and here we are explaining the steps of coding your first app , in full detail. We will start from very basics and slowly move to more complex and advance concepts.

So how to develop a simple HelloWorld app....steps below....

Start the Android Studio.
Go to 'file > New  > New Project ' menu.
Below Screen will appear.
 


Enter your Application's Name and your company Name. Application name will be the name you want to give to your android app, HelloWorld in this case.
Read my another blog post about 'Hello World' . Its an interesting read.
Company Name is used for package name inside your project structure.

Click next on this screen. You will see Target Android Device Screen.



This screen let you set the minimun API your application will support. In other words it let you set the oldest version of Android OS on which your app can be installed successfully. If you are developing your app for TV or other wearables then select the minimum SDK for all.
Click next on this screen and you will be prompted to select the activity type on next screen.


For our HelloWorld app we do not need any specific activity type. A simple blank activity can do the needful.
Click finish after selecting the  'Blank Activity'

Project will start building. Wait for few seconds as it may take some time initializing the project.


When project initialization is done, You will see the screen which will look like below image.


Left most pane is project structure given in tree hierarchy.
'app' folder consist of three sub-directories, 'manifests', 'java' and 'res'.
Manifests folder contains all the manifest files.
Java folder contain all the source packages.
'Res' folder contain all the resource file.


'Res' folder again have some sub-directories. We place images and custom layout xml files in this folder. XML layout files of all the activities are included in 'layout' folder. All the string literals are listed in values/string.xml file.
We will explain the use of all other directories at later stage.


In this app have already created a blank activity which by default contains a text view. Layout of the MainActivity is defined in activity_main.xml file inside layout folder. Default populated code in this file is given below.

   1:  <RelativeLayout
   2:      xmlns:android="http://schemas.android.com/apk/res/android"
   3:      xmlns:tools="http://schemas.android.com/tools"
   4:      android:layout_width="match_parent"
   5:      android:layout_height="match_parent"
   6:      android:paddingLeft="@dimen/activity_horizontal_margin"
   7:      android:paddingRight="@dimen/activity_horizontal_margin"
   8:      android:paddingTop="@dimen/activity_vertical_margin"
   9:      android:paddingBottom="@dimen/activity_vertical_margin"
  10:      tools:context=".MainActivity">
  11:   
  12:      <TextView android:text="@string/hello_world"
  13:          android:layout_width="wrap_content"
  14:          android:layout_height="wrap_content" />
  15:   
  16:  </RelativeLayout>

For now we will not add anything in this application. We will learn more in upcoming articles.

Lets now compile and install this app. You have two options to test the working application. Either run the emulator or use your android device. We will stick to the second approach as this give us the real time feedback about our app. Also emulator is too slow most of the times.
To run the app you need to connect your android device to your system.
If device is not being detected by your system then check of you have enabled 'USB Debugging' in developer options in your mobile's settings.




To run the application press shift+F10 or click the run button on the tool bar at top of screen. You can run application by clicking 'run' menu item.


A screen to select the device will appear. You can either launch an emulator or run the app on connected android device. I prefer later on. Click ok and your application will be installed on your device and will start.

You can see Hello World written on the screen. Right now this app doesn't do anything. This is simply displaying a text on screen. In the next article we will dive into more depth of code, how to create menu items, how to execute code when application starts and how to invoke another activity.





Hello [Programming] World!

There is a question on Quora, 'what is the greatest computer program written?'.
There are many great answers such as 'landing system of the Apollo 11', which was written by Margaret Hamilton, Linux Kernel , GNU C compiler, CERN web server etc. No doubt these programs are really great.  Linux kernel surely has changed the world but no program has changed the world more than 'Hello World' did. This simple program has set many brilliant programmer on a voyage to the beautiful world of coding and programming. This is the first tiny step of any programmer marking the beginning of a journey with ups (code compiled successfully) and downs (segmentation fault). 



Printing 'Hello World!' is every beginner and every newbie' first program (in most of the cases). Every new language you learn, the first program you write is printing 'hello world'. This happened with me atleast. 

Do you know the history behind this trend? 


First ever documented use of this iconic statement is found in a 1974 Bell Laboratories internal memorandum by Brian Kernighan, Programming in C: A Tutorial.

First known version of program is as below -

   1:  main( ) {
   2:          printf("hello, world");
   3:  }

The C version was adapted from Kernighan's 1972 A Tutorial Introduction to the Language B, where the first known version of the program is found in an example used to illustrate external variables:


   1:  main(){
   2:    extrn a,b,c;
   3:    putchar(a); putchar(b); putchar(c); putchar('!*n');
   4:    }
   5:   
   6:  a 'hell';
   7:  b 'o, w';
   8:  c 'orld';


See the question title (URL) in below image.


It is indeed true. Feeling of the first successfully compiled program is unmatched.

Hello World program in different language:

1. C

   1:  int main() {
   2:      printf("Hello World!");
   3:      return 0;
   4:  }

2. Java

   1:  public class HelloWorld
   2:  {
   3:      public static void main(String []args) {
   4:          System.out.println("Hello World!");
   5:      }
   6:  }

3. Python

print "Hello World!\n"

4.  C++

   1:  #include <iostream>
   2:   
   3:  using namespace std;
   4:   
   5:  int main()
   6:  {
   7:     cout << "Hello World" << endl; 
   8:     
   9:     return 0;
  10:  }
  11:   

5. Php (save file as main.php and place in www/html folder)

   1:  <html>
   2:  <head>
   3:  <title>Online PHP Script Execution</title>
   4:  </head>
   5:  <body>
   6:  <?php
   7:     echo "&lt;h1>Hello, PHP!</h1>";
   8:  ?>
   9:  </body>
  10:  </html>

Let us know what is your favorite programming language?

Share this among your friends.

ASCII screensavers in Linux





Are there any ASCII animations in Linux which can be used as screen-saver ?
Answer is "Yes". There are many such ASCII screen-savers , few of them are described below. We will explain in detail how to install and use them.

1. Pipes : Best one so far ( my personal preference .

How to Install :
Open the terminal and run below commands -

   1:  git clone https://github.com/pipeseroni/pipes.sh.git
   2:  cd pipes.sh
   3:  sudo make install 

Refer to this documentation on github for more details.


2. cmatrix : Great one.
It displays matrix movie type characters on screen.


How to install :
Run below command in your terminal.

   sudo apt-get install cmatrix

How to run:
Run the command in terminal :

cmatrix -s -b



3. Termsaver : Multiple animations in one.
Text based screen saver having multiple animations like starwars, matrix, jokes4all etc.

How to install :
Run this command in terminal

sudo apt-get install termsaver

How to use :

termsaver matrix

Output of 'termsaver clock'




4. Aquarium

Installing this ascii screen-saver require a little more work..
I am leaving this on you. Follow these steps to install this screen-saver.


;