Dialog and Alert Dialog in android?

Friends we know that dialog is most important role play on all software development now we are going to learn about the dialog in android development,this tutorial will help to you for creating dialog box in android,please read all my point for learning about Dialogs.

1.What is Dialog in android?

 Dialog is used to display the message with OK and Cancel buttons. It can be used to interrupt and ask the user about his/her choice to continue or discontinue.

2.Type of  Dialog in android?

There are four  type dialog in android.

  1. 1.Dialog
  2. 2.Alert Dialog
  3. 3.Toast

3.Simple Dialog

A simple dialog is small window for prompts the user to a decision or enter additional information.if you want to create simple dialog please fread out blow code

Example :- You can use this code any button click and as your requirement?

   // Create custom dialog object
     final Dialog dialog = new Dialog(CustomDialog.this);

  // Include dialog.xml file
     dialog.setContentView(R.layout.dialog);

  // Set dialog title
     dialog.setTitle("Custom Dialog");
 
   // set values for custom dialog components - text, image and button
      TextView text = (TextView) dialog.findViewById(R.id.textDialog);
                text.setText("Custom dialog Android example.");

     ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
 image.setImageResource(R.drawable.yourimage);

  //show popup window by calling show meth0d
     dialog.show();
                 
     Button declineButton = (Button)    dialog.findViewById(R.id.declineButton);
   // if decline button is clicked, close the custom dialog
        declineButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Close dialog
                        dialog.dismiss();
                    }
                });
Here we are creating xml file which we want show for popup window.

dialog.xml    File

  

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
  
    <ImageView
        android:id="@+id/imageDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dp" />

    <TextView
        android:id="@+id/textDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:layout_toRightOf="@+id/imageDialog"/>
  
     <Button
        android:id="@+id/declineButton"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:text=" Submit "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/textDialog"
        android:layout_toRightOf="@+id/imageDialog"
        />
      
</RelativeLayout>    

4.Alert Dialog

Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can be used to interrupt and ask the user about his/her choice to continue or discontinue.
Android AlertDialog is composed of three regions: title, content area and action buttons.

Note -  The Android AlertDialog in android  is the subclass of Dialog class.

If you want to create Alert Dialog you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
The Complete Example of Alert Dialog see in below-

4.1 Create Alert dialog 

 AlertDialog.Builder builder = new AlertDialog.Builder(this);  
 //Uncomment the below code to Set the message and title from the strings.xml file  
builder.setMessage(R.string.dialog_message)                              builder.setTitle(R.string.dialog_title);  
          
//Setting message manually and performing action on button click  
 builder.setMessage("Do you want to close this application ?")  
            .setCancelable(false)  
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {  
                public void onClick(DialogInterface dialog, int id) {  
                finish();  
                }  
            })  
            .setNegativeButton("No", new DialogInterface.OnClickListener() {  
                public void onClick(DialogInterface dialog, int id) {  
                //  Action for 'NO' Button  
                dialog.cancel();  
             }  
            });  
  
        //Creating dialog box  
        AlertDialog alert = builder.create();  
        //Setting the title manually  
        alert.setTitle("AlertDialogExample");  
        alert.show();  
        
    }  
               

5. Toast 

Toast display a massage for the short period of time. A Toast contains message to be displayed quickly and disappears after sometime.
You can also create custom toast as well for example toast displaying image. You can visit next page to see the code for custom toast.

//display in short period of time
Toast.makeText(getApplicationContext(), "your  msg", Toast.LENGTH_SHORT).show();

//display in long period of time
Toast.makeText(getApplicationContext(), "your msg", Toast.LENGTH_LONG).show();


Note  -if you have any issue regarding this post please comment me on comments box?

Thanks?

Android Get all Song from SDCard

Hello friends today i am shearing  a new  post for get all song from sdcard with the help of Cursor and if you have any query so please comments me for this post


Now this is best example of get all song from sdcards

Note :- add uses permission on your manifest.xml file  
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Create XML file
<RelativeLayout 
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"                                                               android:layout_width="match_parent"
      android:layout_height="match_parent"                                                                             android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      android:paddingBottom="@dimen/activity_vertical_margin"                                           tools:context=".MainActivity">
