Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Tuesday, January 8, 2013

Android: Mini Math Game

For practicing purposes I made this program with humble intentions to be a Math game. It creates basic operations like sums, subtractions, multiplications and divisions, in a randomly fashion, along with the right answer and two incorrect answers. Each valid answers adds a point to the user.


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.mytoolbox.utilities.NumberUtilities;

public class MathRallyActivity extends Activity implements OnClickListener {
 
 public enum Operation {
  SUM, DIVISION, MULTIPLICATION, SUBSTRACT  
 }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_math_rally);
        
        Button buttonOption1 = (Button) findViewById(R.id.buttonMath1);
        Button buttonOption2 = (Button) findViewById(R.id.buttonMath2);
        Button buttonOption3 = (Button) findViewById(R.id.buttonMath3);
        ImageButton buttonHome = (ImageButton) findViewById(R.id.imageButtonHome);
        
        buttonOption1.setOnClickListener(this);
        buttonOption2.setOnClickListener(this);
        buttonOption3.setOnClickListener(this);
        buttonHome.setOnClickListener(this);
        
        createOperation();        
    }
    
    private void createOperation() {
     Operation operation = generateRandOperation();
     
     int operand1 = NumberUtilities.generateRandNumber(2, 100);
     int operand2 = NumberUtilities.generateRandNumber(2, 100);
     
     String operationText = String.valueOf(operand1) + " " +
       getOperationString(operation) + " " + String.valueOf(operand2) + "?";
     
     TextView textViewOperation = (TextView) findViewById(R.id.textViewOperation);
     textViewOperation.setText(operationText);
     float rightValue = calculateRightValue(operation, operand1, operand2);
     
     rightBox = NumberUtilities.generateRandNumber(1, 3);
     float randWrongValue1 = NumberUtilities.generateRandNumber(2);
     float randWrongValue2 = NumberUtilities.generateRandNumber(2);
     
     Button buttonOption1 = (Button) findViewById(R.id.buttonMath1);
        Button buttonOption2 = (Button) findViewById(R.id.buttonMath2);
        Button buttonOption3 = (Button) findViewById(R.id.buttonMath3);
     
     switch (rightBox) {
      case 0:
       buttonOption1.setText(String.valueOf(rightValue));
       buttonOption2.setText(String.valueOf(randWrongValue1));
       buttonOption3.setText(String.valueOf(randWrongValue2));
       break;
      case 1:
       buttonOption2.setText(String.valueOf(rightValue));
       buttonOption1.setText(String.valueOf(randWrongValue1));
       buttonOption3.setText(String.valueOf(randWrongValue2));
       break;
      case 2:
       buttonOption3.setText(String.valueOf(rightValue));
       buttonOption1.setText(String.valueOf(randWrongValue1));
       buttonOption2.setText(String.valueOf(randWrongValue2));
       break;
     }     
    }
    
    private float calculateRightValue(Operation oper, int operand1, int operand2) {
     float calculation = 0;
     
     if (oper == Operation.SUM) {
      calculation = operand1 + operand2;
     } else if (oper == Operation.MULTIPLICATION) {
      calculation = operand1 * operand2;
     } else if (oper == Operation.SUBSTRACT) {
      calculation = operand1 - operand2;
     } else if (oper == Operation.DIVISION) {
      calculation = operand1 / operand2;
     }
     
     return calculation;
    }
    
    private String getOperationString(Operation oper) {
     String operationText = "";
     if (oper == Operation.SUM) {
      operationText = "+";
     } else if (oper == Operation.MULTIPLICATION) {
      operationText = "*";
     } else if (oper == Operation.SUBSTRACT) {
      operationText = "-";
     } else if (oper == Operation.DIVISION) {
      operationText = "/";
     }
     return operationText;
    }
    
    private Operation generateRandOperation() {
     int rand = NumberUtilities.generateRandNumber(1, 4);
     Operation operation = null;
     
     switch(rand) {
      case 0:
       operation = Operation.SUM;
       break;
      case 1:
       operation = Operation.DIVISION;
       break;
      case 2:
       operation = Operation.MULTIPLICATION;
       break;
      case 3:
       operation = Operation.SUBSTRACT;
       break;
     }
     return operation;
    }
  
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_math_rally, menu);
        return true;
    }

 @Override
 public void onClick(View view) {
  boolean correct = false;
  boolean play = true;
  
  switch(view.getId()) {
   case R.id.buttonMath1:
    if (rightBox == 0) {
     correct = true;
    }
    break;
   case R.id.buttonMath2:
    if (rightBox == 1) {
     correct = true;
    }
    break;
   case R.id.buttonMath3:
    if (rightBox == 2) {
     correct = true;
    }
    break;
   case R.id.imageButtonHome:
    startActivity(new Intent(MathRallyActivity.this, ChooseActivity.class));
    play = false;
    break;
  }
  if (correct) {
   points++;
   updateScore();
  } if(play) {
   createOperation();
  }
 }
 
 private void updateScore() {
  EditText editText = (EditText) findViewById(R.id.editTextPoints);
  editText.setText(String.valueOf(points));
 }

 private int rightBox;
 private int points;
}

