Home Blog Page 96

Introduction To Java Programming – what is java

2
introduction to java programming.png
introduction to java programming.png

Introduction To JAVA

JAVA is a programming language that is used in many software developments like Android App Development and much more. It is class-based and object-oriented programming whose syntax is influenced by C++. The primary goals of JAVA are to be simple, object-oriented, robust, secure, and high level. JAVA application runs on JVM (JAVA Virtual Machine).

Tutorial On JAVA Topics

TopicDescription
VariablesLearn about variables and how they are created for storing information in memory. A variable is a container that holds the value while the java program is executed. In Java, there are 3 types of variables namely Local Variable, Static Variable, Instance Variable.
Data TypesLearn about Data Types (i.e. byte, int, char, etc) which is basically a type of information we want to store in the variable. Weather data is number, Character, or something else like boolean value.
StringThe string is nothing but a character array for example “protocoderspoint” is a string of 16 characters as shown.
KeywordsKeywords in JAVA are a predefined list of keywords which has a specific meaning and cannot be used in the Java programming language as an identifier, such as the name of a variable, method, class, function, or label.
OperatorsIn computer, a programming Operator is a symbol that tells the compiler to perform specific action which can be mathematical or logical like addition, subtraction, multiplication, etc.
Class And ObjectsThe concept of class comes into the role when we see certain types of objects or things around us and the common idea or a blueprint behind this type of object is called Class. Object is an instance of the class.
MethodA method is a self-defined block of code that performs a specific task.

Picasso android library tutorial – Picasso image loader

2
picasso android image loader library
picasso android image loader library

Picasso android library is – A powerful image loading, image downloading, and image caching library for Android.

This Picasso library allows for hassle-free image loading in your application—often in one line of code!

Picasso dependency is an open-source Android library that is developed and maintained by Square. This library hides all the complexity as it will deal with back-on threading, loading images from the internet, and even caching. Picasso makes memory-efficient to resize and transform images. Picasso Library makes it quite easier for displaying images from remote locations.

Final Output of this Picasso android tutorial.

picasso android image loader
picasso android image loader

1. Feature of this Universal image loader library

  • Handling ImageView recycling and download cancelation in an adapter.
  • Complex image transformations with minimal memory use.
  • Automatic memory and disk caching.

2. Callbacks and Targets In Picasso In Android

Picasso library loads an image in two ways that are synchronously and Asynchronously.

.fetch() –this is an asynchronously load the image into a background thread. This method only saves the image into the disk or memory cache. It’s neither going to load the image into image view nor it is going to return any Bitmap. If you want to reduce the reduce image loading times and if you know that the image is needed by you shortly after then it could be used to fill the image cache in the background.

.get() – It returns a Bitmap object and loads an image synchronously. But it will freeze the UI if you will call it from the UI thread.

into(ImageView targetImageView) – It is provided by Picasso where you can Specify your target Imageview in which the image is supposed to get displayed.

In this tutorial, you will learn How to use Picasso android library to load images from the locally drawable drive and even how to load images from a URL.

How to add Picasso library in android studio Picasso dependency?

Navigate to your project file at the left side of your android studio. You will see “Gradle Scripts” open the drop down list, you will see a build.gradle (Module:app) open it.

adding picasso dependency library
adding picasso dependency library

Before using Picasso we have to add its dependency in build.gradle file in module level : app.

Picasso dependency

implementation 'com.squareup.picasso:picasso:2.71828'

NOTE: To load image from URL android  you need a internet permission that you need to assign in android manifest.xml file. As shown in below image.

adding internet permission in android studio
adding internet permission in android studio

add internet access permission in AndroidMainfest.xml file.

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

Picasso to load image

To Simply load an image in and imageView

Picasso.get()
.load("https://protocoderspoint.com/wp-content/uploads/2019/10/protocoderspoint-rectangle-round-.png")
.into(imageView);

show placeholder Picasso android library

Picasso.get() .
load("URL PATH") .
placeholder(R.drawable.user_placeholder) .
error(R.drawable.user_placeholder_error) .
into(imageView);

Picasso supports both download and error placeholders as optional features.

We can specify an image as a place holder until the image is being loaded, placeholder are commenly used with we face any technical issue like network failed to load the picasso image, in such a case we make use of placeholder in picasso so that we can show a default image in place of real image.We can also give an image as an error handler if any error occurs while loading the image.

show error image using Picasso library

Picasso.get() 
.load("URL PATH") 
.error(R.drawable.user_placeholder_error)
.into(imageView);

Image Transformation picasso android studio

Picasso.get()
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

As you know picasso is a universal image loader,So we can change image dimensions to fit layouts and reduce memory size utilized by image.

Image Rotation In Picasso

Picasso.with(context)

       .load("image source here")

       .rotate(90f)

       .into(someImageView);

This will rotate the image by 90 degrees.

Picasso Android Image loader library github.

Now let us begin by creating a project in android studio to implement Picasso universal image loader library.

Picasso Android Example

In the Example, i m loading an image from local and from URL when button is clicked OK.

Create a project with and of your wish package name  i m using “protocoderspoint.com.picassoandroidimageloader” and add following code in respective files

activity_main.xml

For User interface design.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Proto Coders Point"
        android:textColor="#0042FF"
        android:textSize="20sp"
        android:layout_marginBottom="15dp"
        android:textStyle="italic|bold"/>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="locally load image"/>

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="load image from URL">

    </TextView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="#093FC4"
        android:text="Click load button to load images ">

    </TextView>

    <Button
        android:id="@+id/load_images"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load images " />

</LinearLayout>
</LinearLayout>

Main_Activity.java

For back end programming in java

package protocoderspoint.com.picassoandroidimageloader;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity {

    ImageView local_image,url_image;
    Button load_images;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        local_image=(ImageView)findViewById(R.id.imageView2);
        url_image=(ImageView)findViewById(R.id.imageView3);

        load_images=(Button)findViewById(R.id.load_images);

        load_images.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Picasso.get().load(R.drawable.protocoder).into(local_image);
                Picasso.get().load("https://cdn.pixabay.com/photo/2012/04/24/11/54/picasso-39592_960_720.png").into(url_image);
            }
        });


    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="protocoderspoint.com.picassoandroidimageloader">

    <!--internet permission to load image from URL-->
    <uses-permission android:name="android.permission.INTERNET"/>

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

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

</manifest>

also read welcome-screen-github-library

Flutter Profile Page UI Design Using Flutter Card & ListTile Widget

4
Flutter Profile Page UI Design

Welcome To Proto Coders Point, In this tutorial, we will learn how to create a profile page UI Design app using Dart and Flutter. A quick sample app on how to create a simple profile screen page in flutter.

Similar profile page UI design 2 

Flutter Profile Page UI Design Using Flutter Card & ListTile Widget

The Final UI of Flutter profile page will look something like below screenshot.

Flutter Profile Page UI Design Using Flutter Card & ListTile Widget
Flutter Profile Page UI Design Using Flutter Card & ListTile Widget

Video Tutorial play here

Open android Studio and create a new flutter project.

File > New  > New Flutter Project

Give a name you your flutter project and set a path to store you flutter project.

Now you will a see a default counter code generated, that simply counts the number of times the button is pressed and display counting on the screeen.

You can just remove default code of flutter and shown in below Image.

flutter profile UI Design
flutter profile UI Design

So let’s begin with the actual code for Flutter profile page example UI Design.

before we start implement, we need the resources such as images and fonts to be set/copy in our project directory, For that we need to create 2 directory.

Directory

  1. images : to store all our project image resources.
  2. fonts : to store all our fonts style ttf extension files.

Here is how to create directory in android-studio ( flutter )

Right Click on project > New > Directory

creating a directory in flutter project
creating a directory in flutter project

like wise create a 2nd directory name “fonts”

download an icon and fonts from google

Icons made by Smashicons from www.flaticon.com

Copy both the image and fonts file in those directorys.

As shown in the highlighted area

NOTE: you also need to initialize the resources in  pubspec.yaml file

setting images in flutter pubspec.yaml android studio
setting images in flutter pubspec.yaml android studio

assets:
    - images/user.png
  fonts:
    - family: SourceSansPRO-Regular
      fonts:
        - asset: fonts/SourceSansPRO-Regular.ttf

Please check the indentation ( Many programmer face problems while setting  resources package )

Source Code of Flutter Profile UI Design

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            "Profile Page UI Design using Flutter ",
            style: TextStyle(fontSize: 18.0),
          ),
        ),
        backgroundColor: Colors.blue[300],
        body: SafeArea(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                CircleAvatar(
                  radius: 80,
                  backgroundImage: AssetImage('images/protocoder.png'),
                ),
                Text(
                  'Proto Coders Point',
                  style: TextStyle(
                    fontFamily: 'SourceSansPro',
                    fontSize: 25,
                  ),
                ),
                Text(
                  'Welcome',
                  style: TextStyle(
                    fontSize: 20,
                    fontFamily: 'SourceSansPro',
                    color: Colors.red[400],
                    letterSpacing: 2.5,
                  ),
                ),
                SizedBox(
                  height: 20.0,
                  width: 200,
                  child: Divider(
                    color: Colors.teal[100],
                  ),
                ),
                Text("Keep visiting protocoderspoint.com for more contents"),
                Card(
                    color: Colors.white,
                    margin:
                        EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                    child: ListTile(
                      leading: Icon(
                        Icons.phone,
                        color: Colors.teal[900],
                      ),
                      title: Text(
                        '+91 85465XXX8XX',
                        style:
                            TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                      ),
                    )),
                Card(
                  color: Colors.white,
                  margin:
                      EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                  child: ListTile(
                    leading: Icon(
                      Icons.cake,
                      color: Colors.teal[900],
                    ),
                    title: Text(
                      '08-05-1995',
                      style: TextStyle(fontSize: 20.0, fontFamily: 'Neucha'),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Explaination of flutter widget used in the above code.

Flutter Card Class

A material design card. A card has slightly rounded corners and a shadow.

A card is a sheet of Material used to represent some related information, for example an album, a geographical location, a meal, contact details, etc.

In the above lines of code Flutter Card i have used child that contains ListTile widget class  with leading icons and title.

Read more above flutter card on official site.

ListTile class

A single fixed-height row that typically contains some text as well as a leading or trailing icon.

It is the responsibility of the caller to ensure that title does not wrap, and to ensure that subtitle doesn’t wrap.

In the above lines of code Flutter ListTile  class that has leading with icons and title with text.

SizedBox Widget Class

A box with a specified size.

If given a child, this widget forces its child to have a specific width and/or height .

In the above code you can observe their is a tiny empty space in between call icon and phone number text

Divider Widget Class

thin horizontal line, with padding on either side.

In the material design language, this represents a divider. Dividers can be used in lists, Drawers, and elsewhere to separate content.

If you are new in flutter development check this post to learn about how to install fluttter in android studio

How to install flutter in android studio with First Flutter App Hello World

Google Flutter UI toolkit for mobile, web and desktop Applications

0
Google Flutter
Google Flutter

Google Flutter is one of a open source user interface(UI) Software Development Toolkit that is been created/ developed by Google, for Software developer which makes programmer to design UI natively compiled applications for mobileweb, and desktop from a single codebase (Google Flutter).

The First version of Flutter Application was named as “SKY”,That was smoothly running on any of the android operating system. Fluttter was released on 2015 by a developer “Summit”. Google announced Flutter Release Preview 2 which is the last big release before Flutter 1.0. 

After somedays of testing the final version was released on December 4th of 2018 as flutter 1.0 at it live event, which was he first “stable” version of the Framework.

Which Language Google Flutter prefers to use?

introduction on flutter
introduction on flutter

Google Flutter are written in the Dart  programming language and make use of many of the language’s more advanced features.

Flutter framework for crafting high-quality native interfaces on iOS and Android in record time. Flutter works with existing code, is used by developers and organizations around the world, and is free and open source. Watch this Video

Widgets in Flutter UI

UI design in Flutter development involves create “Widgets” from other Widgets. Flutter Application is basically a groups of widgets build together to form a beautiful UI/ UX experience.

Flutter widget
Flutter widget

A widget is an immutable description of part of a user interface.” A human being will tell you it’s a Blueprint, which is a much easier way to think about it.

The MyApp Widget contains all the other Widgets, which can contain even smaller Widgets, and together they make up your app.

Google Flutter Hello World Example

Flutter Hello World Program to display text on the screen

import 'package:flutter/material.dart';

void main() => runApp(HelloWorldApp());

class HelloWorldApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello World App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hello World App'),
        ),
        body: Center(
          child: Text('Hello World'),
        ),
      ),
    );
  }
}