<ListView
         android:id="@+id/listView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

Create a class for use this all code step by step
package mail.example.com.songlist;
import android.app.Activity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity {
private MediaPlayer palyer;
private String[] songList;
@Override
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
         palyer = new MediaPlayer();
         ListView mListView = (ListView) findViewById(R.id.listView1);
         songList = getAllSong();
         ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1, songList);
       mListView.setAdapter(mAdapter);
       mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long           id) {
              try {
                     playSong(songList[position]);
                     } catch (IllegalArgumentException e) {
                           e.printStackTrace();
                    } catch (IllegalStateException e) {
                           e.printStackTrace();
                   } catch (IOException e) {
                          e.printStackTrace();
                    }
                 }
           });
    }
     private String[] getAllSong() {
          final Cursor mCursor = managedQuery(
           MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
           new String[] { MediaStore.Audio.Media.DISPLAY_NAME }, null, null,
           "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
           int count = mCursor.getCount();
           String[] songs = new String[count];
           int i = 0;
           if (mCursor.moveToFirst()) {
         do {
            songs[i] = mCursor.getString(0);
              i++;
          
            } while (mCursor.moveToNext());
           }
          mCursor.close();
         return songs;
        }

/*play music song after click on list item*/
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
      String extStorageDirectory = Environment.getExternalStorageDirectory()
      .toString();
      path = extStorageDirectory + File.separator + path;
      palyer.reset();
      palyer.setDataSource(path);
      palyer.prepare();
      palyer.start();
 }
   @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;
   }

Android Broadcast Receivers


1. Overview 

Now friends we are going to learn about  Broadcast Receivers
Broadcast Receivers is an android componant which response to broadcast messages from an applications or system itself.Broadcast Receivers will catch specific event from android oprating system, this is happen when wifi on,battery status change,recieved phone calls and cut etc.we can also send Broadcast messages throw intent with the help of "sendBroadcast(intent object)" methos.

there are two way to create Broadcast Receiver

1) static type - registered receiver at AndroidManifest.xml file
2) dynamic type -  registered receiver at dynamically with the help of registered() or unregisterReceiver() methods


2.. How to registered receiver at AndroidManifest.xml file

MyReceiver is a name of Broadcast Receiver

<receiver android:name="MyReceiver">
       <intent-filter>
          <action android:name="com.hello.app"/>
          <category android:name="android.intent.category.DEFAULT"/>
       </intent-filter>
</receiver>

3. Create activity_main.xml layout

In this layout we will take two componant first EditText and second Button.we wiil get some text from EditText and after click on Button send broadcast message

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context=".MainActivity" >
   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="44dp"
      android:layout_marginTop="26dp"
      android:ems="10" >
    <requestFocus />
  </EditText>
  <Button 
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/editText1"
   android:layout_below="@+id/editText1"
   android:layout_marginTop="32dp"
   android:text="Send Signal" />
</RelativeLayout>


4.How to create  Broadcast  sender

send Broadcast message by sendBriadcast method

package com.example.broadcastsenderapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {

EditText et;
Button bt;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
          et = (EditText) findViewById(R.id.editText1);
          bt = (Button) findViewById(R.id.button1);
       bt.setOnClickListener(new OnClickListener()
       {
            @Override
            public void onClick(View v)
            {
                   String data = et.getText().toString();
                   Intent in = new Intent("com.hello.app");
                   in.putExtra("data",data);
                   sendBroadcast(in);
            }
       });
    }
    @Override
       public boolean onCreateOptionsMenu(Menu menu) {
       // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
        return true;
       }
  }

3.Create Broadcast Receiver

here  receive message by intent

package com.example.broadcastsenderapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context arg0, Intent in)
   {
        String data = in.getStringExtra("data");
        Toast.makeText(arg0, data, 2).show();
    }
}


if you have any issue and want to know more about Broadcast receiver please comments on blow comments box.

Thanks..