Friday, November 23, 2012

Android: Checking WiFi Connection

To be able to check WiFi connection in an Android application you first need to set the proper permission in the Android manifest:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mytoolbox"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 
 ...
 
</manifest>

Here's a code to check the WiFi. If it's not on it shows an alert message indicating connection is required and then it finishes the application:



private void checkWiFiConnectivity() {
  ConnectivityManager connMan =  (ConnectivityManager) 
       getSystemService(Context.CONNECTIVITY_SERVICE);
  boolean wifiIsOn = connMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        .isConnectedOrConnecting();
  Log.d("GABO", "WiFi is : " + wifiIsOn);
  
  if(!wifiIsOn) {
   finishApplication();
  }  
}

private void finishApplication() {
  AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
  builder.setMessage("You need WiFi connection to access this App!");
  builder.setCancelable(false);
     
  builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
   
   @Override
   public void onClick(DialogInterface dialog, int which) {
       MainActivity.this.finish();    
   }
  });
     
  AlertDialog alert = builder.create();
  alert.show();  
}

Sunday, November 4, 2012

Android: Rock, Paper, Scissors

I'm giving my first baby steps in the Android development world. In this simple application I exemplify the use of:

  • Buttons
  • Click events
  • Image Views
  • Alert dialogs
The application is a simple game of "Rock, Paper, Scissors". User clicks on an image button according to the selection, and immediately the Android makes a random selection. According to the universal very well known rules of this game, an alert dialog is shown with the game result.

So here's the basic layout of the game. The two interrogation images are for displaying the two selections. The three images below are for the user to select an option.



















This is the layout 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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:padding="@dimen/padding_medium"
        android:text="Rock, Paper, Scissors!"
        tools:context=".RockPaperScissors" />

    <Button
        android:id="@+id/buttonRock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="147dp"
        android:layout_marginRight="20dp"
        android:layout_toLeftOf="@+id/textView1"
        android:background="@drawable/rock_small" />

    <Button
        android:id="@+id/buttonPaper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/buttonRock"
        android:layout_alignBottom="@+id/buttonRock"
        android:layout_centerHorizontal="true"
        android:background="@drawable/paper_small" />

    <Button
        android:id="@+id/buttonScissors"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/buttonPaper"
        android:layout_alignBottom="@+id/buttonPaper"
        android:layout_marginLeft="23dp"
        android:layout_toRightOf="@+id/textView1"
        android:background="@drawable/scissors_small" />

    <ImageView
        android:id="@+id/imageViewAnswerUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="26dp"
        android:layout_toLeftOf="@+id/buttonPaper"
        android:src="@drawable/question" />

    <ImageView
        android:id="@+id/ImageViewAnswerAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/buttonScissors"
        android:layout_alignTop="@+id/imageViewAnswerUser"
        android:src="@drawable/question" />

    <ImageButton
        android:id="@+id/imageButtonHome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/buttonPaper"
        android:layout_below="@+id/buttonPaper"
        android:layout_marginTop="38dp"
        android:src="@drawable/home" />