What are the feature of flutter framework?

Fast Development

Flutter is very much fast in development, With Statefull Flutter’s hot reload feature helps you quickly and easily experiment, build UIs, add features, and fix bugs within a seconds.

Expressive and Flexiable UI

Quickly ship features with a focus on native end-user experiences. Layered architecture allows for full customization, which results in incredibly fast rendering and expressive and flexible designs.[1]

Native Performation

Flutter’s widgets incorporate all critical platform differences such as scrolling, navigation, icons and fonts to provide full native performance on both iOS and Android. Here are some examples of application that are build using flutter

How to install flutter plugin in android studio?

Here i have demonstrated installation process in ubuntu android-studio same applied to Windows OS.

Check out this post install flutter plugin in android studio.

Flutter is the Future of mobile application development.

What you should learn in 2021? Flutter vs React native 2021

DND Dice Roller Android App tutorial with source code

0
dnd Dice Roller Android App tutorial with source code
dnd Dice Roller Android App tutorial with source code

Hi Guys Welcome to Proto Coders Point. In this android tutorial we will learn how to create a simple dice roller app

A dnd dice roller app using android-studio. who want to learn and gain more knowledge in developing an android application.

This tutorial is not be a fancy 3D dice roller but it’ll be a simple dice that roller with some animation effect and generate a random number from 1 – 6 and show similar image of dice roller to the user.

The main moto of this android tutorial is just to build programming skill and logic.

Demo of how the final Dice Roller dnd android app looks

android dice roller app tutorial
android dice roller app tutorial ( gif )

All the image given below are free to use .

one
 

dice vector images Download from tekeye.uk

 

The sound of a dice roll is stored in shake_dice.mp3. It is by Mike Koenig and is from SoundBilble.com.

dnd dice roller android studio tutorial mini project.

let’s start with creating a new project in android-studio

File > New > New Project

Give a proper name to project ( Dice Roller ) , Select a project storage destination , select minimum API : 22 ,Android 5.1 (Lollipop), all set android project will be get ready in several seconds.

Add the dice resources (from above) to the project by copying them to the res folder in android – studio.

Dice Roller app resources android studio
Dice Roller app resources android studio

Optional Changes

To set a icon from this dice roller app project go to AndroidManifest.xml file

android:icon="@drawable/dice3d" and android:roundIcon="@mipmap/dice3d_rounded".

Designing a UI Layout spin the dice roller

Designing a UI Layout spin the dice roller
main_activity.xml Layout Design

main_activity.xml

Copy the below code in main_activity.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="131dp"
        android:layout_height="121dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/dice3d160" />

    <TextView
        android:id="@+id/dice_no"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dice Number : ? Spin it "
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        app:layout_constraintVertical_bias="0.157" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0184FC"
        android:textSize="25sp"
        android:textStyle="italic|bold"
        android:text="Click on the Dice to Spin it"
        app:layout_constraintBottom_toTopOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Android Dice Roller Source Code

