Android Club – Go to another activity using Intent

ActivityA.java

public class ActivityA extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);

        // find button
        Button bOpenActivityB = (Button) findViewById(R.id.bOpenActivityB);
        // set on click listener
        // when you click this button, slushatel's code will work
        bOpenActivityB.setOnClickListener(slushatel);

    }

    View.OnClickListener slushatel = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // create intent
            // go from ActivityA to ActvityB
            Intent sel = new Intent(ActivityA.this, ActivityB.class);
            // let's go
            startActivity(sel);
        }
    };

}

activity_a.xml

<LinearLayout 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:orientation="vertical"
   tools:context="net.joerichard.helloandroid.ActivityA">

    <Button
       android:id="@+id/bOpenActivityB"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Сим сим откройся"/>

</LinearLayout>

ActivityB.java

public class ActivityB extends ActionBarActivity {

    static int create_counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_b);

    }

}

Android Club – How to show text in TextView?

First of all, let’s open your activity. It starts with this method:

    protected void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);

    }

This line says that we are going to use activity_a layout as layout for our activity.

setContentView(R.layout.activity_a);

Open res folder, then layout, and open activity_a.xml. Inside it put one TextView. After adding TextView, your layout should look like this:

<LinearLayout 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:orientation="vertical"
   tools:context="net.joerichard.helloandroid.ActivityA">

    <TextView
       android:id="@+id/txtCreate"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textColor="#000000" />

</LinearLayout>

Here you can see that we set txtCreate as TextView’s id. Later we will refer this id to get access to this TextView. Now open your Activity class, then refer TextView by its id. Then use method setText to set text.

    private static Integer counter_create = 0;

    protected void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);

        TextView txtCreate = (TextView) findViewById(R.id.txtCreate);
        counter_create++;
        txtCreate.setText(counter_create);
       
    }

Pay attention to that we created static class int variable(counter_create) which we increment each time we call corresponding method(onCreate).

Now your task is to count all callbacks and show in different TextViews. Good luck!

Android Club – Tic Tac Toe game step-by-step instruction

In this tutorial, I will show how to build Tic Tac Toe console game in Java.

1. First of all, we create our class. Let’s call it – Game. Inside of our class, create main method where our game starts.

public class Game {
    public static void main(String[] args) {
       
    }
}

2. Create static String ArrayList where will hold our Xs and Os. If it is empty(no X and no O), it will show element index. ArrayList should be class variable to make it available in our other methods. Fill ArrayList with index numbers using for loop inside main method.

static ArrayList<String> numbers;
   
    public static void main(String[] args) {
       
        elements = new ArrayList<String>();
        for (int i = 0; i <= 8; i++) {
            elements.add(String.valueOf(i));
        }
       
    }

3. Let’s create method which helps us to show Tic Tac Toe in this form
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8

    private static void showTable() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numbers.size(); i++) {
            String position = numbers.get(i);
            sb.append(position);
           
            if(i%3==2)
            {
                sb.append("\n");
            }
            else
            {
                sb.append(" | ");
            }
           
        }
        System.out.println(sb.toString());
    }

4. Create static final Strings for X and O;

    static final String x = "X";
    static final String o = "O";

Create class variable boolean player1. If player1 is true, so player 1’s turn, if player1 is false, now player 2 will play.

    static boolean player1 = true;

Let’s create scanner using which we will get user input.

    static Scanner scanner;
   
    public static void main(String[] args) {
        // initialize scanner
        scanner = new Scanner(System.in);

Create another method, which will be used to set user’s mark(X or O up to player) to position.

    private static void setUserValue() {
        if(player1)
        {
            System.out.println("X - Player 1's turn");
            System.out.println("Enter position");
           
        }
        else
        {
            System.out.println("O - Player 2's turn");
            System.out.println("Enter position");
        }
       
        int position = scanner.nextInt();
       
        if(numbers.get(position).equals(x)||numbers.get(position).equals(o))
        {
            System.out.println("This position is already taken");
        }
        else if(player1)
        {
            numbers.set(position, x);
            player1 = false;
        }
        else
        {
            numbers.set(position, o);
            player1 = true;
        }
    }

5. Now we will create method which identifies winner. These method will return boolean value, which represents winner is found or not. True – if winner found, false – not found.
In this method we create 2 ArrayLists, where we can save positions for Xs and Os. We fill these ArrayLists from numbers ArrayList. For example, if index 4 is X, then we add 4 to xxx ArrayList. Then we create Array of winning combinations in order to find winner.

    private static boolean findWinner()
    {
       
        ArrayList<String> xxx = new ArrayList<String>();
        ArrayList<String> ooo = new ArrayList<String>();
       
        for (int i = 0; i < numbers.size(); i++) {
            String num = numbers.get(i);
            if(num.equals(x))
            {
                xxx.add(String.valueOf(i));
            }
            if(num.equals(o))
            {
                ooo.add(String.valueOf(i));
            }
        }
       
        String[] win0 = {"0","1","2"};
        String[] win1 = {"3","4","5"};
        String[] win2 = {"6","7","8"};
        String[] win3 = {"0","3","6"};
        String[] win4 = {"1","4","7"};
        String[] win5 = {"2","5","8"};
        String[] win6 = {"0","4","8"};
        String[] win7 = {"2","4","6"};
       
        String[][] wins = {win0, win1, win2, win3, win4, win5, win6, win7};
       
        for (int i = 0; i < wins.length; i++) {
            String[] win = wins[i];
           
            int xCount = 0;
            int oCount = 0;
            for (int j = 0; j < win.length; j++) {
                String pos = win[j];
                if(xxx.contains(pos))
                {
                    xCount++;
                }
                if(ooo.contains(pos))
                {
                    oCount++;
                }
            }
            if(xCount==3)
            {
                System.out.println("Winner is Player 1");
                return false;
            }
            if(oCount==3)
            {
                System.out.println("Winner is Player 2");
                return false;
            }
           
        }
        return true;
    }

6. Last step in our game is to create general logic using our methods. We will ask user to choose position till we do not found winner. In each iteration we show table and ask user enter position.

        while(findWinner())
        {
            showTable();
            setUserValue();
        }

That’s it! Now you can play Tic Tac Toe on Console! However, we did not write logic for situation when winner is not determined. I think it should not be hard to write it yourself. Good luck!

Here you can see whole code:

import java.util.ArrayList;
import java.util.Scanner;


public class Game {

    static final String x = "X";
    static final String o = "O";
    public static ArrayList<String> numbers;
    static boolean player1 = true;
    static Scanner scanner;
   
    public static void main(String[] args) {
       
        scanner = new Scanner(System.in);
       
        numbers = new ArrayList<String>();
        for (int i = 0; i <= 8; i++) {
            numbers.add(String.valueOf(i));
        }
       
        while(findWinner())
        {
            showTable();
            setUserValue();
        }
       
    }
   
    private static boolean findWinner()
    {
       
        ArrayList<String> xxx = new ArrayList<String>();
        ArrayList<String> ooo = new ArrayList<String>();
       
        for (int i = 0; i < numbers.size(); i++) {
            String num = numbers.get(i);
            if(num.equals(x))
            {
                xxx.add(String.valueOf(i));
            }
            if(num.equals(o))
            {
                ooo.add(String.valueOf(i));
            }
        }
       
        String[] win0 = {"0","1","2"};
        String[] win1 = {"3","4","5"};
        String[] win2 = {"6","7","8"};
        String[] win3 = {"0","3","6"};
        String[] win4 = {"1","4","7"};
        String[] win5 = {"2","5","8"};
        String[] win6 = {"0","4","8"};
        String[] win7 = {"2","4","6"};
       
        String[][] wins = {win0, win1, win2, win3, win4, win5, win6, win7};
       
        for (int i = 0; i < wins.length; i++) {
            String[] win = wins[i];
           
            int xCount = 0;
            int oCount = 0;
            for (int j = 0; j < win.length; j++) {
                String pos = win[j];
                if(xxx.contains(pos))
                {
                    xCount++;
                }
                if(ooo.contains(pos))
                {
                    oCount++;
                }
            }
            if(xCount==3)
            {
                System.out.println("Winner is Player 1");
                return false;
            }
            if(oCount==3)
            {
                System.out.println("Winner is Player 2");
                return false;
            }
           
        }
        return true;
    }
   
    private static void setUserValue() {
        if(player1)
        {
            System.out.println("X - Player 1's turn");
            System.out.println("Enter position");
           
        }
        else
        {
            System.out.println("O - Player 2's turn");
            System.out.println("Enter position");
        }
       
        int position = scanner.nextInt();
       
        if(numbers.get(position).equals(x)||numbers.get(position).equals(o))
        {
            System.out.println("This position is already taken");
        }
        else if(player1)
        {
            numbers.set(position, x);
            player1 = false;
        }
        else
        {
            numbers.set(position, o);
            player1 = true;
        }
    }
   
    private static void showTable() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numbers.size(); i++) {
            String position = numbers.get(i);
            sb.append(position);
           
            if(i%3==2)
            {
                sb.append("\n");
            }
            else
            {
                sb.append(" | ");
            }
           
        }
        System.out.println(sb.toString());
    }
   
}

