Wednesday, July 31, 2013

Text to speech converter

Welcome Learners World of android.

Switching to new tutorial which converts text entered to audio stream.
This application will be helpful for English learners and good pronunciation practicing. Also for those dumb and blind people where learning is simple task.

Step 1 : Create xml file

Create a anew android application. In the xml, Create edit text field and a button to convert text entered in edittext to speech.



Step 2: Get the text entered

 In java class, get the entered text in a string.

EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();

 Step 3: Create speech method.

Create a speech method and call it in onClick of button. Pass the string "words" obtained in step 2 to it.

 Step 4: Implement TTS within the class

You also need to implement one more interface, so alter your class declaration outline to add “OnInitListener” as in the following example:

public class SpeakingAndroid extends Activity implements OnClickListener, OnInitListener

 Step 5: Check for TTS data 

 Your app needs to check that the user has the data necessary for the TTS function before you call its methods. Declare and instantiate the following instance variable at the top of your Activity class declaration, before the “onCreate” method

private int MY_DATA_CHECK_CODE = 0;
 
 
Also create an intent to keep checking users data in on create method 
 
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
 
Create an TTS instance 
 
private TextToSpeech myTTS;
 

Implementing onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MY_DATA_CHECK_CODE) {
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            myTTS = new TextToSpeech(this, this);
        }
        else {
            Intent installTTSIntent = new Intent();
            installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installTTSIntent);
        }
        }
}
 

Step 6: Create the onInit method

@Override
    public void onInit(int status) {
        if(status == TextToSpeech.SUCCESS){
             if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
                 myTTS.setLanguage(Locale.US);
        }
        else if(status == TextToSpeech.ERROR)
            Toast.makeText(this, "Error while loading", Toast.LENGTH_SHORT).show();
    }

Step 7: Add speak method to function created in step3

In your method created in step 3, add this line of code :

myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
 

Step 8: Dont forget to release the sources you used.

myTTS.shutdown();

 NOTE : Dont use this code if you want user to make it speak more than once.

 

 
 
 




 




Sunday, July 7, 2013

Login validation

Here user will be provided with username and password fields at the first installation of the application. Later shared preferences will be saved and next time user will have to enter respective password to go to next activity.

This saves your info into shared preferences and later validates it.

Source code for login validation :

public class Login extends Activity implements OnClickListener {
    EditText name,pass,phone;
    Button login;
    SharedPreferences preference;
    SharedPreferences preference1;
    SharedPreferences preference2;
    SharedPreferences preference3;
    SharedPreferences preference4;
    String username;
     String password;
     String phone_no;
     String phonetodb;
     boolean bValidate;
     boolean bValidate_table;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        init();
       
