Count Notification For Menu Item and Launcher Icon

Yes we can display Count Notification in action bar and launcher icon. Before creating Count Notification in launcher icon and action bar menu item we need to know some facts. First one is that the native method for creating Count Notification in android launcher icon is deprecated long time ago. The possible solution is to use phone manufactures or launcher application API’s. It’s very hard work, writing code for each manufactures and launcher applications including their API library files. This results in too bulky code, time lose and increase the size of the application. We can overcome these problems and difficulties by using ShortcutBadger Github . ShortcutBadger is a library that can do count notification in launcher icon irrespective of manufacture or launcher app if they support Count Notification. ShortcutBadger take care of converting our input into supported manufacture or launcher app Count Notification.




First add the dependency

dependencies {
compile 'me.leolin:ShortcutBadger:1.1.8'
}

Now we move on to code part

Just add

ShortcutBadger.applyCount(this, i);

I is the integer value set i=0 to disable the count. You can check more information in github.
Count Notification for menu item in actionbar.

1.Creating the icon

The icon must be a vector asset normal png or jpg won’t work. You can get free vector icons from flaticon .Here icon named ic_home is used, now create another xml file called ic_menu.xml to hold the ic_home file. To handle the count a class named Count is used it extents drawable. Set count using setCounting method set 0 to reset the count.

 

2.icon holder


The xml file called ic_menu holds the changes for icon. One thing is to keep in mind is that the id f all icon holder must be same, otherwise you have to create more counter classes.
Ic_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/ic_home"
        android:gravity="center" />

    <!-- set a place holder Drawable so android:drawable isn't null -->
    <item
        android:id="@+id/ic_badge"
        android:drawable="@drawable/ic_home" />
</layer-list>

 

3.counting


We created icon and icon holder now the counting part. Create a class name count then extent the class Drawable.Now we end up with a class file looks like this.

public class Count extends Drawable {
    @Override
    public void draw(Canvas canvas) {

    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {

    }

    @Override
    public int getOpacity() {
        return PixelFormat.UNKNOWN;
    }
}

Change the getOpticity to this

public int getOpacity() {
    return PixelFormat.UNKNOWN;
}

Create objects.

private Paint paint1, paint2, paint3;
private Rect rect1 = new Rect();
private String count1 = "";
private boolean draw1;

Create a constructor.

public Count(Context context) {
    float mTextSize = context.getResources().getDimension(R.dimen.badge_text_size);
    paint1 = new Paint();
    paint1.setColor(ContextCompat.getColor(context.getApplicationContext(), R.color.colorBadge));
    paint1.setAntiAlias(true);
    paint1.setStyle(Paint.Style.FILL);
    paint2 = new Paint();
    paint2.setColor(ContextCompat.getColor(context.getApplicationContext(), R.color.colorBadge));
    paint2.setAntiAlias(true);
    paint2.setStyle(Paint.Style.FILL);

    paint3 = new Paint();
    paint3.setColor(Color.WHITE);
    paint3.setTypeface(Typeface.DEFAULT);
    paint3.setTextSize(mTextSize);
    paint3.setAntiAlias(true);
    paint3.setTextAlign(Paint.Align.CENTER);
}

Editing draw method.

public void draw(Canvas canvas) {

        if (!draw1) {
            return;
        }
        Rect bounds = getBounds();
        float width = bounds.right - bounds.left;
        float height = bounds.bottom - bounds.top;

        // Position the badge in the top-right quadrant of the icon.

           /*Using Math.max rather than Math.min */

        float radius = ((Math.max(width, height) / 2)) / 2;
        float centerX = (width - radius - 1) +5;
        float centerY = radius -5;
        if(count1.length() <= 2){
            // Draw badge circle.
            canvas.drawCircle(centerX, centerY, (int)(radius+7.5), paint2);
            canvas.drawCircle(centerX, centerY, (int)(radius+5.5), paint1);
        }
        else{
            canvas.drawCircle(centerX, centerY, (int)(radius+8.5), paint2);
            canvas.drawCircle(centerX, centerY, (int)(radius+6.5), paint1);
//            canvas.drawRoundRect(radius, radius, radius, radius, 10, 10, paint1);
        }
        // Draw badge count text inside the circle.
        paint3.getTextBounds(count1, 0, count1.length(), rect1);
        float textHeight = rect1.bottom - rect1.top;
        float textY = centerY + (textHeight / 2f);
        if(count1.length() > 2)
            canvas.drawText("99+", centerX, textY, paint3);
        else
            canvas.drawText(count1, centerX, textY, paint3);
    }

Create another method setCount.

public void setCount(String count) {
    count1 = count;

    // Only draw a badge if there are notifications.
    draw1 = !count.equalsIgnoreCase("0");
    invalidateSelf();
}




setCounting method.

public static void setCounting(Context context, LayerDrawable icon, String count) {

    Count badge;

    // Reuse drawable if possible
    Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
    if (reuse != null && reuse instanceof Count) {
        badge = (Count) reuse;
    } else {
        badge = new Count(context);
    }

    badge.setCount(count);
    icon.mutate();
    icon.setDrawableByLayerId(R.id.ic_badge, badge);
}

The full code.

Count.java

public class Count extends Drawable {
    private Paint paint1, paint2, paint3;
    private Rect rect1 = new Rect();
    private String count1 = "";
    private boolean draw1;

