In previous post, we have seen simple android ListView example. In this post, we are going to see Android Custom ListView example.
So we will create custom ListView in which each list item will have Country flag, Country name and its capital in different font size as below.

It is widely used in android apps to list number of items and select one or more items from the list.

Source code:

Step 1 :Creating Project

Create an android application project named "CustomListViewExampleApp".

Step 2 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.customlistviewexampleapp.MainActivity">

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />
</RelativeLayout>
You will see below screen in design view.

Step 3: Creating layout for Row

As We have declared ListView widget in activity_main.xml. Now we need to provide layout for individual row.
  • Go to res -> layout
  • right click on layout
  • Click on New -> File. 
  • Create a file named "row_item.xml" and paste below code in row_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ImageView

        android:layout_rowSpan="2"
        android:layout_width="80dp"
        android:layout_height="70dp"

        android:scaleType="fitXY"
        android:id="@+id/imageViewFlag"
        android:layout_row="0"
        android:layout_column="0" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="30dp"
        android:textColor="#1E90FF"
        android:id="@+id/textViewCountry"
        android:layout_row="0"
        android:layout_column="1" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:textColor="#4B0082"
        android:id="@+id/textViewCapital"
        android:layout_row="1"
        android:layout_column="1" />
</GridLayout>

Step 4 :  Creating ArrayAdapter for ListView

Before creating MainActivity, we need to create CustomCountryList class for custom ListView row.
package com.java2blog.customlistviewexampleapp;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.java2blog.customlistviewexampleapp.R;

public class CustomCountryList extends ArrayAdapter<String> {
    private String[] countryNames;
    private String[] capitalNames;
    private Integer[] imageid;
    private Activity context;

    public CustomCountryList(Activity context, String[] countryNames, String[] capitalNames, Integer[] imageid) {
        super(context, R.layout.row_item, countryNames);
        this.context = context;
        this.countryNames = countryNames;
        this.capitalNames = capitalNames;
        this.imageid = imageid;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row=convertView;
        LayoutInflater inflater = context.getLayoutInflater();
        if(convertView==null)
            row = inflater.inflate(R.layout.row_item, null, true);
        TextView textViewCountry = (TextView) row.findViewById(R.id.textViewCountry);
        TextView textViewCapital = (TextView) row.findViewById(R.id.textViewCapital);
        ImageView imageFlag = (ImageView) row.findViewById(R.id.imageViewFlag);

        textViewCountry.setText(countryNames[position]);
        textViewCapital.setText(capitalNames[position]);
        imageFlag.setImageResource(imageid[position]);
        return  row;
    }
}
This class is used to populating data for ListVIew. getView method is get called for drawing each row.

Step 5 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.customlistviewexampleapp;

import android.app.ListActivity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.java2blog.customlistviewexampleapp.CustomCountryList;
import com.java2blog.customlistviewexampleapp.R;


public class MainActivity extends ListActivity {

    private ListView listView;
    private String countryNames[] = {
            "India",
            "China",
            "Nepal",
            "Bhutan"
    };

    private String capitalNames[] = {
            "Delhi",
            "Beijing",
            "Kathmandu",
            "Thimphu"
    };


    private Integer imageid[] = {
            R.drawable.india,
            R.drawable.china,
            R.drawable.nepal,
            R.drawable.bhutan

    };


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

        // Setting header
        TextView textView = new TextView(this);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        textView.setText("List of Countries");

        ListView listView=(ListView)findViewById(android.R.id.list);
        listView.addHeaderView(textView);

        // For populating list data
        CustomCountryList customCountryList = new CustomCountryList(this, countryNames, capitalNames, imageid);
        listView.setAdapter(customCountryList);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(getApplicationContext(),"You Selected "+countryNames[position-1]+ " as Country",Toast.LENGTH_SHORT).show();        }
        });
    }
}
If you notice, we have extended to ListActivity for this class. ListActivity class provides some methods specific to ListView.
We have declared three arrays to take care of Country textView, Capital textView and flag ImageView and customCountryList is being used to populate data in ListView.
As we have added textView to ListView as header in above code thats why we have used countryNames[position-1] while setting toast text, if you don't use header then it should be countryNames[position].

Step 6: Put images in drawable folder

Download source code, locate res -> drawable and put images in your application 's res -> drawable folder.

Step 7 : Running the app 

When you run the app, you will get below screen:


When you click on Bhutan list item, you will get below screen:


In previous post, we have already seen Android SeekBar example. In this post, we will see how to create Custom SeekBar.
If you follow Android SeekBar example , you will see below screen.

We will customize above SeekBar and it will look as below after customization.

If you want to customize above SeekBar , you can follow below tutorial to create Custom SeekBar it.

Source code:

Step 1 :Creating Project

Create an android application project named "AndroidCustomSeekBarExampleApp".

Step 2 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.customseekbarexampleapp.MainActivity" >

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40dp"
        android:max="10"
        android:thumb="@drawable/thumb"
        android:secondaryProgress="5"
        android:progress="5"
        android:progressDrawable="@layout/progress_seekbar"
        />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/seekBar"
        android:layout_marginLeft="29dp"
        android:layout_marginTop="14dp" />

</RelativeLayout>
If you notice, it has two new attributes android:thumb="@drawable/thumb" and android:progressDrawable="@layout/progress_seekbar". You will understand more about it in further steps.

Step 3: Create thumb and put it in drawable folder :

Thumb is nothing but item which you drag to change the progress.  Create a thumb image called "thumb.png" and put it in drawable folder. It will look something like below :
You can download image from source.

Step 4 : Creating XML for drawing progress bar :

  • Go to res -> layout
  • right click on layout
  • Click on New -> File. 
  • Create a file named "progress_seekbar.xml" and paste below code in row_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <item>
        <shape android:shape="rectangle" >
            <corners android:radius="10dp"/>

            <gradient
                android:angle="270"
                android:endColor="#252945"
                android:startColor="#8a834b" />
        </shape>
    </item>
    <item>
        <clip>
            <shape android:shape="rectangle" >
                <corners android:radius="10dp" />

                <gradient
                    android:angle="270"
                    android:endColor="#990800"
                    android:startColor="#d14900" />
            </shape>
        </clip>
    </item>

</layer-list>
Above XML is used to design progresses for custom SeekBar. Above XML uses layer-list tag. A LayerDrawable is a drawable object that manages an array of other drawables. Each drawable in the list is drawn in the order of the list—the last drawable in the list is drawn on top.

Step 5 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.customseekbarexampleapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.java2blog.customseekbarexampleapp.R;

import static com.java2blog.customseekbarexampleapp.R.id.seekBar;
import static com.java2blog.customseekbarexampleapp.R.id.textView;

public class MainActivity extends Activity {

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

        customSeekbar = (SeekBar) findViewById(R.id.seekBar);
        textView = (TextView) findViewById(R.id.textView);
        // Set default value to 0
        textView.setText("Progress : "+customSeekbar.getProgress() + "/" + customSeekbar.getMax());
        customSeekbar.setOnSeekBarChangeListener(
                new OnSeekBarChangeListener() {
                    int progress = 0;
                    @Override
                    public void onProgressChanged(SeekBar seekBar,
                                                  int progresValue, boolean fromUser) {
                        progress = progresValue;
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        // Display the value in textview
                        textView.setText("Progress : "+progress + "/" + seekBar.getMax());
                    }
                });
    }
}

We are getting widget reference from layout file and then using SeekBar's setOnSeekBarChangeListener method to set listener for our custom seekbar.

Step 6 : Running the app 

When you run the app, you will get below screen:


Drag ping circle and use it to set the value for SeekBar.

We are done with Android Custom SeekBar example.
Happy Android Learning !!

In this post, we will see how to create Android splash screen.
Android splash screen is nothing but screen that appears when some background task (such as fetching data from database,loading images) is going on. These kind of task generally tasks long and at that time, we can show splash screen. Splash screen can be app icon, company logo , punch line. Once background task completes, another activity will get called.
For example:
When Xender app loads, you will see screen as below.
Xender App

Source code:

Lets create Android splash screen example:

Step 1 :Creating Project

Create an android application project named "SplashScreenExampleApp".

Step 2: Put any image in drawable folder with name "splash_logo"

Step 3 : Creating splash screen layout file

  • Go to res -> layout
  • Right click on layout
  • Click on New -> File. 
  • Create a file named "splash_screen.xml" and paste below code in splash_screen.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:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/splash_logo"
        android:layout_gravity="center"/>
</LinearLayout>

Step 4: Create SplashActivity

package com.java2blog.splashscreenexampleapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.java2blog.splashscreenexampleapp.R;

public class SplashActivity extends Activity {

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

