Tuesday, August 19, 2014

How to read contacts from phone and sim card in android


Here are the Two function i have implemented one for displaying the sim contacts and one for
phone contacts

1) Display Sim Contacts


private void displaySIMContacts() 

{
   try
   {
      String simPhoneId = null;
      String simPhoneNum = null;
      String simPhoneName = null;
      Uri simUri = Uri.parse("content://icc/adn");
      Cursor simCusor = getContentResolver().query(simUri, null, null, null, null);                                                   while(simCursor.moveToNext())
      {
        simPhoneId = simCursor.getString(simCursor.getColumnIndex("_id");
        simPhoneNum = simCursor.getString(simCursor.getColumnIndex("name");
        simPhoneName = simCursor.getString(simCursor.getColumIndex("number);
        Log.v(TAG, " id = " + simPhoneId + " - name = " + simPhoneName + " - number = " +  simPhoneNumber); 
      }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}


2) Display All Phone Contacts

private void dispalyPhoneContacts()

{
   Cursor cursor = getContentResolver().query(                                                                                                                         ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);

   while (cursor.moveToNext())
  {
      String name                               =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        Log.v(TAG, "Name = " + name+ " - number = " +  phoneNumber); 

   }
}


Note:- You need to provide the read contacts permission in android manifest file
<uses-permission android:name="android.permission.READ_CONTACTS"/>

You can call these functions either on button click or as you need.

Wednesday, August 13, 2014

how to make a customized list view with images and text

1) Create a new Android project go to
    file-> new Android application->
    Type the Application name as:- ListView
    package name as:-com.example.listview
    then click next


2) Then follow these steps:-


     click next
3) 

click next

4)


5) click next and change the Activity name according to your need in my case i am using the default 
name as MainActivity


and click finish

6) The layout file will open  


    click to activity_main.xml next to graphical layout tab
    and write this code
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
     />
    </LinearLayout>

7)  Create one more Xml file by right clicking on layout folder->New->Others
     ->Android Xml file  name it as list_item  and write this code
      
      <?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/icon"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:contentDescription="@string/image"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/icon"
        android:paddingBottom="10dp"
        android:textColor="#CC0033"
        android:textSize="16sp" />

    </RelativeLayout>

8)  Now click on source folder (src folder) go to the package open MainActivity.java
     and write the following code.
      
    package com.example.listview;


    import java.util.ArrayList;
    import java.util.List;
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListView;
    import android.widget.Toast;


   public class MainActivity extends Activity implements OnItemClickListener{

public static final String[] itemTitles = new String[] { "Twitter",
"Facebook","Linkedin" ,"ImportContact", "Google","Hello Android"};
        
        //  Create the drawable folder in the res folder and put all these images in that particular folder

public static final Integer[] itemImages = { R.drawable.twitter_icon,
R.drawable.fb_icon, R.drawable.linkedin_logo,  
                R.drawable.contact_icon,R.drawable.ic_launcher,R.drawable.ic_launcher };

      
ListView listView;
List<Item> listItems;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listItems = new ArrayList<Item>();
for (int i = 0; i < itemTitles.length; i++) {
Item item = new Item(itemImages[i], itemTitles[i]);
listItems.add(item);
}

listView = (ListView) findViewById(R.id.list);
CustomArrayAdapter adapter = new CustomArrayAdapter(this,
R.layout.list_item, listItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(this,"Clicked:-"+itemTitles[arg2],Toast.LENGTH_SHORT).show();
 }
   }

9) Create Other class in the same package name it as Item.java
     and write this code
     
    package com.example.listview;

    public class Item {
   
int imageIds;
String title;
public Item(int imageIds, String title) {
super();
this.imageIds = imageIds;
this.title = title;
}
public int getImageIds() {
return imageIds;
}
public void setImageIds(int imageIds) {
this.imageIds = imageIds;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

@Override
public String toString() {
return "Item [title=" + title + "]";
}
   }
 
10) Create Other class in the same package name it as CustomArrayAdapter.java
     and write this code
     
     package com.example.listview;

     import java.util.List;
     import android.app.Activity;
     import android.content.Context;
     import android.view.LayoutInflater;
     import android.view.View;
     import android.view.ViewGroup;
     import android.widget.ArrayAdapter;
     import android.widget.ImageView;
     import android.widget.TextView;

    public class CustomArrayAdapter extends ArrayAdapter<Item> {
    
    Context context;
 
    public CustomArrayAdapter(Context context, int resourceId,
            List<Item> items) {
        super(context, resourceId, items);
        this.context = context;
    }
     
    /*private view holder class*/
    private class ViewHolder {
        ImageView imageView;
        TextView txtTitle;       
    }
     
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        Item itemList = getItem(position);
         
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) 
      // Checking the convert view against null helps in reusing the resources instead of creating them every time
       {    
            convertView = mInflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder();
            holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
            holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();                 
     
        holder.txtTitle.setText(itemList.getTitle());
        holder.imageView.setImageResource(itemList.getImageIds());
         
        return convertView;
      }
    }
    
11) Your done now Compile the code run it on emulator and check the results.

     
     
    

Thursday, August 7, 2014

Text to speech in android

1) Create a new Android project go to
file-> new Android application-> Type the Application name as:- TextToSpeech
package name as:-com.example.texttospeech
then click next

                      




2) Then follow these steps:-



                     

click next

3)
                              

                     

click next

4)

                     

5) click next and change the Activity name according to your need in this project.

I have used the default name as activity_main.


                     

and click finish

6) The layout file will open 

    click to activity_main.xml next to graphical layout tab
    and write this code.
    <LinearLayout 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:orientation="vertical" >

   <EditText

     android:id="@+id/txtText"

     android:layout_width="fill_parent"

     android:layout_height="wrap_content"

     android:hint="@string/editText" />

  <Button

    android:id="@+id/btnSpeak"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_gravity="center_horizontal"

   android:layout_marginTop="50dp"

   android:text="@string/btnSpeak" />


  </LinearLayout>




7) Go to values folder -> Strings.xml in that put these fields


<?xml version="1.0" encoding="utf-8"?> 

<resources>

<string name="app_name">TextToSpeech</string>

<string name="btnSpeak">Speak Out</string>

<string name="action_settings">Settings</string>

<string name="editText">enter your text</string>

</resources>


8) Go to source folder open MainActivity.java
    and write this code.

    
package com.example.texttospeech;

import java.util.Locale;

import android.speech.tts.TextToSpeech;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity  implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);

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

txtText = (EditText) findViewById(R.id.txtText);

// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
speakOut();
}

});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}

@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {

int result = tts.setLanguage(Locale.US);

if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}

} else {
Log.e("TTS", "Initilization Failed!");
}

}
private void speakOut() {
// TODO Auto-generated method stub

        String text = txtText.getText().toString();

        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

}

9) Your done with this now compile your project and run it.
    Before click on run connect your android phone to your PC and in your mobile 
    Developer settings click on USB Debugging option.

Note: In some of the phones  Text to speech engines are not installed you have to installed it
through Google play store.
else you can use the following code to check it .


Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, 0);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 0){
    if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
    Toast.makeText(getApplicationContext(),"Already Installed", Toast.LENGTH_LONG).show();
} else {
    Intent installIntent = new Intent();
    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
    startActivity(installIntent);
    Toast.makeText(getApplicationContext(),"Installed Now", Toast.LENGTH_LONG).show();
}