</RelativeLayout>

This is the code for the activity:
package com.example.mytoolbox;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

public class RockPaperScissors extends Activity implements OnClickListener {
 
 public enum Option {
  ROCK, PAPER, SCISSORS
 }
 
 public enum Result {
  WIN, LOSS, DRAW  
 }
 
 private Option userSelection;
 private Result gameResult;
 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rock_paper_scissors);
        
        Button buttonRock = (Button) findViewById(R.id.buttonRock);
        Button buttonpaper = (Button) findViewById(R.id.buttonPaper);
        Button buttonScissors = (Button) findViewById(R.id.buttonScissors);
        ImageButton buttonHome = (ImageButton) findViewById(R.id.imageButtonHome);
        
        // Set click listening event for all buttons.
        buttonRock.setOnClickListener(this);
        buttonpaper.setOnClickListener(this);
        buttonScissors.setOnClickListener(this);
        buttonHome.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_rock_paper_scissors, menu);
        return true;
    }

 @Override
 public void onClick(View v) {
  
  ImageView imageView = (ImageView) findViewById(R.id.imageViewAnswerUser);
  boolean play = true;
  
  switch (v.getId()) {
   case R.id.buttonRock:
    userSelection = Option.ROCK;
    imageView.setImageResource(R.drawable.rock);
    break; 
   case R.id.buttonPaper:
    userSelection = Option.PAPER;
    imageView.setImageResource(R.drawable.paper);
    break;
   case R.id.buttonScissors:
    userSelection = Option.SCISSORS;
    imageView.setImageResource(R.drawable.scissors);
    break;
   case R.id.imageButtonHome:
    startActivity(new Intent(RockPaperScissors.this, ChooseActivity.class)); // To go home.
    play = false;
    break;
  }
  
  if(play) {
   play();
   showResults();
  }
 }

 private void showResults() {
  AlertDialog.Builder builder = new AlertDialog.Builder(RockPaperScissors.this);     
     builder.setCancelable(false);     
     builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {   
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // Do nothing   
   }
  });
     
     // Sets the right message according to result.
     if(gameResult == Result.LOSS) {
      builder.setMessage("You Loose!");
     } else if(gameResult == Result.WIN) {
      builder.setMessage("You Win!");
     } else if(gameResult == Result.DRAW) {
      builder.setMessage("It's a draw!");
     } 
     
     AlertDialog alert = builder.create();
     alert.show();  
    } 

 private void play() {
  // Generates a random play.
  int rand =  ((int)(Math.random() * 10)) % 3;
  Option androidSelection = null;
  ImageView imageView = (ImageView) findViewById(R.id.ImageViewAnswerAndroid);
  
  // Sets the right image according to random selection.
  switch (rand) {
   case 0:
    androidSelection = Option.ROCK;
    imageView.setImageResource(R.drawable.rock);
    break;
   case 1:
    androidSelection = Option.PAPER;
    imageView.setImageResource(R.drawable.paper);
    break;
   case 2:
    androidSelection = Option.SCISSORS;
    imageView.setImageResource(R.drawable.scissors);
    break;
  }
  // Determine game result according to user selection and Android selection.
  if(androidSelection == userSelection) {
   gameResult = Result.DRAW;
  }
  else if(androidSelection == Option.ROCK && userSelection == Option.SCISSORS) {
   gameResult = Result.LOSS;
  }
  else if(androidSelection == Option.PAPER && userSelection == Option.ROCK) {
   gameResult = Result.LOSS;
  } 
  else if(androidSelection == Option.SCISSORS && userSelection == Option.PAPER) {
   gameResult = Result.LOSS;
  } else {
   gameResult = Result.WIN;
  }  
 }    
}

Running app: