Android Useful Tips

Today we are learn some important tips which is use each and every android app.

1. Capitalize Every First letter of a Word in EditText
If any buddy want to capitalize the first letter of every word in a EditText,
assign android:inputType=”textCapWords” to EditText.

The same process by programatically also as shown below.
TextView txtCapitalize = (TextView) findViewById(R.id.txtCapitalize);
txtCapitalize.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);  

2. Hide  the keypad in Android
 public static void hideKeyboard(MainActivity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(MainActivity.INPUT_METHOD_SERVICE);

        View view = activity.getCurrentFocus();

        if (view == null) {
            view = new View(activity);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }



3.How to  start or stot adb from command line
If you start or stop the adb using the command prompt please follow blow processs

1.first open CMD
Note:-Before you execute the commands in CMD make sure that you added the adb tool to your Environment Variables path.

2.Killing adb
 adb kill-server 

3.Starting adb
 adb start-server  

4. Detect back button press in android
Override the onBackPressed() method and take the action inside this function.
@Override
    public void onBackPressed() {
        // Write code here
        super.onBackPressed();
    }





Android Realm Database with Replacing SQLite & Core Data

Realm is the database solution for proposed as  a replacement for SQLite & Core Data.It persists on its own persistence engine.
Realm is  also cross-platform that supports both iOS and Android, so developers who write Java, Swift, Objective-C can share the same Realm files painlessly.

There are some  advantages of Realm over SQLite:
1. Realm is faster than SQLite
2. it is easy to use
3. object conversion can be handled  easy
4. convenient for creating and storing data on the fly

Realm missing the following features:
1. Realm null support
2. auto incrementing
3. Map support
4. easy migrations
5. notifications on specific data changed
6. compound primary keys

Some important guide for Installation:
Realm is installed as a Gradle plugin.
Installing Realm as a Gradle plugin is a two step process.

Step 1: Add the following class path dependency to the project level build.gradle file.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:0.90.1"
    }
}

Step 2: Apply the realm-android plugin to the top of application level build.gradle file.


apply plugin: 'realm-android'





Android Text to Speech

Android has also new  feature (from Android 1.6) called Text to Speech (TTS) which speaks the text in different languages. with the help of this tutorial explains how to work with android text to speech In this tutorial i also explained changing the language type and speed level.
In this tutorial, i want to implement TTS in Android and how we can control some interesting aspects of speech engine.

Text to Speech

Now we will learn text to speech step by step

1. first we have to use the TTS in our app is initialise the engine.

engine = new TextToSpeech(this, this);

2. Implement your main Activity class from TextToSpeech.OnInitListener
This listener is used to inform our app that the engine is ready to be used

public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
@Override
    public void onInit(int status) {
      if (status == TextToSpeech.SUCCESS) {
           Log.d(&Speech&, &Success!&);
           engine.setLanguage(Locale.UK);
        } 
      } 
    }


3.Read the words and speech.
Now our engine is ready to be used, we need simply pass the string we want to read. To this purpose, we use an EditText so that the user can edit his string and when he clicks on the microphone the app start reading. Without detailing too much the code because is trivial we focus our attention when user clicks on the microphone button:

 speechButton.setOnClickListener(new View.OnClickListener() { 
     @Override
     public void onClick(View v) {
        speech();
        }
    });

      private void speech() {
          engine.speak("Your text for speech", TextToSpeech.QUEUE_FLUSH, null, null);
        }

5.Control Text to Speech Engine parameters
We can control on engine to read the sentence. We can modify for example the pitch and the speech rat.

engine.setPitch((float) pitch);
engine.setSpeechRate((float) speed);
engine.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null, null);









Android N Designing for Multi-Window

Android N  primary mode where users can be create multi-window through split-screen mode, Multi-Window is designing for every devices. user can drag the divider between the two split screens to resize the apps.

The Android Studio 2.1 Supports Android N Developer Preview
The release of Android Studio 2.1 is now available and includes updates to the platform’s IDE wizards, build system and Android Emulator. The Android Studio development team says that the latest release provides access to new features and APIs of the developer preview including the new Jack compiler and Java 8 language support. Android Studio 2.1 includes performance improvements to Instant Run which provides faster edit and deploy build speeds.


Designing a responsive UI is still an important first step towards an amazing multi-window experience.

There are some new features  of Android N
1. Multi-window mode
This is a more advanced feature that Building a responsive UI that reacts to the space available is critical to a great multi-window  experience.

2. New Notifications panel
with the help of this feature  we can just reply within the notification that appears at the top of the screen.

3. Quick Settings Menu
Google has released  new quick settings menu to the notifications shade you pull down from the top.
When pulling the notifications bar down a second time to reveal the quick settings menu.

4. 3D Touch support
Google will be released 3D Touch-style interaction to Android N, reports have confirmed.

The second iteration of the Android N developer preview, which rolled out last week, contained support for 'launcher shortcuts'.

The feature was widely expected to mimic the pressure-sensitive contextual functions introduced by the iPhone 6s, allowing users to launch specific app sub-functions by pressing harder on the screen.

N Developer Preview Support

Android Studio 2.1 release with best support for the new Jack compiler and support for Java 8. With the Jack compiler, lambdas, method references, compile-time type annotations, intersection types and type inference are available on all versions of the Android platform. Default and static methods and repeatable annotations are available on Android N and higher. To use Java 8 language features when developing with the N Developer Preview, developers need to use the Jack compiler.

Instant Run
Developers can access fast edits, builds and deploy cycles with A#336667ndroid Studio 2.0 as Instant Run now can now update incremental changes to app code much faster. Instant Run and general build speed are now faster due to two new features - incremental Java compilation and in-process dex.

Android Marshmallow for Developer

Google has also released  the Android version 23 APIs called Android 6.0 Marshmallow.Android Marshmallow was initially announced at Google I/O on May 28.

 It was released as the Android M preview for developer.The Android M developer preview gave developers a clear timeline to test their apps, and an opportunity to explore the new features the latest version of Android has to offer

There are some new features for android Marshmallow.

1. Fingerprint Authentication 
 for using this feature in your app first you need to add the  USE_FINGERPRINT permission in your  app.
2. Lock screen 
 Android Marshmallow add  the dialer shortcut with one to Google’s voice search on lock screen. 
3. Notifications Upgrade 
 This new feature use  NotificationManager.getActiveNotifications() method that allows your apps to  find out which of their notifications are currently alive
4. USB Type-C 
 This feature is silly-fast, can be used any way up – and it’s going to be the most commonly used  connection in the next few years. What’s more, it also allow for much faster charging than  conventional cables: it can fully charge a Nexus 6P in around two hours.
5. System UI Tuner
 Once enabled, System UI Tuner will appear in the settings menu at the very bottom. It provides a  few simple UI tweaks, including adding a battery percentage indicator to your battery icon, a  customizable Quick Settings area.
.App search bar and favourites
 In order to help those who think the new apps menu is worse, and there will be some, there are some  extra features to the apps area. First, there’s a search bar up at the top.


there are some small upgradation  in  Android Marshmallow
1. Bluetooth Stylus Support
2. Bluetooth Low Energy Scanning
3. Video
4. Audio
5.Camera

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;
   }