13 November 2014

Make A Simple Camera App in Android

What we will do?
-> We will make an application with a button which when pressed opens a camera. You can take a picture then it is saved in the sdcard.

What we need?
  • Eclipse ADT
  • A mobile with a Camera and sdcard
Step 1 : Create a new Project by going on File->New->Android Application Project.

Step 2 : Give a Name to your Application like CameraApp. Then click on Next...till Finish.
 

Step 3: Make a Button in activity_main.xml found in res->layout folder.
activity_main.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"
tools:context=".MainActivity"
android:background="@drawable/ic_launcher">"

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Press to Open Camera"
android:background="#FFFFFF"></Button>"


</RelativeLayout>

Step 4: Open MainActivity.java found in src folder and write the code below.

MainActivity.java
package com.mia.cameraapp;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends Activity {

    public File imageFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"img1.jpg");
        Uri u = Uri.fromFile(imageFile);
        i.putExtra(MediaStore.EXTRA_OUTPUT, u);
        i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(i,0);
    }
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            if(requestCode ==0)
            {
                switch(resultCode)
                {
                case Activity.RESULT_OK :
                    if(imageFile.exists())
                        Toast.makeText(this, "Image Saved at"+imageFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    break;
                case Activity.RESULT_CANCELED :Toast.makeText(this, "Image Not Saved", Toast.LENGTH_LONG).show();
                    break;
                default : break;
                }
            }        
    }

}
Step 5: Run the Project in your Mobile phone directly since Camera will only be available in your phone. The Webcam cannot take the Camera functionality.

Explanation of the code:
  • A simple button is made in activity_main.xml.
  • In MainActivity class a File object is made named imageFile.
  • Intent i is defined to carry out action of opening the camera and MediaStore is used to set action of capturing photo.
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  • MediaStore is an inbuild class which deals with storing media like images,video etc.
imageFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),"img1.jpg");
  • Environment class lets us to access the sd card and store the image in it inside PICTURES directory naming the image to img.jpg.
  • The Uri object will get the url of the image location and make it into a string (e.g. "sdcard/Pictures/special/").
i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
  • EXTRA_VIDEO_QUALITY decides the quality of image (1- high quality, 0-low quality).
  • Then we start the Activity by using startActivity() with parameter as Intent object (i) and requestCode (0).
startActivityForResult(i,0);
  • Then we decide what to do after Activity has started by overriding method onActivityResult().
protected void onActivityResult(int requestCode, int resultCode, Intent data)
  • Then we check the condition if our requestCode matches the Activity(if loaded Activity is img1 only and not any other one).
  • We have a switch case in it which has two cases (if result is OK / result is not OK / default).