        //creating new thread just for demonstration of background tasks
        Thread t=new Thread() {
            public void run() {

                try {
                    //sleep thread for 10 seconds
                    sleep(10000);

                    //Call Main activity
                    Intent i=new Intent(SplashActivity.this, com.java2blog.splashscreenexampleapp.MainActivity.class);
                    startActivity(i);

                    //destroying Splash activity
                    finish();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        //start thread
        t.start();
    }
}
Create SplashActivity as above. We are creating a new thread and calling sleep for 10 secs on it. In real time, this will be replaced by actually task that will be performed such as fetching data from database or loading images.

Step 5 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.splashscreenexampleapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World from Java2blog.com" />
</RelativeLayout>

Step 6 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.splashscreenexampleapp;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.java2blog.splashscreenexampleapp.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
It is default MainActivity provided by HelloWorld app.

Step 7 : Changing AndroidManifest.xml

We need to put launcher activity as SplashActivity, so we need to do following changes in app -> src -> main -> AndroidManifest.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2blog.splashscreenexampleapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.java2blog.splashscreenexampleapp.SplashActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"
            android:label="@string/app_name">
        </activity>

    </application>

</manifest>

Step 7 : Running the app 

When you run the app, you will get below screen:

Android Splash Screen tutorial
After 10 secs, you will get below screen:


Android Splash Screen Example

In this post , we are going to create simple ListView.
ListView is the view in which you arrange your list items in vertical order.
For example:
It is very popular widget which is used almost in every application. In this post, I am going to create a very simple list view . If you want to create a some what complex Listview which have images and text in same row , you can go through Android Custom ListView example.

Source code:

Step 1 :Creating Project

Create an android application project named "AndroidListViewExampleApp".

Step 2 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.androidlistviewexampleapp.MainActivity">

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

Step 3 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.androidlistviewexampleapp;

import android.app.ListActivity;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

    String[] listofCountries={"India","China","Nepal","Bhutan"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, listofCountries));

        TextView textView = new TextView(this);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        textView.setText("List of Countries");

        ListView listView=(ListView)findViewById(android.R.id.list);
        listView.addHeaderView(textView);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Toast.makeText(this, "You have selected : " + listofCountries[position-1]+ " as country", Toast.LENGTH_LONG).show();
    }
}
If you notice closely, our MainActivity extends ListActivity as ListActivity has some method specifically for ListView.
    setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, listofCountries));
Whenever we create ListView, we need to provide ArrayAdapter which sets view for each row and also we need to provide a file which defines layout of each Row. In this example, we are using android.R.layout.simple_list_item_1 which is android's predefined layout file .

Step 4 : Running the app 

When you run the app, you will get below screen:
Android simple ListView example

When you click on Bhutan , you will get below screen

Android Simple ListView Tutorial


We are done with Android Simple ListView example.
Happy Android Learning !!

In this post, we are going to see about Android Rating Bar.
RatingBar is android widget which is used to provide rating bar with star icons. You might have seen this RatingBar when any application asks for you to rate installed app.

It is very easy to create Rating in Android. Just follow below steps to create Rating Bar.

Source code:

Step 1 :Creating Project

Create an android application project named "RatingBarExampleApp".

Step 2 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/rateApp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rate this application"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:numStars="5"
        android:stepSize="0.5"
        android:rating="3.0" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:text="Submit" />

    <TextView
        android:id="@+id/ratingVal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Step 3 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.ratingbarexampleapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.widget.RatingBar.OnRatingBarChangeListener;

public class MainActivity extends AppCompatActivity {

    private RatingBar ratingBar;
    private Button button;
    private TextView ratingVal;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        ratingVal=(TextView) findViewById(R.id.ratingVal);
        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {

                ratingVal.setText("Current Rating  : "+String.valueOf(rating));

            }
        });
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this, String.valueOf(ratingBar.getRating()), Toast.LENGTH_LONG).show();
            }

        });

    }
}
We are getting widget reference from layout file and then using RatingBar setOnRatingBarChangeListener method to set listener for our RatingBar.

Step 4 : Running the app 

When you run the app, you will get below screen:
Android RatingBar Example

Click on stars to give appropriate rating

Android RatingBar Example tutorial
 When you submit , you will see below screen.

Android RatingBar toast example

We are done with Android Rating example.
Happy Android Learning !!

In this tutorial , we are going to see Android SeekBar example.
SeekBar is extension of ProgressBar. You can drag cursor left or right to select correct value. It is generally used in setting brightness or music progress or setting sound.
It is very easy to create SeekBar in Android. Just follow below steps to create SeekBar.

Source code:

Step 1 :Creating Project

Create an android application project named "SeekBarExampleApp".

