Facebook

Classic snake game in Linux terminal

Hello Friends,

You must have played the classic snake game on feature phones like Nokia 1100.
Now you can again play the same game in Linux terminal.
For this you need to install nsnake package by running below command in terminal.


sudo apt-get install nsnake


After the package is installed , run the game by running nsnake command.




Use the up and down arrow keys to change to game mode to Borders On and Borders Off.
Use left and right arrow keys to change the speed.
Press enter or space to start the game one you are done with settings.
You can exit the game by pressing q key.




Rules are the same as they were in classic game.
If you collide with yourself (snake), you die. Game over.




Download the latest version of this game from Github.
Buy cheapest nokia mobile phones here.


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.