    public Count(Context context) {
        float mTextSize = context.getResources().getDimension(R.dimen.badge_text_size);
        paint1 = new Paint();
        paint1.setColor(ContextCompat.getColor(context.getApplicationContext(), R.color.colorBadge));
        paint1.setAntiAlias(true);
        paint1.setStyle(Paint.Style.FILL);
        paint2 = new Paint();
        paint2.setColor(ContextCompat.getColor(context.getApplicationContext(), R.color.colorBadge));
        paint2.setAntiAlias(true);
        paint2.setStyle(Paint.Style.FILL);

        paint3 = new Paint();
        paint3.setColor(Color.WHITE);
        paint3.setTypeface(Typeface.DEFAULT);
        paint3.setTextSize(mTextSize);
        paint3.setAntiAlias(true);
        paint3.setTextAlign(Paint.Align.CENTER);
    }

    @Override
    public void draw(Canvas canvas) {

        if (!draw1) {
            return;
        }
        Rect bounds = getBounds();
        float width = bounds.right - bounds.left;
        float height = bounds.bottom - bounds.top;

        // Position the badge in the top-right quadrant of the icon.

	        /*Using Math.max rather than Math.min */

        float radius = ((Math.max(width, height) / 2)) / 2;
        float centerX = (width - radius - 1) +5;
        float centerY = radius -5;
        if(count1.length() <= 2){
            // Draw badge circle.
            canvas.drawCircle(centerX, centerY, (int)(radius+7.5), paint2);
            canvas.drawCircle(centerX, centerY, (int)(radius+5.5), paint1);
        }
        else{
            canvas.drawCircle(centerX, centerY, (int)(radius+8.5), paint2);
            canvas.drawCircle(centerX, centerY, (int)(radius+6.5), paint1);
//	        	canvas.drawRoundRect(radius, radius, radius, radius, 10, 10, paint1);
        }
        // Draw badge count text inside the circle.
        paint3.getTextBounds(count1, 0, count1.length(), rect1);
        float textHeight = rect1.bottom - rect1.top;
        float textY = centerY + (textHeight / 2f);
        if(count1.length() > 2)
            canvas.drawText("99+", centerX, textY, paint3);
        else
            canvas.drawText(count1, centerX, textY, paint3);
    }

    /*
    Sets the count (i.e notifications) to display.
     */
    public void setCount(String count) {
        count1 = count;

        // Only draw a badge if there are notifications.
        draw1 = !count.equalsIgnoreCase("0");
        invalidateSelf();
    }

    @Override
    public void setAlpha(int alpha) {
        // do nothing
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        // do nothing
    }

    @Override
    public int getOpacity() {
        return PixelFormat.UNKNOWN;
    }


    public static void setCounting(Context context, LayerDrawable icon, String count) {

        Count badge;

        // Reuse drawable if possible
        Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
        if (reuse != null && reuse instanceof Count) {
            badge = (Count) reuse;
        } else {
            badge = new Count(context);
        }

        badge.setCount(count);
        icon.mutate();
        icon.setDrawableByLayerId(R.id.ic_badge, badge);
    }

}

 

4.Creating the menu item

Modify the menu file located in menu folder in your project.Add this to the menu.

<item
        android:id="@+id/menu1A"
        android:icon="@drawable/ic_menu"
        android:title="Notification"
        app:showAsAction="always" />

All the other items are below this.

5. Main class

A menu item object is created.Some screen shots.

 

 

 

 

 

 

 

 

public MenuItem menu1A;

Now the first part is the

 

Count Notification.java
import me.leolin.shortcutbadger.ShortcutBadger;
import static logicchip.iconchange.Count.setCounting;

public class CountNotification extends AppCompatActivity implements View.OnClickListener{
    public AppCompatButton icon99,icon0,menu99,menu0;
    public MenuItem menu1A;
    String a="0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icon);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        icon99=(AppCompatButton)findViewById(R.id.icon99);
        icon0=(AppCompatButton)findViewById(R.id.icon0);
        menu99=(AppCompatButton)findViewById(R.id.menu99);
        menu0=(AppCompatButton)findViewById(R.id.menu0);


        icon99.setOnClickListener(this);
        icon0.setOnClickListener(this);
        menu99.setOnClickListener(this);
        menu0.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_icon, menu);
        menu1A = menu.findItem(R.id.menu1A);
        LayerDrawable icon = (LayerDrawable) menu1A.getIcon();
        setCounting(this, icon, a);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.icon0:
                ShortcutBadger.applyCount(this, 0);break;
            case R.id.icon99:
                ShortcutBadger.applyCount(this,99);break;
            case R.id.menu0:
                LayerDrawable icon = (LayerDrawable) menu1A.getIcon();
                a="0";
                setCounting(this, icon, a);
                invalidateOptionsMenu();//for refreshing menu
                // break;
            case R.id.menu99:
                LayerDrawable icon2 = (LayerDrawable) menu1A.getIcon();
                a="99";
                setCounting(this, icon2, a);
                invalidateOptionsMenu();//for refreshing menu
                break;
        }
    }
}

Now for the Ui part of Count Notification.