ActivityMain.java

package protocoderspoint.com.androiddicerollertutorial;

import android.media.AudioAttributes;
import android.media.SoundPool;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import protocoderspoint.PreLollipopSoundPool;

public class MainActivity extends AppCompatActivity {
    ImageView dice_picture;     //reference to dice picture
    Random rng=new Random();    //generate random numbers
    SoundPool dice_sound;       //For dice sound playing
    int sound_id;               //Used to control sound stream return by SoundPool
    Handler handler;            //Post message to start roll
    Timer timer=new Timer();    //Used to implement feedback to user
    boolean rolling=false;      //Is die rolling?
    RotateAnimation rotate;
    int soundplay;
    TextView dice_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Our function to initialise sound playing

        dice_no=(TextView)findViewById(R.id.dice_no);
        InitSound();
        //Get a reference to image widget
        dice_picture = (ImageView) findViewById(R.id.imageView);
        dice_picture.setOnClickListener(new HandleClick());
         rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(3000);
        rotate.setInterpolator(new LinearInterpolator());

        //link handler to callback
        handler=new Handler(callback);
    }

    //User pressed dice, lets start
    private class HandleClick implements View.OnClickListener {
        public void onClick(View arg0) {
            if (!rolling) {
                rolling = true;
                //Show rolling image
                dice_picture.setImageResource(R.drawable.dice3d160);
                //Start rolling sound
              soundplay=  dice_sound.play(sound_id, 1.0f, 1.0f, 0, 0, 1.0f);
                //Pause to allow image to update
                dice_picture.startAnimation(rotate);
                timer.schedule(new Roll(), 3000);
            }
        }
    }

    //New code to initialise sound playback
    void InitSound() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //Use the newer SoundPool.Builder
            //Set the audio attributes, SONIFICATION is for interaction events
            //uses builder pattern
            AudioAttributes aa = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();

            //default max streams is 1
            //also uses builder pattern
            dice_sound= new SoundPool.Builder().setAudioAttributes(aa).build();

        } else {
            //Running on device earlier than Lollipop
            //Use the older SoundPool constructor
            dice_sound= PreLollipopSoundPool.NewSoundPool();
        }
        //Load the dice sound
        sound_id=dice_sound.load(this,R.raw.shake_dice,1);
    }

    //When pause completed message sent to callback
    class Roll extends TimerTask {
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }

    //Receives message from timer to start dice roll
    Handler.Callback callback = new Handler.Callback() {
        public boolean handleMessage(Message msg) {
            //Get roll result
            //Remember nextInt returns 0 to 5 for argument of 6
            //hence + 1
            switch(rng.nextInt(6)+1) {
                case 1:
                    rotate.cancel();
                    dice_no.setText("Dice Number : 1");
                    dice_picture.setImageResource(R.drawable.one);
                    break;
                case 2:
                    rotate.cancel();
                    dice_no.setText("Dice Number : 2");
                    dice_picture.setImageResource(R.drawable.two);
                    break;
                case 3:
                    rotate.cancel();
                    dice_no.setText("Dice Number : 3");
                    dice_picture.setImageResource(R.drawable.three);
                    break;
                case 4:
                    rotate.cancel();
                    dice_no.setText("Dice Number : 4");
                    dice_picture.setImageResource(R.drawable.four);
                    break;
                case 5:
                    rotate.cancel();
                    dice_no.setText("Dice Number : 5");
                    dice_picture.setImageResource(R.drawable.five);
                    break;
                case 6:
                    rotate.cancel();
                    dice_no.setText("Dice Number : 6");
                    dice_picture.setImageResource(R.drawable.six);
                    break;
                default:
            }
            rolling=false;  //user can press again
            return true;
        }
    };

    //Clean up
    protected void onPause() {
        super.onPause();
        dice_sound.pause(sound_id);
    }
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}

To support APIs pre Lollipop add a new class called PreLollipopSoundPool,java

package protocoderspoint;

import android.media.AudioManager;
import android.media.SoundPool;

