I get repeated numbers in the ContactPicker - android

I've a problem using the ContactPicker in Android. My code is the next
public void showContacts(View v){
phoneNumber.setText("");
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, 1001);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1001:
Cursor cursor = null;
String[] numeros = null;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null,
Phone.CONTACT_ID + "=?", new String[] {id}, null);
int phoneIdx = cursor.getColumnIndex(Phone.NUMBER);
if(cursor.getCount() > 0){
numeros = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int cont = 0;
do{
numeros[cont] = cursor.getString(phoneIdx);
cont++;
}while(cursor.moveToNext());
}
}
} catch (Exception e) {
Log.e("Exception", "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
if(numeros != null){
if(numeros.length > 1){
showNumbers(numeros);
}else{
phoneNumber.setText(numeros[0]);
}
}
}
break;
}
}
}
private void showNumbers(final String[] numeros){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(numeros, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo, int item) {
phoneNumber.setText(numeros[item]);
dialogo.cancel();
}
});
builder.create().show();
}
Basically in the first method I call the ContactPicker, in the second I receive the answer of this, I process that and validate if the user have more than one phone.
The problem is, the algorithm return me six times the numbers. I don't know why occur that.

Related

onActivityResult() is not working in fragment " OUTPUT: You haven't picked Image "

This is my code and when i run the code then output will be "**you haven't picked images"**
sdk which i use currently in this app
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.letsget.humanitysavior"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
Here is the manifests permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Here is the fragment code
public class NewPostPublicFragment extends Fragment {
public NewPostPublicFragment() {
// Required empty public constructor
}
private int PICK_IMAGE_MULTIPLE = 3;
String imageEncoded;
List<String> imagesEncodedList;
private GridView gvGallery;
private NewPostImagesAdapter galleryAdapter;
CarouselView carouselView;
private ArrayList<Uri> mArrayUri;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_post_public, container, false);
gvGallery = view.findViewById(R.id.gridview);
ImageView selectimgicon = view.findViewById(R.id.selectimgicon);
ImageView selectvideoicon = view.findViewById(R.id.selectvideoicon);
ImageView selectcameraicon = view.findViewById(R.id.selectcameraicon);
carouselView = view.findViewById(R.id.carouselview);
final TextInputEditText postcategories = view.findViewById(R.id.postcategories);
//carouselView.setPageCount(mThumbIds.length);
//carouselView.setImageListener(imageListener);
//for image selection
selectimgicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//LOGIC FOR PROFILE PICTURE
selectImagesFromGallery();
}
});
postcategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items = { "Book", "Cloth", "Electronic", "Furniture", "Bag", "Social Post", "Other" };
AlertDialog.Builder postCategoryBuilder = new AlertDialog.Builder(v.getContext(),AlertDialog.THEME_HOLO_LIGHT);
postCategoryBuilder.setTitle("Select Post Category");
postCategoryBuilder.setIcon(R.mipmap.categoryicon);
postCategoryBuilder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
postcategories.setText(items[which]);
}
});
postCategoryBuilder.show();
}
});
return view;
}
ImageListener imageListener = new ImageListener() {
#Override
public void setImageForPosition(int position, ImageView imageView) {
//imageView.setImageResource(mThumbIds[position]);
imageView.setImageURI(mArrayUri.get(position));
}
};
private void selectImagesFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_MULTIPLE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Log.v(TAG, "requestCode=" + requestCode + ", resultCode = "+ resultCode + ", data = " + data);
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && data != null) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri = data.getData();
// Get the cursor
Cursor cursor = getActivity().getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
mArrayUri.add(mImageUri);
galleryAdapter = new NewPostImagesAdapter(getActivity().getApplicationContext(),mArrayUri);
gvGallery.setAdapter(galleryAdapter);
gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
.getLayoutParams();
mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);
carouselView.setPageCount(mArrayUri.size());
carouselView.setImageListener(imageListener);
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
galleryAdapter = new NewPostImagesAdapter(getActivity().getApplicationContext(),mArrayUri);
gvGallery.setAdapter(galleryAdapter);
gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
.getLayoutParams();
mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(getContext(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
when I run this app and tap on image button then it open the gallery and select the images after that when i press the done button then it's not display images it just display toast message you haven't picked images
Check these Steps:
Give permission to use camera in AndroidManifest.xml
Use this code to get image properly
String RequestCode=123;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RequestCode && resultCode== RESULT.OK){
//Here get your image code
}
}
Also Check Toast in your OnActivityResult() method and check if condition is true or false. Probably your if condition is false that's why image is not received from gallery.

