EditText Limit Upto 5 contacts only - android

I am making a Panic App, and allowing user to add multiple contacts and showing selected contacts into EditText by doing Tap on Add to Contacts button, whenever he/she wants to add.
In EditText getting something like this: 9867XXXXXX, 9866XXXXXX, ......
Changes i require:
Limit upto 5 Contacts only
I know how to limit for characters length in EditText, but don't know how to limit of 5 contacts only ?
private Button btnAddContacts ;
private EditText editContacts
..............................
btnAddContacts = (Button) findViewById(R.id.btnAddContacts);
btnAddContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent it= new Intent(Intent.ACTION_GET_CONTENT);
it.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(it, 1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
if(editContacts != null && editContacts.getText().toString().length()==0)
editContacts.setText(number);
else
if(editContacts != null) editContacts.append(","+number);
}

You can use a flag say maxNoContacts
Snippet:
public YourActivity extends Activity
{
int maxNoContacts = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState)
...
btnAddContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(maxNoContacts <5 )
{
Intent it= new Intent(Intent.ACTION_GET_CONTENT);
it.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(it, 1);
}
else
{
//show toast saying you added maximum no of contacts.
}
}
});
}
//Update maxNoContacts if contacts fetched properly.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
maxNoContacts++; //Increment maxNoContacts if it fetches contact properly.
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}

Related

Fetch email from the selected Contact in Android APK 25

Code to get permissions and start Pick Contact Activity
Button chooseContactsBtn = (Button) findViewById(R.id.addContactButton);
chooseContactsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getPermissionToReadUserContacts();
Intent contacts = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contacts, PICK_CONTACTS);
}
});
On Activity Result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACTS) {
if (resultCode == RESULT_OK) {
ContactDataManager contactsManager = new ContactDataManager(this, data);
try {
email = contactsManager.getContactEmail();
EditText e_mail = (EditText) findViewById(R.id.e_mail);
e_mail.setText(email);
} catch (ContactDataManager.ContactQueryException e) {
//Print Exception
}
}
}
}
getContactEmail Method in Contact Manager class.
public String getContactEmail() throws ContactQueryException
{
Cursor cursor = null;
String email = null;
try
{
cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?",
new String[]{intent.getData().getLastPathSegment()},
null);
if (cursor.moveToFirst())
{
email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
else {
System.out.println("No Email found. and leaving the method.");
}
} catch (Exception e)
{
Log.e(LOG_TAG, e.getMessage());
throw new ContactQueryException(e.getMessage());
} finally
{
if (cursor != null)
cursor.close();
}
return email;
}
This doesn't return anything. I have methods for returning name and number and they work fine.
Contact permission is positive.
You're invoking the phone picker intent (via the CommonDataKinds.Phone.CONTENT_URI uri in your intent).
You can do one of two things:
(a) change your picker intent to be an email picker, and get a specific email in return
(b) change your picker intent to be a contact picker, and get the first email found for that contact (if any), by using your getContactEmail which is based on a CONTACT_ID.
I'd go for option (a), code is:
Intent contacts = new Intent(Intent.ACTION_PICK, CommonDataKinds.Email.CONTENT_URI); // Note the Email!
startActivityForResult(contacts, PICK_CONTACTS);
and then:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACTS && resultCode == RESULT_OK) {
// Get the URI and query the content provider for the EMAIL
Uri contactUri = data.getData();
String[] projection = new String[]{CommonDataKinds.Email.ADDRESS};
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
// If the cursor returned is valid, get the email
if (cursor != null && cursor.moveToFirst()) {
String email = cursor.getString(0);
}
}
}
See more at: https://developer.android.com/guide/components/intents-common.html#Contacts

get path of video file selected from gallery getting NULL. How to get path of video file?