/**
 * Created a pre Lollipop SoundPool
 */
public final class PreLollipopSoundPool {
    @SuppressWarnings("deprecation")
    public static SoundPool NewSoundPool() {
        return new SoundPool(1, AudioManager.STREAM_MUSIC,0);
    }
}

Explanation of the above ActivityMain.java Code

Random number

Random java – user to generate a random number from 1 to 6

Random rng=new Random();

//Get roll result
//Remember nextInt returns 0 to 5 for argument of 6
//hence + 1
rng.nextInt(6)+1

Rotate a imageView in android-studio

RotateAnimation rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

Set Duration for the rotator in milli-sec like (1 sec = 1000milli sec )

rotate.setDuration(3000);
rotate.setInterpolator(new LinearInterpolator());

Learn more about setInterpolator ( new LinearInterpolator())

Soundpool

In Android-studio Java Soundpool is used to play a sound like in our project we have used a dice roller sound effect to feel like a real dice is spinning. Code below

  SoundPool dice_sound;       //For dice sound playing
 
int sound_id;               //Used to control sound stream return by SoundPool

New code to initialise sound playback

 //New code to initialise sound playback
    void InitSound() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //Use the newer SoundPool.Builder
            //Set the audio attributes, SONIFICATION is for interaction events
            //uses builder pattern
            AudioAttributes aa = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();

            //default max streams is 1
            //also uses builder pattern
            dice_sound= new SoundPool.Builder().setAudioAttributes(aa).build();

        } else {
            //Running on device earlier than Lollipop
            //Use the older SoundPool constructor
            dice_sound= PreLollipopSoundPool.NewSoundPool();
        }
        //Load the dice sound
        sound_id=dice_sound.load(this,R.raw.shake_dice,1);
    }

As java codes runs within a fraction of seconds, it will be hard to view the image is getting spinned or an real animation effect, i have made use of Timer method with will help programmer to show dice rolling effect.

Timer timer=new Timer();    //Used to implement Time to spin

Timer is used to provide a delay in roll.

timer.schedule(new Roll(), 3000);

above snippet code timer is set to 3 sec’s where the viewer will be above to see the animation effect for 3 sec.

Download source code Dice Roller android App

Downlaod from drive

Android Alert Dialog Box with a list of Options

0
Adding a list of options in Alert Dialog in android tsudio
Adding a list of options in Alert Dialog in android tsudio

Working Demo

Custom Alert Dialog with list of options.

An AlertDialog is a Simplest way to get response from a user by providing them a option to select .This post will show you how can we add a list of choices to our AlertDialog box in android.

If you check official documentation that have describe that, their are total three kinds of lists that can be used with an AlertDialog in android :

  1. Traditional single-choice list
  2. Persistent single-choice list (radio buttons)
  3. Persistent multiple-choice list (checkboxes)

In this Tutorial i will give demo on all 3 kinds of alert dialog choice list

Basic to build a Alert Dialog Box

// setup the alert builder

 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose an Option");

Manually Create a Array list to display on a alert dialog

// add a list
        String[] options = {"Option1", "Option2", "Option3", "Option4", "Option3"};

Create a dialog box and show to user on action

// create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();

Traditional single-choice Android alert Dialog list.

Traditional Android Alert Dialog list options
Traditional Alert Dialog list options

The way to make use of a traditional single-choice list is to use setItems method.

Call the Below Function on button Click

 public void TraditionallistDialog()
    {
        // setup the alert builder

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose an Option");

        // add a list

        String[] options = {"Option1", "Option2", "Option3", "Option4", "Option3"};

        //Pass the array list in Alert dialog
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0: // Select option task
                    case 1: // Config it as you need here
                    case 2:
                    case 3:
                    case 4:
                }
            }
        });
// create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

In Traditional list their is no need to set any positive button, as user select any list from alert dialog list the item will automatically gets selected and alert dialog get closed.

Radio button single-choice Android alert Dialog list.