activity_icon.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/content_icon"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="logicchip.iconchange.CountNotification">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="set icon count"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
                <android.support.v7.widget.AppCompatButton
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/icon99"
                    android:text="99"
                    android:layout_weight="1"/>

                <android.support.v7.widget.AppCompatButton
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="0"
                    android:id="@+id/icon0"
                    android:layout_weight="1"/>
        </LinearLayout>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="set menu count"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <android.support.v7.widget.AppCompatButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="99"
                android:id="@+id/menu99"
                android:layout_weight="1"/>

            <android.support.v7.widget.AppCompatButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="0"
                android:id="@+id/menu0"
                android:layout_weight="1"/>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

Setup Wizard Like Language Selector

Setup Wizard is shown when the phone is first starting up or rested. It will be nice to create a setup wizard like language selector. This tutorial is all about creating setup wizard like language selector. So the app contain a xml file for ui class file to handle the ui and finally a floating action button. First create the ui with a fab (floating action button). We are using slightly modified “NumberPicker” to get the desired look for the ui. Two methods are also created. One for changing the divider color which separating the selected value and the other for changing text color of displayed names.





1. activity_set_up_wizard.xml

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    android:id="@+id/cStart"
    android:background="@color/colorPrimary"
    tools:context="logicchip.setupwizard.SetUpWizard">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:visibility="gone"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_set_up_wizard" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical">
            <TextView
                android:layout_marginTop="50dp"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/colorText"
                android:textSize="@dimen/text20"
                android:text="@string/select_language"/>
            <NumberPicker

                android:layout_marginTop="20dp"
                android:layout_marginBottom="20dp"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/picker">
            </NumberPicker>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:focusable="true"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:tint="@color/colorPrimaryText"
                app:srcCompat="@drawable/ic_action_name" />
        </LinearLayout>
    </ScrollView>

</android.support.design.widget.CoordinatorLayout>





2.SetUp Wizard.java

 

Here setDividerColor method is used to change divider color and setNumberPickerTextColor method is for changing text color. Both methods are for getting the desired shape and color of the Setup Wizard.

public class SetUpWizard extends AppCompatActivity {
    public NumberPicker picker;
    public FloatingActionButton fab;
    String TAG="SetUpWizard";
    public CoordinatorLayout cStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_up_wizard);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        cStart=(CoordinatorLayout)findViewById(R.id.cStart);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        picker=(NumberPicker)findViewById(R.id.picker);
        String[] social = {"English (United Kingdom)", "English (United States)","German","Chinese"};
        picker.setMinValue(0);
        picker.setMaxValue(2);

        picker.setValue(1);//display initial selected value

        picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        picker.setDisplayedValues(social);
        setNumberPickerTextColor(picker, Color.WHITE);
        setDividerColor(picker,Color.WHITE);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (picker.getValue()){
                    case 0:
                        Log.d(TAG, "onClick: 0 ");
                        Snack("English (United Kingdom)");break;
                    case 1:
                        Log.d(TAG, "onClick: 1 ");
                        Snack("English (United States)");break;
                    case 2:
                        Log.d(TAG, "onClick: 2 ");
                        Snack("German");break;
                    case 3:
                        Log.d(TAG, "onClick: 3 ");
                        Snack("Chinese");break;
                }

            }
        });
    }
    public void Snack(String message){
        Snackbar.make(cStart, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
    }

    //setting number picker text color
    private  boolean setNumberPickerTextColor(NumberPicker numberPicker, int color)
    {
        final int count = numberPicker.getChildCount();
        for(int i = 0; i < count; i++){
            View child = numberPicker.getChildAt(i);
            if(child instanceof EditText){
                try{
                    Field selectorWheelPaintField = numberPicker.getClass().getDeclaredField("mSelectorWheelPaint");
                    selectorWheelPaintField.setAccessible(true);
                    ((Paint)selectorWheelPaintField.get(numberPicker)).setColor(color);
                    ((EditText)child).setTextColor(color);
                    numberPicker.invalidate();
                    return true;
                }
                catch(NoSuchFieldException e){

                }
                catch(IllegalAccessException e){
                }
                catch(IllegalArgumentException e){
                }
            }
        }
        return false;
    }


    //setting divider color
    private void setDividerColor(NumberPicker picker, int color) {

        java.lang.reflect.Field[] pickerFields = NumberPicker.class.getDeclaredFields();
        for (java.lang.reflect.Field pf : pickerFields) {
            if (pf.getName().equals("mSelectionDivider")) {
                pf.setAccessible(true);
                try {
                    ColorDrawable colorDrawable = new ColorDrawable(color);
                    pf.set(picker, colorDrawable);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}

Developing a Music Streaming Android App

For creating a audio streaming in android you must be aware of some things. Mainly database,web service,json array,php things like that. This project can be tricky. However Wamp is used as the server for php and database. Advantage of using php is it’s very easy to setup and test. Android support streaming defaultly. Only need to set type AudioManager.STREAM_MUSIC in MediaPlayer object.


MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

Here a tablayout is used for category selection. Here we use 6 tabs Blues, Electronics, Folk, Hip Hop, Jazz, Pop and Rock. For database connection we use web services the server side code is in php. Only one fragment is used for all the 6 tabs, changing content according to the tab. Inorder to use web services we need a network library called volley, Add this dependencies in the build.gradle(Module:app) file


dependencies {
compile 'com.android.volley:volley:1.0.0'
}




Also add internet permission in Androidmanifest.xml.

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

 

1. Creating Database

Download wamp or xamp server and install it. Create a database called song in it a table called audio.

Now create a folder called song in the www directory of wamp or xamp whatever you are installed. Another folder called songs inside song to store your music files in there. Example a.mp3, b.mp4 etc. Add those names to the database also.

If wamp or xamp don’t run properly check Internet Information Service(IIS) Manager in windows. Also check privileges.

 

2. Php files for web service

Need two php files like.php and song.php. The song.php file is for finding and viewing songs. The like.php file is for rating the audio file.

song.php

<?php
$host="localhost"; // Host name
$servername = "localhost";
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="song"; // Database name

$conn = new mysqli($servername, $username, $password,$db_name);
$tname=$_POST['tag'];

// Check connection
if ($conn->connect_error) {
    	die("Connection failed: " . $conn->connect_error);
} else{
//echo "Connected successfully "."<br />\r\n";
}
	$jsonData      = array();
	$jsonTempData  = array();
$sql = "SELECT * FROM `audio` WHERE TYPE='$tname'";//" ORDER BY index DESC";
	$result = $conn->query($sql);

if ($result->num_rows > 0) {
while(($rowb = $result->fetch_assoc())) {
			$jTempData  = array();
      		$jTempData['id']         	=$rowb["NO"];
			$jTempData['name']         	=$rowb["NAME"];
      		$jTempData['score']         =$rowb["SCORE"];
      		$jTempData['rate']         	=$rowb["RATING"];
			$jsonData[]=$jTempData;
	}
	}else {
			$jTempData  = array();
    			$jTempData['id']         	="no";
			$jTempData['song']         	="noooo";
      		$jTempData['song']         	="noo";
      		$jTempData['song']         	="no";
			$jsonData[]=$jTempData;
}
$conn->close();

$outputArr['song'] = $jsonData;
// Encode Array To JSON Data
print_r( json_encode($outputArr));
?>

For song.php we must provide a tag. Tag for the category of songs to be selected and displayed.




like.php

<?php
$servername = "localhost";// Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="song"; // Database name

$conn = new mysqli($servername, $username, $password,$db_name);
$id=$_POST['id'];
$val=$_POST['like'];

// Check connection
if ($conn->connect_error) {
    		die("Connection failed: " . $conn->connect_error);
} else{
//echo "Connected successfully "."<br />\r\n";
}
	$jsonData      = array();
	$jsonTempData  = array();
  	$sql = "UPDATE audio SET SCORE=SCORE+'$val' WHERE NO='$id'";
	$result = $conn->query($sql);
  	$jTempData['song']         	=$result;
  	$jsonData[]=$jTempData;
  	$conn->close();

  	$outputArr['song'] =$jsonData;
  // Encode Array To JSON Data
  	print_r( json_encode($outputArr));
  ?>

For like.php we must provide id and value of rating. Updated rating can be positive or negative.

 

3. Android part

Class files for android part are MainActivity.java, Constants.java and Common.java. MainActivity holds the fragments and tabs. Also it’s where the streaming take place. Constants.java for holding the constants. Common.java for fragment class and a page adapter class for the tabs.

Comn.java

Class file comn.java contains clicks for streaming audio. Load streaming audio list and display  it.

public class Comn extends Fragment {
    int sect;
    public ListView listView;
    public static ArrayList<String> id = null, song = null, score = null, rate = null;
    public SongAdapter songAdapter;
    public RequestQueue requestQueue;

    public Comn() {

    }

    public Comn newInstance(int sectionNumber, MediaPlayer mediaPlayer) {

        Comn fragment = new Comn();
        Bundle args = new Bundle();
        args.putInt(Constants.KEY_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        requestQueue = ((MainActivity) getActivity()).getRequestQueue();
        requestQueue.getCache().clear();
        View rootView = inflater.inflate(R.layout.fragment_comn, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.t1);
        listView = (ListView) rootView.findViewById(R.id.listview_song);
        listOfSong();
        //((MainActivity)getActivity()).Snack("Json pling");
        textView.setText(getString(R.string.section_format, getArguments().getInt(Constants.KEY_NUMBER)));
        return rootView;
    }


    public void listOfSong() {

        StringRequest menuRequest = new StringRequest(Request.Method.POST, Constants.LINK,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonResponse = new JSONObject(response).getJSONArray(Constants.KEY);
                            int i = jsonResponse.length();

                            id = new ArrayList<String>();
                            song = new ArrayList<String>();
                            score = new ArrayList<String>();
                            rate = new ArrayList<String>();

                            for (int j = 0; j < i; j++) {
                                JSONObject jsonChildNode = jsonResponse.getJSONObject(j);

                                id.add(jsonChildNode.optString(Constants.TAG_ID).toString());
                                song.add(jsonChildNode.optString(Constants.TAG_NAME).toString());
                                score.add(jsonChildNode.optString(Constants.TAG_SCORE).toString());
                                rate.add(jsonChildNode.optString(Constants.TAG_RATE).toString());

                            }
                            songAdapter = new SongAdapter(getActivity(), id, song, score, rate);
                            listView.setAdapter(songAdapter);


                        } catch (JSONException e) {
                            e.printStackTrace();
                            ((MainActivity) getActivity()).Snack("Json " + e.getMessage());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        ((MainActivity) getActivity()).Snack("Volley " + error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                // the POST parameters:
                params.put(Constants.C_TAG, getResources().obtainTypedArray(R.array.type).getText(getArguments().getInt(Constants.KEY_NUMBER)).toString());
                return params;
            }
        };
        //requestQueue.getCache().clear();
        requestQueue.add(menuRequest);
    }


    public class SongAdapter extends BaseAdapter {
        Activity activity;
        ArrayList<String> id, name, score, rate;


        public SongAdapter(Activity activity, ArrayList<String> id, ArrayList<String> name, ArrayList<String> score, ArrayList<String> rate) {
            this.activity = activity;
            this.id = id;
            this.name = name;
            this.score = score;
            this.rate = rate;
        }

        public class ViewHolder {
            public TextView song_name, song_rating;
            public ImageView rate_l, rate_d, rate_p;
        }


        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.song_layout, null);
                holder = new ViewHolder();
                holder.song_name = (TextView) convertView.findViewById(R.id.song_name);
                holder.song_rating = (TextView) convertView.findViewById(R.id.song_rating);
                holder.rate_l = (ImageView) convertView.findViewById(R.id.rate_l);
                holder.rate_d = (ImageView) convertView.findViewById(R.id.rate_d);
                holder.rate_p = (ImageView) convertView.findViewById(R.id.rate_p);

                holder.song_name.setText(name.get(position));
                holder.song_rating.setText(score.get(position));

                holder.rate_p.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((MainActivity) activity).playSong(name.get(position));
                    }
                });
                holder.rate_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((MainActivity) activity).like(id.get(position), "1");
                        listOfSong();
                    }
                });

                holder.rate_d.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        ((MainActivity) activity).like(id.get(position), "-1");
                        listOfSong();
                    }
                });

                convertView.setTag(holder);
            } else {

                holder = (ViewHolder) convertView.getTag();
                holder.song_name.setText(name.get(position));
                holder.song_rating.setText(score.get(position));

            }

            return convertView;
        }
    }
}