get path of video file selected from gallery getting NULL. How to get path of video file ? Get URi in Activity Result also give null. converting Uri to String also getting Null.
Intent intent;
String selectedVideo1Path, selectedVideo2Path;
EditText e1,e2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_activity);
Button button1 = (Button) findViewById(R.id.video1_btn);
Button button2 = (Button) findViewById(R.id.video2_btn);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 101);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 102);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (data.getData() != null) {
selectedVideo1Path = getPath(data.getData());
Toast.makeText(MergeVideosActivity.this, "Path 1 : "+selectedVideo1Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
if (requestCode == 102) {
if (data.getData() != null) {
selectedVideo2Path = getPath(data.getData());
//String str2 = selectedVideo2Path.toString();
// e2.setText(str2);
Toast.makeText(MergeVideosActivity.this, "Path 2 : "+selectedVideo2Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
}
This is my getPath method
public String getPath(Uri uri) {
int column_index = 0;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
}
return cursor.getString(column_index);
}
Selected Video from Gallery I hope its OK ? Check it
public void selectVideoFromGallery() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
} else {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI);
}
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
}
}
Update your getPath method
public String generatePath(Uri uri,Context context) {
String filePath = null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if(isKitKat){
filePath = generateFromKitkat(uri,context);
}
if(filePath != null){
return filePath;
}
Cursor cursor = context.getContentResolver().query(uri, new String[] { MediaStore.MediaColumns.DATA }, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath == null ? uri.getPath() : filePath;
}
#TargetApi(19)
private String generateFromKitkat(Uri uri,Context context){
String filePath = null;
if(DocumentsContract.isDocumentUri(context, uri)){
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { Media.DATA };
String sel = Media._ID + "=?";
Cursor cursor = context.getContentResolver().
query(Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
}

Get PicturePath selected from gallery to store it in dataBase

I used this code to upload image from gallery .it works perfectly..but the problem is that i wanna get the Image's path to store it in wamp dataBase ..`
public class Image extends Activity {
ImageView contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
contact = (ImageView) findViewById(R.id.candidat);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1)
contact.setImageURI(data.getData());
}
}
}
Thank you for help
You can get the exact path using this method -
public String getPathFromURI(Uri contentURI) {
String result = null;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int _id = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(_id);
cursor.close();
}
return result;
}
And use it like -
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1)
contact.setImageURI(data.getData());
String path = getPathFromURI(data.getData());
}
}
put this code:
public static final int IMAGEM = 1;
In the click put:
startActivityForResult(Intent.createChooser(new Intent(Intent.ACTION_PICK).setType("image/*"), "Select a image"), IMAGE);
In your activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
try {
if (resultCode == RESULT_OK && requestCode == IMAGE){
String pathImg = getRealPathFromURI(intent.getData());
}
}catch (Exception e){
e.printStackTrace();
}
}
public String getRealPathFromURI(Uri uri) {
//this method work for any api
Cursor cursor = null;
try {
Uri newUri = handleImageUri(uri);
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(newUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e){
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}

how to access phone book contacts?

I am using an Edittext and a button . On press of a button , phone book gets open and then user will select a contact from it and the selected phonenumber will get display on the edittext.
I followed many tutorials and but the methods that they are showing are already depreciated.
I have declared this permission: READ_CONTACTS in manifest
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_picker);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.pick_person)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
Answer provided by Digvesh Patel is correct. He has used "type" of contact, which returns number. so I have used his code and made some changes which i used in my application. it maybe helpful to someone
public int REQUESTCODE=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button select = (Button) findViewById(R.id.select);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, REQUESTCODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String name = c.getString(0);
String number = c.getString(1);
int type = c.getInt(2);
showSelectedNumber(name, number,type);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(String name, String number, int type){
TextView usernumber = (TextView) findViewById(R.id.textView1);
String typelabel = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(getResources(), type, "");
usernumber.setText(name+": "+number+" "+typelabel);
}

Contacts list crashes when accessed by app under some Android devices

In my app I give the user the opportunity to choose a number from his contacts. On my phone,(Samsung Galaxy SPlus) it works every time, without even a warning. I sent this app to some of my friends to test it before I upload it and they said that it crashed every time when choosing a name from the contacts list. I do not have access to any other device right now, so do you see anything problematic in my code?
search_contacts.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor1 = settings.edit();
editor1.putString("phone", number);
editor1.commit();
System.out.println("Set phone number to: " + number);
send_to = number;
text.setText(send_to);
// int type = c.getInt(1);
// showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}

Categories

Resources