Android Club – Tic Tac Toe game source code

import java.util.ArrayList;
import java.util.Scanner;

public class TicTacToeGame {
   
    static final String x = "X";
    static final String o = "O";
    static ArrayList<String> numbers;
    static Scanner scanner;
    static boolean player1 = true;
   
    public static void main(String[] args) {
       
        scanner = new Scanner(System.in);
       
        numbers = new ArrayList<String>();
        for (int i = 0; i <= 8; i++) {
            numbers.add(String.valueOf(i));
        }
       
        while(findWinner())
        {
            showTable();
            setUserValue();
        }
    }
   
    private static boolean findWinner()
    {
       
        ArrayList<String> xxx = new ArrayList<String>();
        ArrayList<String> ooo = new ArrayList<String>();
       
        for (int i = 0; i < numbers.size(); i++) {
            String num = numbers.get(i);
            if(num.equals(x))
            {
                xxx.add(String.valueOf(i));
            }
            if(num.equals(o))
            {
                ooo.add(String.valueOf(i));
            }
        }
       
        String[] win0 = {"0","1","2"};
        String[] win1 = {"3","4","5"};
        String[] win2 = {"6","7","8"};
        String[] win3 = {"0","3","6"};
        String[] win4 = {"1","4","7"};
        String[] win5 = {"2","5","8"};
        String[] win6 = {"0","4","8"};
        String[] win7 = {"2","4","6"};
       
        String[][] wins = {win0, win1, win2, win3, win4, win5, win6, win7};
       
        for (int i = 0; i < wins.length; i++) {
            String[] win = wins[i];
           
            int xCount = 0;
            int oCount = 0;
            for (int j = 0; j < win.length; j++) {
                String pos = win[j];
                if(xxx.contains(pos))
                {
                    xCount++;
                }
                if(ooo.contains(pos))
                {
                    oCount++;
                }
            }
            if(xCount==3)
            {
                System.out.println("Winner is Player 1");
                return false;
            }
            if(oCount==3)
            {
                System.out.println("Winner is Player 2");
                return false;
            }
           
        }
        return true;
    }

    private static void setUserValue() {
        if(player1)
        {
            System.out.println("X - Player 1's turn");
            System.out.println("Enter position");
           
        }
        else
        {
            System.out.println("O - Player 2's turn");
            System.out.println("Enter position");
        }
       
        int position = scanner.nextInt();
       
        if(numbers.get(position).equals(x)||numbers.get(position).equals(o))
        {
            System.out.println("This position is already taken");
        }
        else if(player1)
        {
            numbers.set(position, x);
            player1 = false;
        }
        else
        {
            numbers.set(position, o);
            player1 = true;
        }
    }

    private static void showTable() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numbers.size(); i++) {
            String position = numbers.get(i);
            sb.append(position);
           
            if(i%3==2)
            {
                sb.append("\n");
            }
            else
            {
                sb.append(" | ");
            }
           
        }
        System.out.println(sb.toString());
    }
   
}