Android - picking file with specific extension (pdf & docx) - java

I used this code for video
public void pickVideo()
{
Intent pickVideoIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickVideoIntent, PICK_VIDEO_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK){
switch (requestCode){
case PICK_VIDEO_ACTIVITY_REQUEST_CODE:
Uri selectedVideo = data.getData();
videoPicked(videoUriToRealPath(selectedVideo));
break;
.
.
.
public String videoUriToRealPath(Uri videoUri){
String[] proj = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(videoUri, proj, null, null, null);
String videoPath = "";
try{
if (cursor != null){
int column_index = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
if (cursor.moveToFirst()){
videoPath = cursor.getString(column_index);
}
}
}finally{
cursor.close();
}
return videoPath;
}
and it's working. I want to set PICK_FILE_ACTIVITY_REQUEST_CODE as one of cases. I've defined it:
public void pickFile()
{
Intent pickFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickFileIntent.setType("*/*");
startActivityForResult(pickFileIntent, PICK_FILE_ACTIVITY_REQUEST_CODE );
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK){
switch (requestCode){
case PICK_FILE_ACTIVITY_REQUEST_CODE:
Uri selectedFile = data.getData();
filePicked(fileUriToRealPath(selectedFile));
.
.
.
public String fileUriToRealPath(Uri fileUri){
String[] proj = {MediaStore.Files.Media.DATA};
Cursor cursor = getContentResolver().query(fileUri, proj, null, null, null);
String filePath = "";
try{
if (cursor != null){
int column_index = cursor.getColumnIndex(MediaStore.Files.Media.DATA);
if (cursor.moveToFirst()){
filePath = cursor.getString(column_index);
}
}
}finally{
cursor.close();
}
return filePath;
}
Actually it's not working. extension .PDF and .DOCX in my files. how to fix it?

I think you need to search on the whole sdcard.
searchDir(Environment.getExternalStorageDirectory());
public void searchDir(File dir){
String docExt = ".doc";
String pdfExt = ".pdf";
File listFile[] = dir.listFiles();
if (listFile != null){
for (int i = 0; i < listFile.length; i++){
if (listFile[i].isDirectory()){
searchDir(listFile[i]);
}else{
if(listFile[i].getName().endsWith(docExt)){
//Do what ever u want
}else if(listFile[i].getName().endsWith(pdfExt)){
//Do what ever u want
}
}
}
}
}

Related

How can I get information about the audio file that was selected by the user? (using SAF and MediaStore)

I can’t understand how to request data about a file (that was selected by the user) from MediaStore.
1) I open file picker like this
public static void launchPicker(Fragment f) {
Intent pickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickerIntent.setType("audio/mpeg");
pickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
pickerIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
f.startActivityForResult(pickerIntent, REQUEST_CODE);
}
2) get the data from the intent
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
//multiselection only
ClipData clipData = data.getClipData();
if (clipData != null) {
List<Uri> results = new ArrayList<>();
for(int i = 0; i < clipData.getItemCount(); i++) {
Uri uri = clipData.getItemAt(i).getUri();
if (uri != null) {
results.add(uri);
}
}
//TODO process result
}
}
}
3) Now I have my list of DocumentUris. What should be my next step?
MediaSoter can convert mediaUri to documentUri via Mediastore.getDocumentUri(), but I couldn't find a way to convert documentUri to mediaUri.
I would like to get these fields from MediaStore: MediaStore.Audio.Media._ID, ALBUM_ID, ARTIST_ID.
I do that this way:
Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(mUri,
documentId);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(mContext,documentUri);
String albumName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
String track = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER);
String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
String year = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR);

get phone number from contactlist

i need get contact number from contacts
i use below code for get contact number in onCreate:
buttonSelectContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
and use below code in onAcivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String number = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
etName.setText(name);
etNumber.setText(number);
}
etName set correctly but etNumber is wrong,The values are 0 or 1 inside it
how to set contact number in etNumber??
here is how I have it in onActivityResult it gets all the phone numbers from a contact this is in a fragment so you will have to take out getActivity() if you are doing it from an activity
Uri contactData = data.getData();
Cursor c = getActivity().getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
textcontact.setText(name + "\n");
customerName = name;
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String num = "";
if (Integer.valueOf(hasNumber) == 1) {
Cursor numbers = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (numbers.moveToNext()) {
num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
textcontact.append(num + "\n");
phoneNumbers.add(num);
}
}
}

How would I also be able to get the phone number from the contact the user picked?

