Wednesday, 14 December 2011
Monday, 14 November 2011
Saturday, 8 October 2011
Custom Dialog without border
In order to create the Dialog without border,we need to create the out custom dialog.To create the custom dialog, our class should extend the Dialog class.
See the below example...
MyProgressDialog.java is as follows.
import android.app.Dialog;
import android.content.Context;
import android.view.WindowManager.LayoutParams;
import android.widget.ProgressBar;
public class MyProgressDialog extends Dialog {
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message) {
return show(context, title, message, false);
}
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate) {
return show(context, title, message, indeterminate, false, null);
}
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate, boolean cancelable) {
return show(context, title, message, indeterminate, cancelable, null);
}
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate,
boolean cancelable, OnCancelListener cancelListener) {
MyProgressDialog dialog = new MyProgressDialog(context);
dialog.setTitle(title);
dialog.setCancelable(cancelable);
dialog.setOnCancelListener(cancelListener);
/* The next line will add the ProgressBar to the dialog. */
dialog.addContentView(new ProgressBar(context), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
dialog.show();
return dialog;
}
public MyProgressDialog(Context context) {
super(context, R.style.NewDialog);
}
}
The styles.xml file is as like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NewDialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowTitleStyle">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:background">@android:color/transparent</item>
</style>
</resources>
In the Activity class write like this
MyProgressDialog dialog = new MyProgressDialog(Register.this);
dialog.setContentView(R.layout.pleasewaitpopup);
dialog.show();
For more information here
See the below example...
MyProgressDialog.java is as follows.
import android.app.Dialog;
import android.content.Context;
import android.view.WindowManager.LayoutParams;
import android.widget.ProgressBar;
public class MyProgressDialog extends Dialog {
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message) {
return show(context, title, message, false);
}
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate) {
return show(context, title, message, indeterminate, false, null);
}
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate, boolean cancelable) {
return show(context, title, message, indeterminate, cancelable, null);
}
public static MyProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate,
boolean cancelable, OnCancelListener cancelListener) {
MyProgressDialog dialog = new MyProgressDialog(context);
dialog.setTitle(title);
dialog.setCancelable(cancelable);
dialog.setOnCancelListener(cancelListener);
/* The next line will add the ProgressBar to the dialog. */
dialog.addContentView(new ProgressBar(context), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
dialog.show();
return dialog;
}
public MyProgressDialog(Context context) {
super(context, R.style.NewDialog);
}
}
The styles.xml file is as like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NewDialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowTitleStyle">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:background">@android:color/transparent</item>
</style>
</resources>
In the Activity class write like this
MyProgressDialog dialog = new MyProgressDialog(Register.this);
dialog.setContentView(R.layout.pleasewaitpopup);
dialog.show();
For more information here
Labels:
Android
Tuesday, 4 October 2011
Create Database using exiting database
In this tutorial, I am going to create the database by using the existing database. In order to do this , place your existing database into the “assets” folder. The DBAdapter.java file is as follows.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "game.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
private static DBAdapter mDBConnection;
private DBAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = "/data/data/"+ context.getApplicationContext().getPackageName() + "/databases/";
}
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// ----------------------- DATABASE Operations ------------------------------
public long insertPuzzle(String problem,String solution,String level, int status)
{
ContentValues initialValues = new ContentValues();
initialValues.put("problem", problem);
initialValues.put("solution",solution);
initialValues.put("level",level);
initialValues.put("status",status);
return myDataBase.insert("puzzles", null, initialValues);
}
}
In the Activity class call like this
private DBAdapter db=null;
db=DBAdapter.getDBAdapterInstance(this);
/*try {
db.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}*/
db.openDataBase();
db.insertPuzzle(..,..,..);
Labels:
Android
Monday, 3 October 2011
Store the Image into SQLite Database
In this tutorial, I used the BLOB data type to store the image into the SQLite database.
BLOB --> Binary Large Object.
This data type is used to store the values in the binary format. This type is used to store the images ,audio and video file.
Here I am going to store the image .So that ,
1.I have to convert the image to byte[].
2.This byte[] is going to be stored in the database.
Example:
The DBAdapter .java file
import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public class DBAdapter {
private static final String DATABASE_NAME = "myDatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String USERDETAILS=
"create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERDETAILS);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility) {
ContentValues initialValues = new ContentValues();
initialValues.put("username", uname);
initialValues.put("userid",userid);
initialValues.put("password", pass);
initialValues.put("photo",photo);
initialValues.put("visibility",visibility);
return db.insert("userdetails", null, initialValues);
}
public Cursor getUserDetails(String userid) {
return db.rawQuery("select username,userid,photo,visibility ,usersno from userdetails where userid='"+userid+"'",null);
}
public int updateUserDetails(String userid,String username,byte[] photo,String visibility) {
ContentValues args = new ContentValues();
args.put("username", username);
args.put("photo",photo);
args.put("visibility",visibility);
return db.update("userdetails", args,"userid='" +userid+"'", null);
}
public Cursor searchFriends(String username,String to_userid) {
return db.rawQuery("select userid,username,photo,usersno from userdetails where username LIKE '%"+username+"%' AND userid <>'"+to_userid+"' AND userid NOT IN (select request_destinationid from requestdetails where request_sourceid='"+to_userid+"' and status=1)",null);
}
public void deleteFriend(int l_userid,int dest_userid) {
db.delete("requestdetails","request_sourceid="+l_userid+" and request_destinationid="+dest_userid+" and status=1", null);
db.delete("requestdetails","request_sourceid="+dest_userid+" and request_destinationid="+l_userid+" and status=1", null);
}
}
In the Activity class write like this
To Store into the DB..
private DBAdapter db=new DBAdaptet(this);
db.open();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = (BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
db.insertUserDetails(fullName,userid, password, photo,visibility);
Retrieve from DB..
byte[] photo=cursor.getBlob(..);
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
image_view.setImageBitmap(theImage);
Labels:
Android
Friday, 30 September 2011
Genarate KeyStore to create a Signed APK and Google Maps in Android
To generate the keystore:
==================
----------------------------------------------------------------------------------------------------------------------------------
keytool -genkey -v -keystore myCertificate.keystore -alias myKey -keyalg RSA -keysize 2048 -validity 20000
----------------------------------------------------------------------------------------------------------------------------------
>>Fill the Details:
Enter Keystore Password :- ********
Re-enter new Password :- ********
What is your first and last Name? :-kkbrothers
What is the name of your organizational unit?:- Elites
What is the name of your organization?:-kkbrothers
What is the name of your City or Locality?:-Hyd
What is the name of your State or Province?:-Ap
What is the two-letter country code for this unit?:- IND
Enter key password for <myKey>
(RETURN if same as keystore password):-*******
Re-enter new password:-*******
For GoogleMaps:
============
Some of the Links link1 , link2
E:\keystore>keytool.exe -list -alias androiddebugkey -keystore "E:\keystore\debu
g.keystore" -storepass android -keypass android
androiddebugkey, Nov 26, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): FB:93:B3:1D:16:A8:DB:84:B3:1B:0F:5D:EA:51:FB:BA
Your key is:urkey
This key is good for all apps signed with your certificate whose fingerprint is:
FB:93:B3:1D:16:A8:DB:84:B3:1B:0F:5D:EA:51:FB:BA
Here is an example xml layout to get you started on your way to mapping glory:
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="urkey"
/>
==================
----------------------------------------------------------------------------------------------------------------------------------
keytool -genkey -v -keystore myCertificate.keystore -alias myKey -keyalg RSA -keysize 2048 -validity 20000
----------------------------------------------------------------------------------------------------------------------------------
>>Fill the Details:
Enter Keystore Password :- ********
Re-enter new Password :- ********
What is your first and last Name? :-kkbrothers
What is the name of your organizational unit?:- Elites
What is the name of your organization?:-kkbrothers
What is the name of your City or Locality?:-Hyd
What is the name of your State or Province?:-Ap
What is the two-letter country code for this unit?:- IND
Enter key password for <myKey>
(RETURN if same as keystore password):-*******
Re-enter new password:-*******
For GoogleMaps:
============
Some of the Links link1 , link2
E:\keystore>keytool.exe -list -alias androiddebugkey -keystore "E:\keystore\debu
g.keystore" -storepass android -keypass android
androiddebugkey, Nov 26, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): FB:93:B3:1D:16:A8:DB:84:B3:1B:0F:5D:EA:51:FB:BA
Your key is:urkey
This key is good for all apps signed with your certificate whose fingerprint is:
FB:93:B3:1D:16:A8:DB:84:B3:1B:0F:5D:EA:51:FB:BA
Here is an example xml layout to get you started on your way to mapping glory:
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="urkey"
/>
Labels:
Android
Important links
Android Samples http://www.bogotobogo.com/android.html
1.Html Color Codes
2. JavaMail api documentation here
3.Developing Web applications with Tomcat and Eclipse here
4.Android Animation Tutorial here
5.How to make a exe file of Java Program ? here
6.Acces to the MMS part file content here
7.How to Read MMS Data in Android? here
8.Android and self-signed ssl certificates here
9.Sending Email in Android using JavaMail API here
10. Android Sample code projects HERE IMP.
11. Other language Samples HERE
12. File Uploading and downloading in android. HERE
Labels:
Links
Wednesday, 28 September 2011
Android BroadcastReceiver for SMS
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private SharedPreferences myPrefs;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "SMS Received", Toast.LENGTH_LONG).show();
myPrefs = context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
if (intent.getAction().equals(SMS_RECEIVED)) {
//Toast.makeText(context, "SMS Received", Toast.LENGTH_LONG).show();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
String number=messages[0].getOriginatingAddress();
if(PhoneNumberUtils.compare(number1, number)||(number.endsWith(number1))){
Intent intent1=new Intent(context,AudioHandler.class);
intent1.putExtra("filename", details.getFilename());
intent1.putExtra("from",details.getFrom());
intent1.putExtra("subject", details.getSubject());
intent1.putExtra("content", details.getContent());
intent1.putExtra("time", details.getTime());
context.startService(intent1);
}
}
}
}
}
And also declare the bellow permission in the android manifestfile
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private SharedPreferences myPrefs;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "SMS Received", Toast.LENGTH_LONG).show();
myPrefs = context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
if (intent.getAction().equals(SMS_RECEIVED)) {
//Toast.makeText(context, "SMS Received", Toast.LENGTH_LONG).show();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
String number=messages[0].getOriginatingAddress();
if(PhoneNumberUtils.compare(number1, number)||(number.endsWith(number1))){
Intent intent1=new Intent(context,AudioHandler.class);
intent1.putExtra("filename", details.getFilename());
intent1.putExtra("from",details.getFrom());
intent1.putExtra("subject", details.getSubject());
intent1.putExtra("content", details.getContent());
intent1.putExtra("time", details.getTime());
context.startService(intent1);
}
}
}
}
}
And also declare the bellow permission in the android manifestfile
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
Labels:
Android
Query the Android Contacts
This code snippet queries all the contacts from the android device and sort those contacts
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ContactActivity extends Activity {
ArrayList<HashMap<String,String>> contactData=new ArrayList<HashMap<String,String>>();
ListView nameList;
private DBAdapter db;
String contact="";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setTitle("Wait....");
setContentView(R.layout.deleteaccountlist);
db=new DBAdapter(this);
db.open();
nameList=(ListView)findViewById(R.id.listView2);
android.telephony.TelephonyManager mng=(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
new QueryContacts().execute();
nameList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
HashMap map=contactData.get(position);
db.insertSMSContact((String)map.get("name"),(String)map.get("number"));
db.insertSpeechDetails((String)map.get("number"), 0);
setResult(Activity.RESULT_OK);
finish();
}
});
}
class QueryContacts extends AsyncTask<Void,Void,Void> {
Dialog dialog;
@Override
protected void onPreExecute( ) {
dialog=ProgressDialog.show(ContactActivity.this,"Please wait...", "Loading the contacts..",true, true);
contactData.clear();
}
@Override
protected void onPostExecute(Void result) {
SimpleAdapter contactsAdapter=new SimpleAdapter(ContactActivity.this,contactData,R.layout.contactview,new String[]{"name","number"},new int[]{R.id.contactName,R.id.contactNumber});
nameList.setAdapter(contactsAdapter);
dialog.cancel();
setTitle("Select Contact:");
}
protected void onProgressUpdate(Void... values) {
}
@SuppressWarnings("unchecked")
@Override
protected Void doInBackground(Void... arg0) {
ContentResolver cr = getContentResolver();
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
try{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
HashMap<String,String> map=new HashMap<String,String>();
map.put("name", name);
map.put("number", phoneNumber);
contactData.add(map);
}
phones.close();
}
}catch(Exception e){}
}
/*Cursor cur = cr.query(People.CONTENT_URI,null, null, null, null);
while (cur.moveToNext()) {
try{
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
// if (Integer.parseInt(cur.getString(cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
Cursor pCur = cr.query(Contacts.Phones.CONTENT_URI, null,Contacts.Phones.PERSON_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
HashMap<String,String> map=new HashMap<String,String>();
String phoneNumber=pCur.getString(pCur.getColumnIndex(Contacts.Phones.NUMBER));
map.put("name", name);
map.put("number", phoneNumber);
contactData.add(map);
contact=contact+":"+name;
contact=contact+":"+phoneNumber;
}
//}
}catch(Exception e){e.printStackTrace();}
}
/*
while (cursor.moveToNext()) {
String name=cursor.getString(cursor.getColumnIndex(People.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex( People.NUMBER));
HashMap<String,String> map=new HashMap<String,String>();
map.put("name", name);
map.put("number", phoneNumber);
if(phoneNumber!=null)
contactData.add(map);
}*/
Collections.sort(contactData, new Comparator(){
@Override
public int compare(Object o1, Object o2) {
HashMap map1=(HashMap)o1;
HashMap map2=(HashMap)o2;
String s1=(String)map1.get("name");
String s2=(String)map2.get("name");
return s1.compareTo(s2);
}
});
/*
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
HashMap<String,String> map=new HashMap<String,String>();
map.put("name", name);
map.put("number", phoneNumber);
contactData.add(map);
}
phones.close();
}
}
Collections.sort(contactData, new Comparator(){
@Override
public int compare(Object o1, Object o2) {
HashMap map1=(HashMap)o1;
HashMap map2=(HashMap)o2;
String s1=(String)map1.get("name");
String s2=(String)map2.get("name");
return s1.compareTo(s2);
}
});*/
return null;
}
}
}
Also declare the permission in the android manifest file
<uses-permission android:name="android.permission.READ_CONTACTS"/>
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ContactActivity extends Activity {
ArrayList<HashMap<String,String>> contactData=new ArrayList<HashMap<String,String>>();
ListView nameList;
private DBAdapter db;
String contact="";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setTitle("Wait....");
setContentView(R.layout.deleteaccountlist);
db=new DBAdapter(this);
db.open();
nameList=(ListView)findViewById(R.id.listView2);
android.telephony.TelephonyManager mng=(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
new QueryContacts().execute();
nameList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
HashMap map=contactData.get(position);
db.insertSMSContact((String)map.get("name"),(String)map.get("number"));
db.insertSpeechDetails((String)map.get("number"), 0);
setResult(Activity.RESULT_OK);
finish();
}
});
}
class QueryContacts extends AsyncTask<Void,Void,Void> {
Dialog dialog;
@Override
protected void onPreExecute( ) {
dialog=ProgressDialog.show(ContactActivity.this,"Please wait...", "Loading the contacts..",true, true);
contactData.clear();
}
@Override
protected void onPostExecute(Void result) {
SimpleAdapter contactsAdapter=new SimpleAdapter(ContactActivity.this,contactData,R.layout.contactview,new String[]{"name","number"},new int[]{R.id.contactName,R.id.contactNumber});
nameList.setAdapter(contactsAdapter);
dialog.cancel();
setTitle("Select Contact:");
}
protected void onProgressUpdate(Void... values) {
}
@SuppressWarnings("unchecked")
@Override
protected Void doInBackground(Void... arg0) {
ContentResolver cr = getContentResolver();
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
try{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
HashMap<String,String> map=new HashMap<String,String>();
map.put("name", name);
map.put("number", phoneNumber);
contactData.add(map);
}
phones.close();
}
}catch(Exception e){}
}
/*Cursor cur = cr.query(People.CONTENT_URI,null, null, null, null);
while (cur.moveToNext()) {
try{
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
// if (Integer.parseInt(cur.getString(cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
Cursor pCur = cr.query(Contacts.Phones.CONTENT_URI, null,Contacts.Phones.PERSON_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
HashMap<String,String> map=new HashMap<String,String>();
String phoneNumber=pCur.getString(pCur.getColumnIndex(Contacts.Phones.NUMBER));
map.put("name", name);
map.put("number", phoneNumber);
contactData.add(map);
contact=contact+":"+name;
contact=contact+":"+phoneNumber;
}
//}
}catch(Exception e){e.printStackTrace();}
}
/*
while (cursor.moveToNext()) {
String name=cursor.getString(cursor.getColumnIndex(People.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex( People.NUMBER));
HashMap<String,String> map=new HashMap<String,String>();
map.put("name", name);
map.put("number", phoneNumber);
if(phoneNumber!=null)
contactData.add(map);
}*/
Collections.sort(contactData, new Comparator(){
@Override
public int compare(Object o1, Object o2) {
HashMap map1=(HashMap)o1;
HashMap map2=(HashMap)o2;
String s1=(String)map1.get("name");
String s2=(String)map2.get("name");
return s1.compareTo(s2);
}
});
/*
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
HashMap<String,String> map=new HashMap<String,String>();
map.put("name", name);
map.put("number", phoneNumber);
contactData.add(map);
}
phones.close();
}
}
Collections.sort(contactData, new Comparator(){
@Override
public int compare(Object o1, Object o2) {
HashMap map1=(HashMap)o1;
HashMap map2=(HashMap)o2;
String s1=(String)map1.get("name");
String s2=(String)map2.get("name");
return s1.compareTo(s2);
}
});*/
return null;
}
}
}
Also declare the permission in the android manifest file
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Labels:
Android
Subscribe to:
Posts (Atom)