if(requestCode ==0)
            {
                switch(resultCode)
                {
                case Activity.RESULT_OK :
                    if(imageFile.exists())
                        Toast.makeText(this, "Image Saved at"+imageFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    break;
                case Activity.RESULT_CANCELED :Toast.makeText(this, "Image Not Saved", Toast.LENGTH_LONG).show();
                    break;
                default : break;
                }
            }
  • If result is Ok we make a Toast which returns path of image where it is saved.
  • If result is not Ok it shows error message in a Toast.

Stay Tuned with Made In Android

Published By:
Yatin Kode
on 13.11.14

10 November 2014

Change the Title and icon of a particular page in the action bar

Today we will learn how to change the title in the action bar of a single page. If you have noticed the name of the page in title bar remains as the same name as that of the app. And if you try to change it from the xml layout .Its not possible.

What we will do?
-> We will make a demo application and change the image and the name(title) of the page from the action bar.

What we need ?
  •  An Android Project
  • An image we will use to replace the previous one.
Step 1: Make an Android Project. I have made an application named TitleApp and logo of Made in Android.
title icon

Step 2: Now I want to change the name of the page to Home and also change the title image to the image shown below.
home icon

Step 3: First I will import the image into drawable-hdpi folder found in workspace->TitleApp->res folder.
drag icon

Step 4: Go into AndroidManifest.xml file from the Project Explorer.
android manifest

Look at the code:

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mia.titleapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


        <activity
            android:name="com.mia.titleapp.MainActivity"
           android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Each <activity> represents a single page execution. To change the title we change the string besides the label parameter inside the activity parenthesis.
android:label="Home"

To change the icon we add a line below the bold line in activity parenthesis.

android:icon="@drawable/homeimg"
Note: homeimg is the name of the new icon imported in the previous step.

The final AndroidManifest.xml will become.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mia.titleapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

 <activity
            android:name="com.mia.titleapp.MainActivity"
            android:label="Home"
android:icon="@drawable/homeimg" >
 <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 5: Run the project.

Before making changes.
before change

After making changes.
after change
 Stay Tuned with Made In Android

Published By:
Yatin Kode
on 10.11.14

29 October 2014

Import a pre-build application code into eclipse

Suppose we want to run a code on a pc which we have made  on another pc .
What shall we do ????

What are we going to do ?
-> We will run a previously existing android project on eclipse by importing it from any of the location .

What we need ?
  • ADT
  • The project folder .
Step 1: Find the location of the android project you want to run . Example: Here we will use a pre-existing project named videocamera into eclipse stored on desktop .
videocamera

Step 2: Start eclipse adt by choosing workspace of your choice.Click on File-> Import .
choose import

 Step 3: Click on Android-> Existing Android Code in workspace and click Next .
existing code

Step 4 : Click on Browse besides Root directory and  just select the folder of your project (Note: Do not select and files from inside the folder, just select the whole folder) and click OK .
browse project

Step 5 : Then you will see the project inside the projects box, .Tick on "copy projects into workspace" and then click on Finish .
tick project

Step 6: You will see your project in the Project Explorer and then run it or reuse it .

Stay Tuned with Made In Android

Published By:
Yatin Kode
on 29.10.14

2 October 2014

Run app in your mobile directly from Eclipse

You may get bored of the emulator often due to its long time processing.. Why bare it ?
You can run the app you developed directly in your android mobile .

What you need ?
  • A Phone(Android Smartphone)
  • A USB Cable
  • USB Driver of your mobile (Download it from manufacturer's site)
Step 1 : Connect your phone to the pc using the USB Cable.

Note that your USB Debugging option from Settings-> Applications->Development must be ON .
Note : For Android 5 (Lollipop)

  • Go to About phone->Tap on Build version 5 times.
  • A message will appear "You are a developer". 
  • Press Back
  • Go to Developer Options. Check USB Debugging

Step 2 : Start your ADT bundle and have your application ready to be Run .(Don't press the Run button).

Step 3 : Install the USB Driver of your Android phone. Check this video.

Step 4: Check your AndroidManifest.xml File for the Debuggable Option from the Application Tag .
and make it to true (true by default).

Step 5 : Click on the DDMS option on the above-right corner of eclipse besides Java and check the devices tab to see if your phone appears in it .

Step 6 : Click on Run option in the toolbar and select Run Configurations .

Step 7 : Select the Target Tab and select to Launch on all compatible devices/AVDs .

The app will directly run on your phone .
Choose your mobile phone from list of running devices.

Stay Tuned with Made In Android

Published By:
Yatin Kode
on 2.10.14

6 September 2014

Choose a Date in Android by using DatePicker

In this post we will make an application to choose a date and display it using a DatePicker .

What are we going to do ?
-> We will let the user choose a date from the DatePicker and display a Toast with the Day, Month and Year when the user clicks the OK button .

What we need ?
Step 1 : Design the xml layout in activity_main.xml found in res -> layout folder from Package Explorer .
activity main datepicker

The code for the above layout is given below :

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Choose the date" />
    
    <DatePicker 
        android:id="@+id/dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        />
    
    <Button
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OK" 
        />

</LinearLayout>

Note that the ids for DatePicker and Button are dp and btnok which will be needed in the Java Code .

Step 2 : The Java code for the layout is defined in MainActivity.java found in src folder .

MainActivity.java
package com.mia.datepickerexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;

public class MainActivity extends Activity {

    DatePicker datepicker;
    Button btnok;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        datepicker = (DatePicker)findViewById(R.id.dp);
       
        btnok = (Button)findViewById(R.id.btnok);
        
        btnok.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this,"Selected Day is "+datepicker.getDayOfMonth()+"\nSelected Month is "+datepicker.getMonth()+"\nSelected Year is "+datepicker.getYear(),Toast.LENGTH_SHORT).show();
            }
        });
    }

}
Step 3 : Run the Project .
select datetoast date

Explanation of the code :
  • First we design the layout of our page in activity_main.xml using a LinearLayout with vertical orientation .
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
  • Then we use a TextView to tell the user to select a date and then insert a DatePicker with id as dp .
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Choose the date" />
    
    <DatePicker 
        android:id="@+id/dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        />
<Button
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OK" 
        />
  • When we design the java class in MainActivity.java we first make variables of the DatePicker and Button by using the function setViewById .
datepicker = (DatePicker)findViewById(R.id.dp);
        btnok = (Button)findViewById(R.id.btnok);
  • Then we call the setOnClickListener() method with the object of the button (btnok) which defines the action of the button when it is pressed .
btnok.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
  • We define a Toast in the onClick method which displays the selected Day, Month and Year from the DatePicker (datepicker) by using the functions getDayOfMonth() ,getMonth() and getYear() for the Day, Month and Year respectively .
Toast.makeText(MainActivity.this,"Selected
 Day is "+datepicker.getDayOfMonth()+"\nSelected Month is 
"+datepicker.getMonth()+"\nSelected Year is 
"+datepicker.getYear(),Toast.LENGTH_SHORT).show();
Stay Tuned with Made In Android 

Published By:
Yatin Kode
on 6.9.14

Previous Page Next Page Home
Top