Step 2 : Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.seekbarexampleapp.MainActivity">


    <SeekBar
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40dp"
        android:max="10"
        android:id="@+id/seekBar" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/seekBar"
        android:layout_marginLeft="29dp"
        android:layout_marginTop="14dp" />
</RelativeLayout>

Step 3 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.seekbarexampleapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends AppCompatActivity {

    private SeekBar seekBar;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        textView = (TextView) findViewById(R.id.textView);
        // Set default value to 0
        textView.setText(seekBar.getProgress() + "/" + seekBar.getMax());
        seekBar.setOnSeekBarChangeListener(
                new OnSeekBarChangeListener() {
                    int progress = 0;
                    @Override
                    public void onProgressChanged(SeekBar seekBar,
                                                  int progresValue, boolean fromUser) {
                        progress = progresValue;
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        // Display the value in textview
                        textView.setText("Progress : "+progress + "/" + seekBar.getMax());
                    }
                });
    }


}

We are getting widget reference from layout file and then using SeekBar's setOnSeekBarChangeListener method to set listener for our seekbar.

Step 4 : Running the app 

When you run the app, you will get below screen:


Drag ping circle and use it to set the value for SeekBar.

We are done with Android SeekBar example.
Happy Android Learning !!

In this post, we will see how to add internet permission in android studio.

When you are working on app which wants to access internet, you need to add extra permission in androidManifest.xml else your application won't be able to access internet.
So you need to put below code in AndroidManifest.xml file to access internet in your app.
<uses-permission android:name="android.permission.INTERNET" />

Why do you need to put extra permission to access internet in your app? 

You need to add this permission for user security. Whenever you download an app from play store, it asks for permission that application will use.
Lets say you are downloading an application which must not use internet at all and if you don't require any permission for that, it might be secretly putting data on some server. You need to explicitly put internet permission in AndroidManifest.xml, so user of your app will be aware of it.

How to add internet permission in AndroidManifest.xml in android studio. 

Step 1 : 

Go to app -> src -> main -> AndroidManifest.xml.

Step 2:

Copy following code:
<uses-permission android:name="android.permission.INTERNET" />

Step 3: 

Put it in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2blog.helloworldapp">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".HelloWorldActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
Done, we have added internet permission to AndroidManifest.xml. Your application must be able to access internet now.

This is another post in the series of mock questions for OCAJP exam. One of the exam objective is “Apply encapsulation principles to a class”.
This exam objective tests your knowledge on how to write a class that meets the encapsulation principles and validate your understanding.
I have prepared a set of good mock questions for this objective that might be useful for the readers who are preparing for the OCAJP 8 certification exam.

Encapsulation mock questions 

1. Which Java feature uses access modifiers to protect class data (variables)? 

A. Abstraction
B. Inheritance
C. Polymorphism
D. Encapsulation
E. Data hiding

2. What is Encapsulation ? 

A. Variables are public and public setter/getter methods are provided to change/access their values.
B. Variables are default and protected setter/getter methods are provided to change/access their values.
C. Variables are protected and public setter/getter methods are provided to change/access their values. D. Variables are private and protected setter/getter methods are provided to change/access their values.
E. Variables are private and public setter/getter methods are provided to change/access their values.

3. Which are true about Encapsulation ? (select 2 options)

A. A class can have total control over what data is stored in its fields.
B. Classes can get functionality from other classes.
C. Classes expose only certain fields and methods to other classes for access.
D. Classes contains abstract methods which must be implemented by it’s sub classes.
 4. How can you make the below class to exhibit fully encapsulation ?
public class Student {
 public int id;
 protected String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

}
A. No need of changes.
B. Make all properties private.
C. Make all methods protected.
D. Make all properties private and provide setter method for name property.
E. Make all properties private and remove setter method for id property.

5. How can you make the below class to exhibit fully encapsulation ?

public class Rectangle {
 public int length;
 public int width;
 public int area;

 public void setLength(int length) {
  this.length = length;
  calculateArea();
 }

 public void setWidth(int width) {
  this.width = width;
  calculateArea();
 }

 private void calculateArea() {
  this.area = this.length * this.width;

 }

 protected int getArea() {
  return area;
 }

}
A. No need of changes.
B. Make all properties private.
C. Make all methods protected.
D. Make all properties private and provide setter method for area property.
E. Make all properties private and getArea method public.

Answers 