Show image gallery in camera intent

I'm working on a feature where the user can take a picture and choose from the gallery. This is basically where it starts and goes on to save the images in db.
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
However, I want to make the user experience better. I want to skip the dialog where the user selects one of the options (from gallery or camera) and instead show the gallery in camera intent. Something similar to this:
I hope you get my point. Thanks :)
Get all image
public List<File> getAllShownImagesPath(Context context) {
//get all images
String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.Media.SIZE};
List<File> result = new ArrayList<>();
File f = null;
final Cursor cursor = context.getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, // Specify the provider
columns, // The columns we're interested in
null, // A WHERE-filter query
null, // The arguments for the filter-query
MediaStore.Images.Media.DATE_ADDED + " DESC"
);
if (cursor != null) {
cursor.moveToFirst();
for (int r = 0; r < cursor.getCount(); r++, cursor.moveToNext()) {
int i = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
//int l = cursor.getString(1).length();
final int image_path_col = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (i > 0) {
f = new File(cursor.getString(image_path_col));
if (f.length() > 0) {
result.add(f);
}
}
}
cursor.close();
}
return result;
}
Add all image into recyclerview or listview

Why I cant't get the video duration from MediaStore?

On one of my device, the following code can't make my video appear in Gallery:
File file = new File(path);
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
activity.sendBroadcast(scanFileIntent);
So I use scanFile explicitly:
android.media.MediaScannerConnection.scanFile(activity, new String[]{file.getAbsolutePath()},
new String[]{"video/" + mMimeType}, null);
When my video is xxx.mpeg4, the value of mMimeType is mp4, the result is that the video can appear in MediaStore but I can't get the duration later(the returned value is always 0). Need help on this.
public static long[] getVideoDetail(Context context, Uri uri) {
long[] result = new long[] {DEFAULT_VIDEO_FRAME_WIDTH, DEFAULT_VIDEO_FRAME_HEIGHT, -1};
if(uri == null || (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()))) {
return result;
}
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION, MediaStore.Video.VideoColumns.DURATION};
Cursor cursor = null;
boolean success = false;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor.moveToFirst()) {
String resolution = cursor.getString(0);
if(!StringUtils.isEmpty(resolution)) {
int index = resolution.indexOf('x');
result[0] = Integer.parseInt(resolution.substring(0, index));
result[1] = Integer.parseInt(resolution.substring(index + 1));
if(result[0] != 0 && result[1] != 0) {
success = true;
}
if(result[0] > result[1]) {
swap(result, 0, 1);
}
}
result[2] = cursor.getLong(1);
if(result[2] >= 0 && success) {
success = true;
} else {
success = false;
}
}
if (null != cursor) {
cursor.close();
}
}
catch (Exception e) {
// do nothing
} finally {
try {
if (null != cursor) {
cursor.close();
}
} catch (Exception e2) {
// do nothing
}
}
if (!success) {
try {
ContentResolver contentResolver = context.getContentResolver();
String selection = MediaStore.Images.Media._ID + "= ?";
String id = uri.getLastPathSegment();
String[] selectionArgs = new String[]{ id };
cursor = contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor.moveToFirst()) {
String resolution = cursor.getString(0);
if(!StringUtils.isEmpty(resolution)) {
int index = resolution.indexOf('x');
result[0] = Integer.parseInt(resolution.substring(0, index));
result[1] = Integer.parseInt(resolution.substring(index + 1));
if(result[0] > result[1]) {
swap(result, 0, 1);
}
}
result[2] = cursor.getLong(1);
}
if (null != cursor) {
cursor.close();
}
} catch (Exception e) {
// do nothing
} finally {
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
// do nothing
}
}
}
if(result[0] <= 0) {
result[0] = DEFAULT_VIDEO_FRAME_WIDTH;
}
if(result[1] <= 0) {
result[1] = DEFAULT_VIDEO_FRAME_HEIGHT;
}
return result;
}
As I see in your code you are requesting duration in your projection
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION, MediaStore.Video.VideoColumns.DURATION};
now you just need to retrieve it from the cursor like shown below:
long timeInMs = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
get help from MediaPlayer :
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(context, Uri.parse(uri));
} catch (IOException e) {
Log.d("-MS-","Cannot parse url");
e.printStackTrace();
}
int duration= mp.getDuration();
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION,duration};
I always get Duration by MediaPlayer.