           preference2 =getSharedPreferences("validate", MODE_PRIVATE);
           bValidate =preference2.getBoolean("validate", false);
           if(bValidate==false)
           { 

               // For first installation of app
               Toast.makeText(getApplicationContext(), "Enter details", Toast.LENGTH_LONG).show();
               login.setOnClickListener(this);   
            }
           else
           { 

                 // If you have registered here previously
                // Shared preferences will display username for you 
                   SharedPreferences preference =getSharedPreferences("userid", MODE_PRIVATE);
                   username = preference.getString("userid", " ");
                   Log.d("Username", "Username "+ username);
                   

                //  Shared preferences will display phone no for you
                   SharedPreferences preference3 = getSharedPreferences("phone_no", MODE_PRIVATE);
                   phone_no = preference3.getString("phone_no", "");
                  // get password to match with currently entered one 
                   SharedPreferences preference1 =getSharedPreferences("pass_word", MODE_PRIVATE);
                   password= preference1.getString("pass_word", " ");
                   Log.d("password", "password "+ password);
                   name.setText(username);
                   name.setEnabled(false);
                   phone.setText(phone_no);
                   phone.setEnabled(false);
                   Log.d("checking", "Check in progress");
                         login.setOnClickListener(this);   
         }
    }
   
    private void init() {
        name=(EditText)findViewById(R.id.name);
        login = (Button)findViewById(R.id.login);
        pass=(EditText)findViewById(R.id.password);
        phone = (EditText)findViewById(R.id.phone);
    }
   
    @Override
    public void onClick(View v) 
    {
        switch(v.getId())
        {
        case R.id.login :
            if(bValidate==false)
            { 

               // Creating shared preferences at the first installation for user name
                 SharedPreferences preference =getSharedPreferences("userid", MODE_PRIVATE);
                 SharedPreferences.Editor editor1=preference.edit();
                 editor1.putString("userid", name.getText().toString());
                 editor1.commit();
                 String usertodb =  name.getText().toString();
                 
// Creating shared preferences at the first installation for password
                 SharedPreferences preference1 =getSharedPreferences("pass_word", MODE_PRIVATE);
                 SharedPreferences.Editor editor2=preference1.edit();
                 editor2.putString("pass_word", pass.getText().toString());
                 editor2.commit();
                 
// Creating shared preferences at the first installation for phone no
                 SharedPreferences preference3 = getSharedPreferences("phone_no", MODE_PRIVATE);
                 SharedPreferences.Editor editor4 = preference3.edit();
                 editor4.putString("phone_no", phone.getText().toString());
                 editor4.commit();;
                 phonetodb = phone.getText().toString();
                 
                 SharedPreferences preference2 =getSharedPreferences("validate", MODE_PRIVATE);
                 SharedPreferences.Editor editor3=preference2.edit();
                 editor3.putBoolean("validate", true);
                 editor3.commit();  

                 // Starting asynchronous task to store details at server side
                 new LoginTask(Login.this).execute(usertodb,phonetodb);
                 login();
        }
            else
            { 

              // matching password for authentication
                 String password1=pass.getText().toString();
                    Log.d("pass", "p "+ password1);
                   if(password1.equals(password))
                   {
                       Log.d("Match", "Match " +  (password1.equals(password))); 
                       login();
                   } 
                   else
                   {
                         AlertDialog.Builder alert = new AlertDialog.Builder(Login.this);
                        alert.setMessage("Incorrect password.");
                        alert.setTitle("Error!!!");
                        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                        }
                        });
                        alert.show();
                   }
                }
            break;
        }
    }

        private void login() 
         {       
            preference4 =getSharedPreferences("validate_table", MODE_PRIVATE);
               bValidate_table =preference4.getBoolean("validate_table", false);
               if(bValidate_table==false)
               { 

                    
                           SharedPreferences preference4 =getSharedPreferences("validate_table", MODE_PRIVATE);
                    SharedPreferences.Editor editor5=preference4.edit();
                    editor5.putBoolean("validate_table", true);
                    editor5.commit();  
               }           
        Toast.makeText(getApplicationContext(), "Login Successfull", Toast.LENGTH_LONG).show();
        Intent j = new Intent(Login.this, RespectiveNextClass.class);
        startActivity(j);
        }
    }

Changing brightness, hue and saturation of an image

Here is the code to change brightness, hue and saturation of an image. These are the respective functions. You just need to refer code of seekbar in order to implement this.

1.Brightness
2.Hue
3.Saturation

1. Brightness