1. Correct option : D Encapsulation uses access modifiers to protect variables.
2. Correct option : E To make a class as fully encapsulated, make variables as private and provide setters methods to assign or change variable values and provide getters methods to get variable values.
3. Correct options : A, C With Encapsulation your classes can expose only certain fields and methods to other classes for access and class can have total control over what data is stored in its fields.
4. Correct option : D To make the above class as fully encapsulated, make all variables as private and give setter method for name property for assigning data to name property.
5. Correct option : E To make the above class as fully encapsulated, make all variables as private and give public to getArea method.
If you are preparing for the OCAJP certification exam, the following references would be much useful.
• OCAJP 8 Exam Curriculum
• OCAJP Forums
• How to prepare for OCAJP Exam?

In this post, we will see how to enable or disable Wifi in android programmatically.
It is very simple to enable or disable wifi from android code.
For enabling WiFi:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
For disabling Wifi:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
So you can enable or disable WiFi using WifiManger class.
You need to add extra permissions in AndroidManifest.xml to enable or disable Wifi.

Source code:

Step 1 :

Create an android application project named "EnableDisableWiFiApp".

Step 2:

Add following permissions in AndoridManifest.xml.
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
 Go to app -> src -> main -> AndroidManifest.xml and add above permissions. AndroidManifest.xml will look like below xml.
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2blog.enabledisablewifiapp">
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Step 3 :

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:gravity="center"
    android:orientation="vertical">

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="false"
       />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
         />

</LinearLayout>

Step 4:

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.enabledisablewifiapp;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.java2blog.enabledisablewifiapp.R;

public class MainActivity extends AppCompatActivity {

    ToggleButton toggleButton;
    TextView textView;

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

        // Getting toggle button and textView from activity_main
        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
        textView = (TextView) findViewById(R.id.textView);
        
        // Put listener on toggle button
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked) {
                    textView.setText("WiFi is ON");
                    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                    wifi.setWifiEnabled(true);
                } else {
                    textView.setText("WiFi is OFF");
                    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                    wifi.setWifiEnabled(false);
                }
            }
        });
        // For initial setting
        if (toggleButton.isChecked()) {
            textView.setText("WiFi is ON");
            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wifi.setWifiEnabled(true);
        } else {
            textView.setText("WiFi is OFF");
            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wifi.setWifiEnabled(false);
        }
    }
}

Step 5: 

Run the app
When you run the app, you will get below screen:
When you click on toggle button, you will get below screen:

In this post, we will see how to enable or disable Bluetooth in android programmatically.
It is very simple to enable or disable bluetooth from android code.
For enabling Bluetooth:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.enable();
For disabling Bluetooth:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.disable();
So you can enable or disable Bluetooth using BluetoothAdapter class.
You need to add extra permissions in AndroidManifest.xml to enable or disable Bluetooth.

Source code:

Download
click to begin
20KB .zip

Step 1 :

Create an android application project named "EnableDisableBluetoothApp".

Step 2:

Add following permissions in AndoridManifest.xml.
 
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
 Go to app -> src -> main -> AndroidManifest.xml and add above permissions. AndroidManifest.xml will look like below xml.
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2blog.enabledisablebluetoothapp">
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Step 3 :

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:gravity="center"
    android:orientation="vertical">

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="false"
        />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        />

</LinearLayout>

Step 4:

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.enabledisablebluetoothapp;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.java2blog.enabledisablebluetoothapp.R;

public class MainActivity extends AppCompatActivity {

    ToggleButton toggleButton;
    TextView textView;

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

        // Getting toggle button and textView from activity_main
        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
        textView = (TextView) findViewById(R.id.textView);

        // Put listener on toggle button
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked) {
                    textView.setText("Bluetooth is ON");
                    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                    adapter.enable();
                } else {
                    textView.setText("Bluetooth is OFF");
                    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                    adapter.disable();
                }
            }
        });
        // For initial setting
        if (toggleButton.isChecked()) {
            textView.setText("Bluetooth is ON");
            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            adapter.enable();
        } else {
            textView.setText("Bluetooth is OFF");
            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            adapter.disable();
        }
    }
}

Step 5: 

Run the app
When you run the app, you will get below screen:

When you click on toggle button, you will get below screen:


Sometimes when you are developing an android application, you may want to get current battery health

In this post, we are going to see how to get current battery voltage in android. You can use intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0) to get information about current battery voltage.

Source code:

Download
click to begin
20KB .zip

Step 1 :

Create an android application project named "GetBatteryHealthApp".

Step 2 :

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.getbatteryhealthapp.MainActivity">

    <TextView
        android:id="@+id/textViewBatteryHealth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Current Battery Health"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/buttonBatteryHealth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewBatteryHealth"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="Click here to Get battery Health" />
</RelativeLayout>

Step 3:

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.checkbatteryhealthapp;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.java2blog.checkbatteryhealthapp.R;

public class MainActivity extends Activity {

    TextView textview;
    Button button;
    IntentFilter intentfilter;
    int deviceHealth;
    String currentBatteryHealth="Battery Health ";
    int batteryLevel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.buttonBatteryHealth);
        textview = (TextView)findViewById(R.id.textViewBatteryHealth);

        intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);

            }
        });

    }

    private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            deviceHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);

            if(deviceHealth == BatteryManager.BATTERY_HEALTH_COLD){

                textview.setText(currentBatteryHealth+" = Cold");
            }

            if(deviceHealth == BatteryManager.BATTERY_HEALTH_DEAD){

                textview.setText(currentBatteryHealth+" = Dead");
            }

            if (deviceHealth == BatteryManager.BATTERY_HEALTH_GOOD){

                textview.setText(currentBatteryHealth+" = Good");
            }

            if(deviceHealth == BatteryManager.BATTERY_HEALTH_OVERHEAT){

                textview.setText(currentBatteryHealth+" = OverHeat");
            }

            if (deviceHealth == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){

                textview.setText(currentBatteryHealth+" = Over voltage");
            }

            if (deviceHealth == BatteryManager.BATTERY_HEALTH_UNKNOWN){

                textview.setText(currentBatteryHealth+" = Unknown");
            }
            if (deviceHealth == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){

                textview.setText(currentBatteryHealth+" = Unspecified Failure");
            }
        }
    };
}
As we want to get battery level health information, we need to register broadcast receiver and intent filter. An intent filter is used to tell native battery app that this app is listening for changes in native battery app.
Lets understand above code:

Intent.ACTION_BATTERY_CHANGED: 

If you see the code we have used Intent.ACTION_BATTERY_CHANGED to get current battery info. It is sticky broadcast which contain battery charging state , level and other info. BatteryManager class contains all constant strings.
Sticky broadcast is broadcast which will remain active once registered.
MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
Here we are registering created broadcastreceiver to the MainActivity and intent filter is listening for battery change events.

Run the app:

When you run above app on actual device, you will get below screen :


When you click on button, you will get below screen :

Sometimes when you are developing an android application, you may want to get current batter voltage

In this post, we are going to see how to get current battery voltage in android. You can use intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0) to get information about current battery voltage.

Source code:

Download

click to begin

20KB .zip

Step 1 :

Create an android application project named "GetBatteryVoltageApp".

Step 2 :

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.getbatteryvoltageapp.MainActivity">

    <TextView
        android:id="@+id/textViewBatteryVol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/buttonBatteryVol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewBatteryVol"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="Click here to Get battery voltage" />
</RelativeLayout>

Step 3:

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.getbatteryvoltageapp;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.java2blog.getbatteryvoltageapp.R;

public class MainActivity extends Activity {

    TextView volTextView;
    Button button;
    IntentFilter intentfilter;
    int batteryVol;
    float fullVoltage;
    String currentBatteryVol="Current Battery Voltage :";
    int batteryLevel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.buttonBatteryVol);
        volTextView = (TextView)findViewById(R.id.textViewBatteryVol);

        intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);

            }
        });
    }

    private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            
            batteryVol = (int)(intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0));
            fullVoltage = (float) (batteryVol * 0.001);
            volTextView.setText(currentBatteryVol +" "+fullVoltage+" volt");

        }
    };
}
As we want to get battery level change information, we need to register broadcast receiver and intent filter. An intent filter is used to tell native battery app that this app is listening for changes in native battery app.
Lets understand above code:

Intent.ACTION_BATTERY_CHANGED: 

If you see the code we have used Intent.ACTION_BATTERY_CHANGED to get current battery info. It is sticky broadcast which contain battery charging state , level and other info. BatteryManager class contains all constant strings.
Sticky broadcast is broadcast which will remain active once registered.
MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
Here we are registering created broadcastreceiver to the MainActivity and intent filter is listening for battery change events.

Run the app:

When you run above app on actual device, you will get below screen :

When you click on button, you will get below screen :

Sometimes when you are developing an android application, you may want to get current batter temperature
For example:
Lets say if battery temperature is too high, you may want to close some application.
In this post, we are going to see how to get current battery temperature in android.

Source code:

Download
click to begin
20KB .zip

Step 1 :

Create an android application project named "GetBatteryTemperatureApp".

Step 2 :

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.getbatterytemperatureapp.MainActivity">

    <TextView
        android:id="@+id/textViewBatteryTemp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/buttonBatteryTemp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewBatteryTemp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="Click here to Get battery temperature" />
</RelativeLayout>

Step 3:

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.getbatterytemperatureapp;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.java2blog.getbatterytemperatureapp.R;

public class MainActivity extends Activity {

    TextView tempTextView;
    Button button;
    IntentFilter intentfilter;
    float batteryTemp;
    String currentBatterytemp="Current Battery temp :";
    int batteryLevel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.buttonBatteryTemp);
        tempTextView = (TextView)findViewById(R.id.textViewBatteryTemp);

        intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);

            }
        });

    }

    private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            batteryTemp = (float)(intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0))/10;

            tempTextView.setText(currentBatterytemp +" "+batteryTemp +" "+ (char) 0x00B0 +"C");

        }
    };


}
As we want to get battery level change information, we need to register broadcast receiver and intent filter. An intent filter is used to tell native battery app that this app is listening for changes in native battery app.
Lets understand above code:

Intent.ACTION_BATTERY_CHANGED: 

If you see the code we have used Intent.ACTION_BATTERY_CHANGED to get current battery info. It is sticky broadcast which contain battery charging state , level and other info. BatteryManager class contains all constant strings.
Sticky broadcast is broadcast which will remain active once registered.
MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
Here we are registering created broadcastreceiver to the MainActivity and intent filter is listening for battery change events.

Run the app:

When you run above app on actual device, you will get below screen :
When you click on button, you will get below screen :

Sometimes when you are developing an android application, you may want to get current batter level or state.
For example:
Lets say you want to make a rule that if battery level is less than 15%, turn off all background processes in android.
In this post, we are going to see how to get current battery level and state in android.
There are five android battery state which you must know.
  • BatteryManager.BATTERY_STATUS_CHARGING
  • BatteryManager.BATTERY_STATUS_DISCHARGING
  • BatteryManager.BATTERY_STATUS_FULL
  • BatteryManager.BATTERY_STATUS_UNKNOWN
  • BatteryManager.BATTERY_STATUS_NOT_CHARGING

Source code:

Download
click to begin
20KB .zip

 Step 1 :

Create an android application project named "GetBatteryInfoApp".

Step 2 :

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.getbatteryinfoapp.MainActivity">

    <TextView
        android:id="@+id/textViewBatteryStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Current Battery Status"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/buttonBatteryStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewBatteryStatus"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="Click here to Get battery Info" />
</RelativeLayout>

Step 3:

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.checkbatterystatusapp;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.java2blog.checkbatterystatusapp.R;

public class MainActivity extends Activity {

    TextView textview;
    Button button;
    IntentFilter intentfilter;
    int deviceStatus;
    String currentBatteryStatus="Battery Info";
    int batteryLevel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.buttonBatteryStatus);
        textview = (TextView)findViewById(R.id.textViewBatteryStatus);

        intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);

            }
        });

    }

    private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int batteryLevel=(int)(((float)level / (float)scale) * 100.0f);

            if(deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING){

                textview.setText(currentBatteryStatus+" = Charging at "+batteryLevel+" %");

            }

            if(deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING){

                textview.setText(currentBatteryStatus+" = Discharging at "+batteryLevel+" %");

            }

            if (deviceStatus == BatteryManager.BATTERY_STATUS_FULL){

                textview.setText(currentBatteryStatus+"= Battery Full at "+batteryLevel+" %");

            }

            if(deviceStatus == BatteryManager.BATTERY_STATUS_UNKNOWN){

                textview.setText(currentBatteryStatus+" = Unknown at "+batteryLevel+" %");
            }


            if (deviceStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING){

                textview.setText(currentBatteryStatus+" = Not Charging at "+batteryLevel+" %");

            }

        }
    };
}
As we want to get battery level change information, we need to register broadcast receiver and intent filter. An intent filter is used to tell native battery app that this app is listening for changes in native battery app.
Lets understand above code:

Intent.ACTION_BATTERY_CHANGED: 

If you see the code we have used Intent.ACTION_BATTERY_CHANGED to get current battery info. It is sticky broadcast which contain battery charging state , level and other info. BatteryManager class contains all constant strings.
Sticky broadcast is broadcast which will remain active once registered.
MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
Here we are registering created broadcastreceiver to the MainActivity and intent filter is listening for battery change events.