Radio button alert dialog list options
Radio button alert dialog list options

The Best advantage of the radio button list over a Simple traditional list is that the user will be able to check which is the default selected option in the list where as in Traditional list their is no default option.

The way to make a radio button list is to use setSingleChoiceItems.

Call the below code on button Click.

public  void radiolistDialog()
    {
        // setup the alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose a Option");
// add a radio button list
        final String[] selectedoption = {"Option1", "Option2", "Option3", "Option4", "Option5"};
        int checkedItem = 1; // cow
        builder.setSingleChoiceItems(selectedoption, checkedItem, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // user checked an item
                Toast.makeText(MainActivity.this,"selected option: "+selectedoption[which],Toast.LENGTH_LONG).show();
                //here 'which' is the position selected
            }
        });
// add OK and Cancel buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // user clicked OK
            }
        });
        builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

In Radiobutton list we can implement 2 kinds of buttons in alert dialog box i.e setPositiveButton() and setNegativeButton() with different actions.

Checkbox list choice Android alert Dialog list.

setMultiChoiceItems alert dialog list
setMultiChoiceItems alert dialog list

Here in Checkbox list alert dialog list user can select multiple option from the given options.

The way to make a checkbox list is to use setMultiChoiceItems.

public void checkboxlistDialog()
    {
        // setup the alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose some Options ");
        // add a checkbox list
        String[] selectedoption = {"Option1", "Option2", "Option3", "Option4", "Option5"};
        final boolean[] checkedItems = {true, false, false, false, false};
        builder.setMultiChoiceItems(selectedoption, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                // user checked or unchecked a box


            }
        });
// add OK and Cancel buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // user clicked OK
            }
        });
        builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

Complete Source Code android Alert Dialog with list of options

activitymain.xml for UI Design

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Alert Dialog box with List "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.07" />

    <Button
        android:id="@+id/listdialog1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:text="Simple list"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/radiolist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:text="Radio button list"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/listdialog1" />

    <Button
        android:id="@+id/checkboxlist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="Checkbox list"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radiolist" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package protocoderspoint.com.customalertdialog;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button simplelist,radiolist,checkboxlist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simplelist=(Button)findViewById(R.id.listdialog1);
        radiolist=(Button)findViewById(R.id.radiolist);
        checkboxlist=(Button)findViewById(R.id.checkboxlist);
     simplelist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                simplelistDialog();
            }
        });

     radiolist.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             radiolistDialog();
         }
     });

     checkboxlist.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             checkboxlistDialog();
         }
     });
    }

    public void simplelistDialog()
    {
        // setup the alert builder

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose an Option");

        // add a list

        String[] options = {"Option1", "Option2", "Option3", "Option4", "Option3"};

        //Pass the array list in Alert dialog
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0: // Select option task
                    case 1: // Config it as you need here
                    case 2:
                    case 3:
                    case 4:
                }
            }
        });
// create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public  void radiolistDialog()
    {
        // setup the alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose a Option");
// add a radio button list
        final String[] selectedoption = {"Option1", "Option2", "Option3", "Option4", "Option5"};
        int checkedItem = 1; // cow
        builder.setSingleChoiceItems(selectedoption, checkedItem, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // user checked an item
                Toast.makeText(MainActivity.this,"selected option: "+selectedoption[which],Toast.LENGTH_LONG).show();
                //here 'which' is the position selected
            }
        });
// add OK and Cancel buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // user clicked OK
            }
        });
        builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

   public void checkboxlistDialog()
    {
        // setup the alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose some Options ");
        // add a checkbox list
        String[] selectedoption = {"Option1", "Option2", "Option3", "Option4", "Option5"};
        final boolean[] checkedItems = {true, false, false, false, false};
        builder.setMultiChoiceItems(selectedoption, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                // user checked or unchecked a box


            }
        });
// add OK and Cancel buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // user clicked OK
            }
        });
        builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

Recommended Android post

Android custom alert dialog