public static Bitmap doBrightness(Bitmap src, int value) {
       
// get image size 
        int width = src.getWidth();
        int height = src.getHeight();

        //creating output bitmap
        Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
        int A, R, G, B;
        int pixel;
        //iterations through pixels
        for(int x = 0; x < width; ++x) {
            for(int y = 0; y < height; ++y) {

               
                pixel = src.getPixel(x, y);
                A = Color.alpha(pixel);
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
                // changing R, G, B values to change brightness as per value on seekbar
                R += value;
                if(R > 255) { R = 255; }
                else if(R < 0) { R = 0; }

                G += value;
                if(G > 255) { G = 255; }
                else if(G < 0) { G = 0; }

                B += value;
                if(B > 255) { B = 255; }
                else if(B < 0) { B = 0; }
                //output bitmap
                bmOut.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }
        return bmOut;
    }


2. Hue

      public static Bitmap applyHueFilter(Bitmap source, int level) {
        // get image size
        int width = source.getWidth();
        int height = source.getHeight();
        int[] pixels = new int[width * height];
        float[] HSV = new float[3];
        // get pixel array from source
        source.getPixels(pixels, 0, width, 0, 0, width, height);
       
        int index = 0;
        // iteration through pixels
        for(int y = 0; y < height; ++y) {
            for(int x = 0; x < width; ++x) {
                // get current index in 2D-matrix
                index = y * width + x;               
                // convert to HSV
                Color.colorToHSV(pixels[index], HSV);
                // increase Saturation level
                HSV[0] *= level;
                HSV[0] = (float) Math.max(0.0, Math.min(HSV[0], 360.0));
                // take color back
                pixels[index] |= Color.HSVToColor(HSV);
            }
        }
        // output bitmap               
        Bitmap bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bmOut.setPixels(pixels, 0, width, 0, 0, width, height);
        return bmOut;       
    }


3. Saturation

public static Bitmap applySaturationFilter(Bitmap source, int level) {
        // get image size
        int width = source.getWidth();
        int height = source.getHeight();
        int[] pixels = new int[width * height];
        float[] HSV = new float[3];
        // get pixel array from source
        source.getPixels(pixels, 0, width, 0, 0, width, height);

        int index = 0;
        // iteration through pixels
        for(int y = 0; y < height; ++y) {
            for(int x = 0; x < width; ++x) {
                // get current index in 2D-matrix
                index = y * width + x;
                // convert to HSV
                Color.colorToHSV(pixels[index], HSV);
                // increase Saturation level
                HSV[1] *= level;
                HSV[1] = (float) Math.max(0.0, Math.min(HSV[1], 1.0));
                // take color back
                pixels[index] |= Color.HSVToColor(HSV);
            }
        }
        // output bitmap
        Bitmap bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bmOut.setPixels(pixels, 0, width, 0, 0, width, height);
        return bmOut;
    }

Wednesday, July 3, 2013

Photoshop operations on image

Various photoshop apps are available in android. Various operations like rotating, flipping, mirror image, water image, converting to grayscale are available. Also advanced features like snow effect are also possible.

  1. Rotate
  2. Flip (Mirror image)
  3. Gray Scale
  4. Snow Effect
1. Rotate Right
        
          //Get image set to imageview
          Imageview.buildDrawingCache();
            bitmap = Imageview.getDrawingCache();
            Matrix matrixr = new Matrix();

            //Rotate matrix
            matrixr.postRotate(270);
            bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrixr, true);


 Rotate Left

          //Get image set to imageview
          Imageview.buildDrawingCache();
            bitmap = Imageview.getDrawingCache();
            Matrix matrixr = new Matrix();

            //Rotate matrix
            matrixr.postRotate(90);
            bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrixr, true);


2. Flip Horizontal

          //Get image set to imageview
          Imageview.buildDrawingCache();
            bitmap = Imageview.getDrawingCache();
            Matrix matrixr = new Matrix();

            //Scale matr
            matrixr.preScale(-1.0f, 1.0f );
            bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrixr, true);
  