I am able to get the contact name that the user chose but not the phonenumber
In the onclick :
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
PICK_CONTACT is just an int value that equals one its my requestcode
then:
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == PICK_CONTACT) {
if (resultCode == AppCompatActivity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
contactadder.setText(name);
c.close();
}
Here is a little snippet of my work which perhaps might help you to get the right direction. Android database interaction is poorly documented and hard to find the right way/values. Just reply if you need more help to understand. I removed some business relevant data out, so it will not compile this way. Just for easy post!
public static final String[] PROJECTION ={
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.DATA1,
ContactsContract.Data.DATA2,
ContactsContract.Data.DATA3,
ContactsContract.Data.DATA4,
ContactsContract.Data.DATA5,
ContactsContract.Data.DATA6,
ContactsContract.Data.DATA7,
ContactsContract.Data.DATA8,
ContactsContract.Data.DATA9,
ContactsContract.Data.DATA10,
ContactsContract.Data.DATA11,
ContactsContract.Data.DATA12,
ContactsContract.Data.DATA13,
ContactsContract.Data.DATA14,
ContactsContract.Data.DATA15
};
private static final int MIMETYPE_COLUMN=0;
private static final int DATA_COLUMN=1;
private static final int DATATYPE_COLUMN=2;
private static final String SELECTION = ContactsContract.Data.CONTACT_ID + " = ?";
public static ContactWrapper localContact(long contactId){
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,PROJECTION, SELECTION, new String[]{String.valueOf(contactId)}, null);
ContactWrapper wrapper = new ContactWrapper(contact);
if(cursor==null){
return wrapper;
}
while(cursor.moveToNext()){
String mime=cursor.getString(MIMETYPE_COLUMN);
if (mime.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
contact.setU8sDisplayName(cursor.getString(DATA_COLUMN));
} else if (mime.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
putPhoneNumber(contact, cursor);
} else if (mime.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
putEmail(contact, cursor);
} else if (mime.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)) {
putAddress(contact, cursor);
}else if (mime.equals(ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE)) {
contact.setU8sSIPAddress(cursor.getString(DATA_COLUMN));
}else if (mime.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)) {
wrapper.setImageBinaryString(getContactPhotoBase64(contactId));
}
}
cursor.close();
return wrapper;
}
private static void putPhoneNumber(ContactWrapper contact,Cursor data){
switch (data.getInt(DATATYPE_COLUMN)){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contact.setU8sPhoneHome(data.getString(DATA_COLUMN));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
contact.setU8sPhoneMobile(data.getString(DATA_COLUMN));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contact.setU8sPhoneBusiness(data.getString(DATA_COLUMN));
break;
}
}

Assigning ID to specific dynamically generated content

I have a template form that is called and put into view programmatically. In the form I have a button that enables the user to search the phone for images and then saves the image. The image thumbnail shows the image selected and saved. The thumbnail is placed in an ImageView with an XML id of "imgView" next to the button. In order to save the image for each dynamic form generated I am, on form creation/retrieval, selecting the "imgView" generated and then assigning it an integer id which starts from 50001, like so:
case R.id.makeLayoutButton:
v1 = vi.inflate(R.layout.form_template, null);
//add view to the insertPoint
((LinearLayout) insertPoint).addView(v1);
mStartActivityButton = (Button)v1.findViewById(R.id.start_file_picker_button1);
mStartActivityButton.setOnClickListener(this);
thumbnailContainer = (ImageView)v1.findViewById(R.id.imgView);
thumbnailContainer.setId(setImageViewID);
imageViewId = thumbnailContainer.getId();
setImageViewID++;
break;
I'm then, when the user selects an image, iterating from 50000 to 500020, then in the loop searching for an ImageView with an id of i, like so:
ImageView imageView = (ImageView)findViewById(i);
And when found, I'm placing the image in the appropriate imageView, like so:
if(i == imageView.getId()){
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
return;
}
Problem is that its crashing and giving a NULL POINTER EXCEPTION error when trying to retrieve and store the image. It seems like its not finding the ImageView with the appropriate ID assigned. Any clue as to where I'm going wrong?
Code that starts image browsing:
case R.id.start_file_picker_button1:
// Create a new Intent for the file picker activity
Intent intent1 = new Intent(this, FilePickerActivity.class);
Intent i1 = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i1, RESULT_LOAD_IMAGE);
break;
Code for that looks for image and stores it:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
for(int i = 50000;i<=50020; i++){
ImageView imageView = (ImageView)findViewById(i);
if(i == imageView.getId()){
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
return;
}
}
}
}
Solved it. Here is the code if anyone is interested, I realize that this can be optimized and fixed further.
int templateID = 1, inflatedID = 0, setImageViewID = 10, buttonID = 1, imageViewId;
Button b, target, bNext, testTemplate, mStartActivityButton, browseButton;
View v1, insertPoint;
RelativeLayout.LayoutParams templateParams;
LayoutInflater vi;
ImageView thumbnailContainer;
private TextView mFilePathTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.make_question);
Initialize();
}
public void Initialize(){
//button for adding new forms
b = (Button) findViewById(R.id.makeLayoutButton);
b.setOnClickListener(this);
bNext = (Button) findViewById(R.id.bNext);
bNext.setOnClickListener(this);
//get the template form to be duplicated, v1 is the form layout to be duplicated
vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v1 = vi.inflate(R.layout.form_template, null);
//container where forms will be contained in
insertPoint = findViewById(R.id.questionsContainer);
// Set the views
mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
mStartActivityButton = (Button)findViewById(R.id.start_file_picker_button);
mStartActivityButton.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId() == R.id.makeLayoutButton){
v1 = vi.inflate(R.layout.form_template, null);
((LinearLayout) insertPoint).addView(v1);
mStartActivityButton = (Button)v1.findViewById(R.id.start_file_picker_button);
mStartActivityButton.setId(buttonID);
mStartActivityButton.setOnClickListener(this);
thumbnailContainer = (ImageView)v1.findViewById(R.id.imgView);
thumbnailContainer.setId(setImageViewID);
buttonID++;
setImageViewID++;
}
for(int x=1;x<=10;x++){
if(v.getId() == x){
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, v.getId());
}
}
if(v.getId() == R.id.bNext){
Intent b = new Intent(MakeQuestion.this, ChoosingTarget.class);
startActivity(b);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView)findViewById(requestCode + 9);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}

Run the second case with PICK_CONTACT

I have this code to put sound in as a contact but when I insert the second case java recognize me if a duplicate any ideas? I've lightened the code so as not to confuse thanks in advance:
code:
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 1;
// first Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT1);
// second
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT2);
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT1):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) { //ecc...
case (PICK_CONTACT2):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c
.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
here is the problem
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 1;
that's why java sees is as duplicate, here is the correct one
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 2;
You have both PICK_CONTACT1 and PICK_CONTACT2 equal to 1:
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 1;
So you're effectively doing:
switch(reqCode) {
case 1:
//stuff
case 1:
//stuff
}
You'll need to make those different values. Also, make sure you add a break at the end of each case.

Categories