Adapter for viewing songs is inside the comn.java class, It uses an xml file for Ui.

song_layout.xml

<?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:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text.mp3"
        android:id="@+id/song_name" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="right">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:layout_gravity="center_vertical"
            android:text="123456"
            android:id="@+id/song_rating" />
        <View
            android:layout_width="24dp"
            android:layout_height="24dp"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_play"
            android:tint="@color/black"
            android:id="@+id/rate_p"
            android:layout_gravity="center_vertical"/>
        <View
            android:layout_width="24dp"
            android:layout_height="24dp"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_like"
            android:tint="@color/green_500"
            android:id="@+id/rate_l"
            android:layout_gravity="center_vertical"/>
        <View
            android:layout_width="24dp"
            android:layout_height="24dp"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_dislike"
            android:tint="@color/red_500"
            android:id="@+id/rate_d"
            android:layout_gravity="center_vertical"/>
    </LinearLayout>


</LinearLayout>

fragment_comn.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="logicchip.cheriyidam.songstream.Comn">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/t1"
        android:visibility="gone"
        android:text="common" />
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listview_song">

    </ListView>

</FrameLayout>

MainActivity.java which contains methods for streaming

public class MainActivity extends AppCompatActivity {


    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    public MediaPlayer mediaPlayer;
    public String songString="";
    public boolean intialStage = true,playPause;
    public CoordinatorLayout coordinatorLayout;
    TextView sng_name,sng_dur;
    public int dur;
    public RequestQueue requestQueue;
    public ImageView img;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        requestQueue= Volley.newRequestQueue(MainActivity.this);
        requestQueue.getCache().clear();
        mViewPager = (ViewPager) findViewById(R.id.container);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        coordinatorLayout=(CoordinatorLayout)findViewById(R.id.main_content);
        sng_name=(TextView)findViewById(R.id.sng_name);
        sng_dur=(TextView)findViewById(R.id.sng_dur);
        img=(ImageView)findViewById(R.id.icon_img);
        img.setEnabled(false);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        tabLayout.addTab(tabLayout.newTab().setText("Blues"));
        tabLayout.addTab(tabLayout.newTab().setText("Electronic"));
        tabLayout.addTab(tabLayout.newTab().setText("Folk"));
        tabLayout.addTab(tabLayout.newTab().setText("Hip hop"));
        tabLayout.addTab(tabLayout.newTab().setText("Jazz"));
        tabLayout.addTab(tabLayout.newTab().setText("Pop"));
        tabLayout.addTab(tabLayout.newTab().setText("Rock"));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount(),mediaPlayer);
        mViewPager.setAdapter(mSectionsPagerAdapter);
       // tabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer.isPlaying()){
                    playPause=true;
                    mediaPlayer.pause();
                    img.setImageResource(R.drawable.play);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }else if(playPause){
                    mediaPlayer.start();
                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                    playPause=false;
                }
            }
        });
    }
    public RequestQueue getRequestQueue(){
        return requestQueue;
    }

    public void like(final String id, final String like){
        StringRequest menuRequest = new StringRequest(Request.Method.POST, Constants.LIKE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonResponse = new JSONObject(response).getJSONArray(Constants.KEY);
                            int i=jsonResponse.length();


                            for(int j=0;j<i;j++){
                                JSONObject jsonChildNode = jsonResponse.getJSONObject(j);
                                Snack(jsonChildNode.optString(Constants.TAG_SONG).toString());

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Snack("Json "+e.getMessage());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        Snack("Volley "+error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<>();
                // the POST parameters:
                params.put(Constants.TAG_ID,id);
                params.put(Constants.TAG_LIKE,like);
                return params;
            }
        };
        //requestQueue.getCache().clear();
        requestQueue.add(menuRequest);
    }


    public MediaPlayer getMediaPlayer(){
        return mediaPlayer;
    }

    public void list(){
    }

    public void playSong(String song) {
        sng_name.setText(song);
        img.setEnabled(true);
        String songPath=Constants.SONG_LINK+song;

        //    Snack(songPath);
       try {

            if(mediaPlayer.isPlaying()){
                if(songString.equals(songPath)){
                    mediaPlayer.pause();
                    playPause=true;
                    img.setImageResource(R.drawable.play);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }else{
                    playPause=false;
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(songPath);
                    songString=songPath;
                    mediaPlayer.prepare();
                    mediaPlayer.start();

                    //setting duration change it...
                    sng_dur.setText(String.valueOf(mediaPlayer.getDuration()));

                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }
            }else if(playPause){
                if(songString.equals(songPath)){
                    mediaPlayer.start();
                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                    playPause=false;
                }else{
                    playPause=false;
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(songPath);
                    songString=songPath;
                    mediaPlayer.prepare();
                    mediaPlayer.start();

                    //setting duration change it...
                    sng_dur.setText(String.valueOf(mediaPlayer.getDuration()));

                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }

            }else {
                mediaPlayer.reset();
                playPause=false;
                mediaPlayer.setDataSource(songPath);
                songString=songPath;
                mediaPlayer.prepare();
                mediaPlayer.start();
                sng_dur.setText(String.valueOf(mediaPlayer.getDuration()));
                img.setImageResource(R.drawable.pause);
                img.setColorFilter(getResources().getColor(R.color.black));
               // dur=mediaPlayer.getDuration();
                //Snack(String.valueOf(dur));
            }


            // Setup listener so next song starts automatically
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                public void onCompletion(MediaPlayer arg0) {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }

            });

        } catch (IOException e) {
            Log.v(getString(R.string.app_name), e.getMessage());
        }
    }

    public void check(){

    }


    public  void Snack(String message) {
        Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    
  

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="logicchip.cheriyidam.songstream.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:layout_scrollFlags="scroll|enterAlways">

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="30dp" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="end|bottom">
        <ImageView
            android:layout_margin="@dimen/appbar_padding_top"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/icon_img"
            android:layout_gravity="center_vertical"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/green_500"
            android:layout_margin="@dimen/appbar_padding_top"
            android:layout_gravity="center_vertical"
            android:id="@+id/sng_name"/>
        <View
            android:layout_width="60dp"
            android:layout_height="2dp"
            android:layout_gravity="center_vertical"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/red_500"
            android:layout_margin="@dimen/appbar_padding_top"
            android:layout_gravity="center_vertical"
            android:id="@+id/sng_dur"/>
    </LinearLayout>


</android.support.design.widget.CoordinatorLayout>

Constants.java

public class Constants {
    public static final String KEY_NUMBER = "key_number";
    public final static String IP="http://192.168.201.1";
    public final static String LINK="http://192.168.201.2/song/song.php";
    public final static String LIKE="http://192.168.201.2/song/like.php";
    public final static String SONG_LINK="http://192.168.201.2/song/songs/";
    public final static String KEY="song";

    public final static String TAG_ID="id";
    public final static String TAG_LIKE="like";
    public final static String TAG_NAME="name";
    public final static String TAG_SCORE="score";
    public final static String TAG_RATE="rate";
    public final static String TAG_SONG="song";

    public final static String C_TAG="tag";
}

You should replace the ip address with your wamp server running systems ip. Streaming requires ip or link for working. While using a local system ip is our best option. Don’t use “localhost” us ip. Streaming works by loading a link and retrieving it’s content. By using a localhost android try to access it which is not possible, because it’s not have any servers running. Wamp is the server running so we need to use the ip of the system. In case it’s hosted online server. We can use links like “www.yourwebsite.com/songlink.mp3” .

SectionsPagerAdapter.java

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    public MediaPlayer mediaPlayer;
    int mNumOfTabs;

    public SectionsPagerAdapter(FragmentManager fm,int NumOfTabs,MediaPlayer mediaPlayer) {
        super(fm);
        this.mediaPlayer=mediaPlayer;
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {
        Comn comn=new Comn();
        return comn.newInstance(position,mediaPlayer);

    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="red_500">#F44336</color>
    <color name="green_500">#4CAF50</color>
    <color name="white">#FFF</color>
    <color name="black">#000</color>
</resources>

icon_dislike.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
</vector>

icon_like.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
</vector>

icon_none.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M22,9.24l-7.19,-0.62L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21 12,17.27 18.18,21l-1.63,-7.03L22,9.24zM12,15.4l-3.76,2.27 1,-4.28 -3.32,-2.88 4.38,-0.38L12,6.1l1.71,4.04 4.38,0.38 -3.32,2.88 1,4.28L12,15.4z"/>
</vector>

icon_play.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M8,5v14l11,-7z"/>
</vector>

pause.xml

Pause button used for pause streaming audio.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="50dp"
        android:height="50dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M6,19h4L10,5L6,5v14zM14,5v14h4L18,5h-4z"/>
</vector>

 

play.xml

Play button used for start streaming.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="50dp"
        android:height="50dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M8,5v14l11,-7z"/>
</vector>

Alert Dialog Box With Dynamic Content

In this post we are talking about creating dynamic content in alert dialog box.This is not the correct way but it is a way. It’s mostly for beginners in android developing. where we want to use dynamic content for alertdialog box.Like a sub catogery in categorys.managing and utilising space of mobile screen more effectively. First of all let me give you a hind what we are up to.

 

 

 

 

 

 

 

 

 

 

First we need to create the Alertdialog box.Contents for Alert dialog box can be added in many ways. The first way is by code,it means write what we want directly in code like

EditText edittext=new EditText(this)

. For advanced programmers it’s works but it’s bit difficult to do for biginers. The second method is creating a custom xml file for the Alertdialog box. It’s easy to make and understand. We go with the second way.



First step

The first step is to initialise some contents globally,so it can be accessed everywhere from the class.

    public LayoutInflater inflater;
    public RadioButton checkBox0,checkBox1,checkBox2,checkBox2v,checkBox2n,checkBox3,checkBox4,checkBox5,checkBox6,checkBox7;
    public RadioButton radioButton0,radioButton1,radioButton2;
Creating the custom Alert dialog box

Android uses xml file for creating Ui.Our custom ui is created using an xml file.Create an xml file for the ui in the layout folder of android studio.Below is a sample code.
I am using

dialog.xml
<?xml version="1.0" encoding="utf-8"?>\n<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
	android:orientation="vertical"   
        android:layout_width="wrap_content"    
        android:id="@+id/test"    
        android:layout_height="wrap_content">  
<TextView        
        android:layout_marginTop="16dp"
        android:layout_marginLeft="16dp"        
        android:layout_width="wrap_content"     
	android:layout_height="wrap_content"
        android:textSize="20sp"        
        android:text="categories to include"/>          
<LinearLayout
        android:layout_marginLeft="16dp" 
        android:layout_width="wrap_content"             
	android:layout_height="wrap_content"        
        android:orientation="vertical">  
<CheckBox             
	android:layout_width="wrap_content"  
        android:layout_height="wrap_content"   
        android:id="@+id/checkbox_1" 
	android:onClick="onCheckboxClicked"       
        android:text="event management"/>   
<CheckBox                
	android:layout_width="wrap_content"  
        android:layout_height="wrap_content"         
        android:id="@+id/checkbox_2" 
	android:onClick="onCheckboxClicked"    
        android:text="catering"/> 
<CheckBox                       
	android:layout_width="wrap_content"        
        android:layout_height="wrap_content"  
        android:id="@+id/checkbox_2v"
	android:visibility="gone"                       
        android:layout_marginLeft="16dp"                      
        android:onClick="onCheckboxClicked"       
	android:text="vegetarian"/>                   
<CheckBox                       
        android:layout_width="wrap_content"                       
	android:layout_height="wrap_content"  
        android:id="@+id/checkbox_2n"  
        android:visibility="gone"      
	android:layout_marginLeft="16dp"   
        android:onClick="onCheckboxClicked"  
        android:text="non vegetarian"/>
<CheckBox                  
        android:layout_width="wrap_content"                 
        android:layout_height="wrap_content"    
	android:id="@+id/checkbox_3"                  
        android:onClick="onCheckboxClicked"                  
        android:text="videography"/>            
<CheckBox                   
        android:layout_width="wrap_content"                
        android:layout_height="wrap_content"                 
	android:id="@+id/checkbox_4"                 
        android:onClick="onCheckboxClicked"                 
        android:text="photography"/>       
<CheckBox                  
        android:layout_width="wrap_content"                 
        android:layout_height="wrap_content"                 
	android:id="@+id/checkbox_5"                    
        android:onClick="onCheckboxClicked"                 
        android:text="travels"/>           
<CheckBox                  
        android:layout_width="wrap_content"                
        android:layout_height="wrap_content"                  
	android:id="@+id/checkbox_6"               
        android:onClick="onCheckboxClicked"                
        android:text="decaration"/>       
<CheckBox                   
        android:layout_width="wrap_content"                 
        android:layout_height="wrap_content"                 
	android:id="@+id/checkbox_7"                    
        android:onClick="onCheckboxClicked"                
        android:text="lighting and sound"/>
	
</LinearLayout>
</LinearLayout>




Now for the main part

MainActivity.java contain all the codeing part of the Alert dialog box

public class MainActivity extends AppCompatActivity implements View.OnClickListener {   
 CoordinatorLayout coordinatorLayoutMain;  
 
	FloatingActionButton fab;
	View view;   
	LayoutInflater inflater;   
	CheckBox checkBox1,checkBox2,checkBox2v,checkBox2n,checkBox3,checkBox4,
	checkBox5,checkBox6,checkBox7;   
	Button buttonDialog; 
	
	@Override    
	protected void onCreate(Bundle savedInstanceState) {     
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
	setSupportActionBar(toolbar);        
	coordinatorLayoutMain=(CoordinatorLayout)findViewById(R.id.coordinatorLayoutMain);       
	fab = (FloatingActionButton) findViewById(R.id.fab);
	buttonDialog=(Button)findViewById(R.id.buttonDialog);        
	fab.setOnClickListener(this);       
	buttonDialog.setOnClickListener(this);
	//inflater for the dialogbox     
	inflater = this.getLayoutInflater();        
	view=inflater.inflate(R.layout.dialog, null);        
	//check box for alertdialogbox START     
	checkBox1=(CheckBox)view.findViewById(R.id.checkbox_1);
	checkBox2=(CheckBox)view.findViewById(R.id.checkbox_2);      
	checkBox2v=(CheckBox)view.findViewById(R.id.checkbox_2v);
	checkBox2n=(CheckBox)view.findViewById(R.id.checkbox_2n);   
	checkBox3=(CheckBox)view.findViewById(R.id.checkbox_3);
	checkBox4=(CheckBox)view.findViewById(R.id.checkbox_4);	
	checkBox5=(CheckBox)view.findViewById(R.id.checkbox_5);   
    checkBox6=(CheckBox)view.findViewById(R.id.checkbox_6);     
	checkBox7=(CheckBox)view.findViewById(R.id.checkbox_7);      
	//check box for alertdialogbox  END
    }  
	
	
	// for viewng snack bar messages    
	public void SnackMessage(String message){     
	Snackbar.make(coordinatorLayoutMain,message, Snackbar.LENGTH_LONG).setAction("Action", null).show();   
	} 

	
	//handling clicks   
	@Override    
	public void onClick(View view) {        
	switch (view.getId()){       
	case R.id.fab:SnackMessage("fab click");break;
	case R.id.buttonDialog:onCreateDialog();break;        }    }
	
	// method for dialogbox view   
	public void onCreateDialog() {       
	final AlertDialog.Builder builder = new AlertDialog.Builder(this);      
	// Get the layout inflater
	// Inflate and set the layout for the dialog\n    
    // Pass null as the parent view because its going in the dialog layout        
	builder.setView(view)               
	// Add action buttons               
	.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { 
	@Override\n                    
	public void onClick(DialogInterface dialog, int id) {\n   
	// do something here  
	}}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {
	// do something here                    }
	}).setNeutralButton(R.string.report,new DialogInterface.OnClickListener() {
	public void onClick(DialogInterface dialog, int id) {
	// do something here
	}
	});
	builder.create().show();
	}
	
    //handling clicks from inside dialog box
    public void onCheckboxClicked(View view) {
	// Is the view now checked?
	boolean checked = ((CheckBox) view).isChecked();
	// Check which checkbox was clicked
	switch(view.getId()) {
	case R.id.checkbox_1:
	if (checked){                  
	SnackMessage("event management checked");
	} else{
	SnackMessage("event management unchecked");
	}break;
	case R.id.checkbox_2:
	if (checked){
	SnackMessage("catering checked");
	checkBox2v.setVisibility(View.VISIBLE);
	checkBox2n.setVisibility(View.VISIBLE);
	}else{
	SnackMessage("catering unchecked");
	checkBox2v.setVisibility(View.GONE);
	checkBox2n.setVisibility(View.GONE);
	}break;
	case R.id.checkbox_2n:
	if (checked){
	SnackMessage("non-veg checked");
	}else{
	SnackMessage("non-veg unchecked");
	}               
	break;          
	case R.id.checkbox_2v:
	if (checked){
	SnackMessage("veg checked");
	}else{
	SnackMessage("veg unchecked");
	}               break;
	case R.id.checkbox_3:
	if (checked){
	SnackMessage("video checked");
	}else{
	SnackMessage("video unchecked");
	}               
	break;
	case R.id.checkbox_4:
	if (checked){
	SnackMessage("photography checked");
	}else{
	SnackMessage("photography unchecked");
	}
	break;
	case R.id.checkbox_5:
	if (checked){
	SnackMessage("travel checked");
	} else{
	SnackMessage("travel unchecked");
	}
	break;
	case R.id.checkbox_6:
	if (checked){
	SnackMessage("decoration checked");
	} else{
	SnackMessage("decoration unchecked");               
	}               
	break;
	case R.id.checkbox_7:
	if (checked){
	SnackMessage("light and sound checked");
	} else{
	SnackMessage("light and sound unchecked");
	}               break;
	}    }  
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.menu_main, menu);
	return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// Handle action bar item clicks here. The action bar will
	// automatically handle clicks on the Home/Up button, so long
	// as you specify a parent activity in AndroidManifest.xml.
	int id = item.getItemId();
	//noinspection SimplifiableIfStatement
	if (id == R.id.action_settings) {
	return true;
	}        
	return super.onOptionsItemSelected(item);
    }}