3. Gray Scale

        public static Bitmap convertToGray(Bitmap src)
        {
       //setting red, green, blue factors to convert image to grayscale
        final double GS_RED = 0.299;
        final double GS_GREEN = 0.587;
        final double GS_BLUE = 0.114;
       //create output bitmap
        Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
        int A,R,G,B;
        int pixel;
      
        int width = src.getWidth();
        int height  =src.getHeight();
       //pixels iteration
        for(int x=0;x<width;++x)
        {
            for(int y=0;y<height;++y)
            {
                pixel = src.getPixel(x, y);
                A = Color.alpha(pixel);
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
               // Generating pixels for gray scale image
                R = G = B = (int) (G*GS_GREEN + R*GS_RED + B*GS_BLUE);
                bmOut.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }
        return bmOut;
    }
 


4.Snow Effect

public static Bitmap applySnowEffect(Bitmap source) {
        // get image size
        int width = source.getWidth();
        int height = source.getHeight();
        int[] pixels = new int[width * height];
        // get pixel array from source
        source.getPixels(pixels, 0, width, 0, 0, width, height);
        // random object
        Random random = new Random();
      
        int R, G, B, index = 0, thresHold = 50;
        // iteration through pixels
        for(int y = 0; y < height; ++y) {
            for(int x = 0; x < width; ++x) {
                // get current index in 2D-matrix
                index = y * width + x;              
                // get color
                R = Color.red(pixels[index]);
                G = Color.green(pixels[index]);
                B = Color.blue(pixels[index]);
              
                // generate threshold
                thresHold = random.nextInt(COLOR_MAX);
                if(R > thresHold && G > thresHold && B > thresHold) {
                    pixels[index] = Color.rgb(COLOR_MAX, COLOR_MAX, COLOR_MAX);
                }                          
            }
        }
        // output bitmap              
        Bitmap bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        bmOut.setPixels(pixels, 0, width, 0, 0, width, height);
        return bmOut;
    }
 

 


IMEI number of your android device

You may be in a situation where you want to access your device IMEI number. Specially in case where you dont want your application's user to be irritated by enabling him to enter username and password for authentification.

You want to call android.telephony.TelephonyManager.getDeviceId().
This will return whatever string uniquely identifies the device.

You'll need the
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
permission to do this.

Source code to call telephone manager :

 You can get access to various useful information using telephony manager as :
  1. IMEI number
  2. Subscriber ID
  3. SIM state
  4. Is in roaming or not
 You create new instance of telephony manager as :

TelephonyManager mytelemanager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

1.To get imei number :

String IMEInumber = mytelemanager.getDeviceId();

2. IMEI and subscriber ID are one and the same.

3. SIM state

            int SIMState=mytelemanager.getSimState();
            switch(SIMState)
            {
                    case TelephonyManager.SIM_STATE_ABSENT :
                        Log.d(SIMState,"absent");
                        break;
                    case TelephonyManager.SIM_STATE_NETWORK_LOCKED :
                       
Log.d(SIMState,"network locked");
                        break;
                    case TelephonyManager.SIM_STATE_PIN_REQUIRED :
                       
Log.d(SIMState,"pin required");
                        break;
                    case TelephonyManager.SIM_STATE_PUK_REQUIRED :
                       
Log.d(SIMState,"puk required");
                        break;
                    case TelephonyManager.SIM_STATE_READY :
                       
Log.d(SIMState,"Ready");
                        break;
                    case TelephonyManager.SIM_STATE_UNKNOWN :
                       
Log.d(SIMState,"Unknown");
                        break;
                        }


 4.  Is in Roaming or not
  
      String phoneDetails;
      boolean isRoaming=mytelemanager.isNetworkRoaming();
              if(isRoaming)
                      phoneDetails+="\nIs In Roaming : "+"YES";
              else
                     phoneDetails+="\nIs In Roaming : "+"NO";


Monday, July 1, 2013

Selecting image from gallery and capturing from camera and setting it to ImageView

Basic image application in android requires selecting an image from gallery or capturing from camera.

Basically your any android app will require a XML file and associated Java class.
XML file here will contain an imageview, and two buttons. one to capture from camera and one to select from gallery.

1. Capturing an image and selecting from gallery are handled using switch case.

Source code for Java class :

package com.example.photoshop;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class ImageSelector extends Activity implements OnClickListener {
   
    protected static final int SELECT_PICTURE = 1;
    static final int camera=0;
    Bitmap bmp;
    Intent i;
    ImageView image;
    Button galleryy,cameraa;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.imageselector);
   
        galleryy = (Button)findViewById(R.id.gallery);
        cameraa = (Button)findViewById(R.id.camera);

        image = (ImageView)findViewById(R.id.image);
   
        galleryy.setOnClickListener(this);
        cameraa.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId())
        {

        case R.id.gallery: 
             i= new Intent(Intent.ACTION_GET_CONTENT);
            i.setType("image/*");                   
            startActivityForResult(Intent.createChooser(i,"Select Picture"), SELECT_PICTURE);
            break; 


        case R.id.camera :
            i= new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
             startActivityForResult(i, camera);
             break;
        }   
    }

   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK  )
        {
            if(requestCode == camera)
            {
            Bundle bdata = data.getExtras();
            bmp = (Bitmap)bdata.get("data"); 
 

               image.setImageBitmap(bmp);
            }
         
            else 
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
                String imageLocation = null;
                if(cursor!=null)
                {
                    int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    imageLocation = cursor.getString(column_index);
                    bmp = BitmapFactory.decodeFile(imageLocation);  
                   image.setImageBitmap(bmp);
                }
             
            }
         
        }
    }
}

 

2. XML will be same in either case. 

Source code for xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="@drawable/subtle_grunge">
   
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/cd"
        android:src="@android:drawable/screen_background_dark" />

    
    <Button
        android:id="@+id/gallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="81dp"
        android:text="@string/gallery" />

    <Button
        android:id="@+id/camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/gallery"
        android:layout_below="@+id/gallery"
        android:layout_marginTop="80dp"
        android:text="@string/camera" />

</RelativeLayout>