Run the app:

When you run above app on actual device, you will get below screen :

When you click on button, you will get below screen :
So it shows current battery state and level.

In this post, we are going to create first android app which will show result of multiplication of two user input numbers. We have already created Android hello world example before but it was too basic.
We are going to design our screen as below:
Android First App

We are not going to put much validations here. We will just create above screen which will show multiplication of two numbers in Result textview.

Steps for creating first android app using Android studio:

Step 1: 

Create a new android project named "MultiplicationApp". Provide Activity name as "MultiplicationActivity" instead of "HelloWorldActivity".

Step 2:

Go to res -> layout -> activity_multiplication.xml. Paste following code in xml file to create multiplication screen.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_multiplication"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.multiplicationapp.MultiplicationActivity">

    <TextView
        android:text="Number 1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="38dp"
        android:layout_marginStart="38dp"
        android:layout_marginTop="103dp"
        android:id="@+id/textView1"
        android:textSize="18sp" />

    <TextView
        android:text="Number 2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="206dp"
        android:layout_marginLeft="38dp"
        android:layout_marginStart="38dp"
        android:id="@+id/textView2"
        android:textSize="18sp" />
    <TextView
        android:text="Result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="309dp"
        android:layout_marginLeft="38dp"
        android:layout_marginStart="38dp"
        android:id="@+id/textView3"
        android:textSize="18sp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textView1"
        android:layout_toEndOf="@+id/textView1"
        android:layout_marginLeft="41dp"
        android:layout_marginStart="41dp"
        android:layout_marginTop="91dp"
        android:id="@+id/editText1" />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textView2"
        android:layout_toEndOf="@+id/textView2"
        android:layout_marginLeft="41dp"
        android:layout_marginStart="41dp"
        android:layout_marginTop="182dp"
        android:id="@+id/editText2" />

    <Button
        android:text="Multiply"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/textView2"
        android:layout_toEndOf="@+id/textView2"
        android:layout_marginBottom="48dp"
        android:id="@+id/button" />

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/textView3"
        android:layout_toRightOf="@+id/button"
        android:layout_toEndOf="@+id/button"
        android:layout_marginLeft="35dp"
        android:layout_marginStart="35dp"
        android:id="@+id/textView4"
        android:textSize="18sp" />
</RelativeLayout>

Step 3: 

Go to app -> java -> package -> MultiplicationActivity.java.
Change MultiplicationActivity.java as below:
package com.java2blog.multiplicationapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MultiplicationActivity extends AppCompatActivity {

    private EditText edittext1,edittext2;
    private TextView textView;
    private Button buttonMulti;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_multiplication);
        multiplyOnButtonClick();
    }

    public void multiplyOnButtonClick(){
        edittext1=(EditText)findViewById(R.id.editText1);
        edittext2=(EditText)findViewById(R.id.editText2);
        textView=(TextView) findViewById(R.id.textView4);
        buttonMulti=(Button)findViewById(R.id.button);

        buttonMulti.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                String value1=edittext1.getText().toString();
                String value2=edittext2.getText().toString();
                Double num1=Double.parseDouble(value1);
                Double num2=Double.parseDouble(value2);
                double multi=num1*num2;
                textView.setText(""+multi);
                Toast.makeText(getApplicationContext(),String.valueOf(multi),Toast.LENGTH_LONG).show();
            }

        });

    }
}
To get any widget reference in activity class, you can use id which you have defined in layout xml file. So to get reference for editText corresponds to "Number 1" in the screen, we have used below code:
EditText edittext1=(EditText)findViewById(R.id.editText1);
You can get text entered by user in that edit text by using below code:
String value1=edittext1.getText().toString();
We have also put click listener on button named "Multiply".
 buttonMulti.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                String value1=edittext1.getText().toString();
                String value2=edittext2.getText().toString();
                Double num1=Double.parseDouble(value1);
                Double num2=Double.parseDouble(value2);
                double multi=num1*num2;
                textView.setText(""+multi);
                Toast.makeText(getApplicationContext(),String.valueOf(multi),Toast.LENGTH_LONG).show();
            }

        });

Step 4 : 

Run the app. When you run above app on emulator, you will get below screen:
Android first app preparation
Provide user input numbers and click on multiply, you will get the result.
Android first app development
We are done with first  android app using android studio.
Happy Android Learning!!
 

Java tutorial for beginners Copyright © 2012