I am trying to export a single contact from the address book to .vcf. Where am I going wrong?

package com.example.address_book;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract.CommonDataKinds.Phone;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageButton;import android.widget.Toast;
public class MainActivity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
String[] num={" "," "};
String number1;
#Overrideprotected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{ImageButton add_me = (ImageButton) findViewById(R.id.imageButton1);
add_me.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE);startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
});
}catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
int n=0;int n1=0;
if (requestCode == PICK_CONTACT_REQUEST){
if (resultCode == RESULT_OK){
Uri stuff = data.getData();Intent in = new Intent(android.content.Intent.ACTION_VIEW, stuff);
in.setType("text/x-vcard");
startActivity(in);
String[] projection = {Phone.NUMBER};Cursor cursor = getContentResolver().query(stuff, projection, null, null, null);cursor.moveToFirst();
int column = cursor.getColumnIndex(Phone.NUMBER);
number1 = cursor.getString(column);
n++;number1 = number1.replace("-" ,"");
for(int i=0;i<num.length;i++){num[i]=number1;
}
}
}
}
#Overridepublic boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);return true;
}
}
Try with this dude it will open your contact jusr pass contactId in this
Intent intent = new Intent(Intent.ACTION_VIEW);
//pass your contact id
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
intent.setData(uri);
mcntxt.startActivity(intent);

Text to speech doesn't seem to be working and there is no error message in logCat

There appears to be something wrong with this code, each time its saying that I have not installed texttoSpeech on create and I have done, also when i click the start read button the application crashed with no error messages... So heres the code..
public class CBrecipeReader extends Activity{
public Cursor cursor;
CBDataBaseHelper data;
public static int ReadData = 1;
public TextToSpeech Speak = null;
public boolean SpeakInit = false;
public TextView Speech;
public TextView rowIDText2;
CBListAdapter adapter;
String RowID;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.texttospeech);
Bundle extras = getIntent().getExtras();
Button StartSpeech = (Button)findViewById(R.id.startSpeech);
rowIDText2 = (TextView)findViewById(R.id.rowID2);
Speech = (TextView) findViewById(R.id.sayThis);
if (extras != null) {
RowID = extras.getString("SELECTED3");
rowIDText2.setText(RowID);
}
if (rowIDText2.getText() != ""){
data = new CBDataBaseHelper(this);
String s = rowIDText2.getText().toString();
int ID = Integer.parseInt(s);
data.open();
Cursor cursor = data.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
Speech.setText(cursor.getString(1) + " " + cursor.getString(2) + " " + cursor.getString(3));
}
data.close();
}
//+ " " + cursor.getString(2) + "" + cursor.getString(3)
initSpeak();
speakButtons(StartSpeech);
}
protected void initSpeak(){
Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, ReadData);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == ReadData){
if (resultCode == Engine.CHECK_VOICE_DATA_PASS){
Speak = new TextToSpeech(this, new OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS){
SpeakInit = true;
if(Speak.isLanguageAvailable(Locale.UK) >= 0){
Speak.setLanguage(Locale.UK);
Speak.setPitch(0.8f);
Speak.setSpeechRate(1.1f);
}
}
}
});
}else {
Intent installVoice = new Intent(Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installVoice);
}
}
}
protected void speakButtons(View view){
boolean diditwork;
try {
Speech = (TextView) findViewById(R.id.sayThis);
if (Speak != null && SpeakInit){
Speak.speak("test", TextToSpeech.QUEUE_ADD, null);
} else if (SpeakInit == false){
Toast.makeText(getApplicationContext(), "No Text to speech Installed ", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
diditwork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
}
Your code appears to be very similar to mine, the only difference I can see is
I call:
Speak.speak("test", TextToSpeech.QUEUE_FLUSH, null);
You call:
Speak.speak("test", TextToSpeech.QUEUE_ADD, null);

Categories

Resources