How to select a file from Android Emulator? - android

These are the codes which appeared to have no error but activity stops when I clicked on the Select File button. I wish to upload a file to Amazon S3 but I have to choose a file before uploading. The File I wish to upload is from "Downloads" of the emulator.
Anyone know what's wrong?
package sit.nyp.edu.sg.filepicker;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class FilePicker2Activity extends Activity {
/** Called when the activity is first created. */
TextView textFile, textFileName, textFolder;
TextView textFileName_WithoutExt, textFileName_Ext;
private static final int PICKFILE_RESULT_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPick = (Button)findViewById(R.id.buttonpick);
textFile = (TextView)findViewById(R.id.textfile);
textFolder = (TextView)findViewById(R.id.textfolder);
textFileName = (TextView)findViewById(R.id.textfilename);
textFileName_WithoutExt = (TextView)findViewById(R.id.textfilename_withoutext);
textFileName_Ext = (TextView)findViewById(R.id.textfilename_ext);
buttonPick.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_PICK);
intent.setType("file/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
String FilePath = data.getData().getPath();
String FileName = data.getData().getLastPathSegment();
int lastPos = FilePath.length() - FileName.length();
String Folder = FilePath.substring(0, lastPos);
textFile.setText("Full Path: \n" + FilePath + "\n");
textFolder.setText("Folder: \n" + Folder + "\n");
textFileName.setText("File Name: \n" + FileName + "\n");
filename thisFile = new filename(FileName);
textFileName_WithoutExt.setText("Filename without Ext: " + thisFile.getFilename_Without_Ext());
textFileName_Ext.setText("Ext: " + thisFile.getExt());
}
break;
}
}
private class filename{
String filename_Without_Ext = "";
String ext = "";
filename(String file){
int dotposition= file.lastIndexOf(".");
filename_Without_Ext = file.substring(0,dotposition);
ext = file.substring(dotposition + 1, file.length());
}
String getFilename_Without_Ext(){
return filename_Without_Ext;
}
String getExt(){
return ext;
}
}
}

My guess is that, you dont have any file browser apps which can handle get content intent on the emulator, though if you post the log , can come to conclusion clearly.

Related

Walking a DocumentFile tree

I'm trying to walk an Android DocumentFile tree recursively but I cannot get a list of files to be returned for a subfolder. When I attempt listFiles() on the folder URI, I get the list of root files returned each time.
Why is this not working?
package com.example.usbfoldertest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "USBFolderTest";
private static final int RQS_OPEN_DOCUMENT_TREE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, RQS_OPEN_DOCUMENT_TREE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE){
Uri uriTree = data.getData();
Log.d(TAG, "WalkTree: " + uriTree.toString() );
WalkTree( uriTree );
}
super.onActivityResult(requestCode,resultCode,data);
}
private void WalkTree( Uri uriTop ) {
Log.d( TAG, "LoadFileList: " + uriTop.toString() );
DocumentFile documentFile = DocumentFile.fromTreeUri(this, uriTop);
DocumentFile files[] = documentFile.listFiles();
if( files == null ) {
Log.d( TAG, "files is null in LoadFileList()" );
} else {
for( DocumentFile f : files ) {
if( f.isDirectory() ) {
Log.d( TAG, "FOLDER: " + f.getName());
if( f.getName().toLowerCase().contains("lost.dir") ) {
Log.d( TAG, "IGNORE LOST.DIR");
} else {
// Recurse into the folder..
WalkTree( f.getUri() );
}
} else {
Log.d( TAG, "FILE: " + f.getName());
}
}
}
}
}
It looks as though upgrading the documentfile library fixes the problem. I add this to my build.gradle and it works as expected now:
implementation 'androidx.documentfile:documentfile:1.0.1'

Android studio Can't create a new directory on sdcard?

I'm useing a library called scanlibrary to scan the photo and then pass it to tess-two to perform the OCR process. The problem is that the directory "ScanDemoExample" is not being created thus the tessdata files aren't copied and when I run my activity I get the error :
E/Tesseract(native): Could not initialize Tesseract API with language=eng!
because tesseract can't find the files in the data_path.
The code works when I use an existing directory instead of the following :
public static final String DATA_PATH = Environment
.getExternalStorageDirectory() +"/ScanDemoExample/";
Here's my main activity:
package com.scanner.demo;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.googlecode.tesseract.android.TessBaseAPI;
import com.scanlibrary.ScanActivity;
import com.scanlibrary.ScanConstants;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends ActionBarActivity {
public static final String PACKAGE_NAME = "com.scanner.demo";
public static final String DATA_PATH = Environment
.getExternalStorageDirectory() +"/ScanDemoExample/";
// You should have the trained data file in assets folder
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
public static final String lang = "eng";
private static final String TAG = "MainActivity.java";
// public static final String _path = DATA_PATH + "/ocr.jpg";
private static final int REQUEST_CODE = 99;
private Button scanButton;
private Button cameraButton;
private Button mediaButton;
private ImageView scannedImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.e(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
// lang.traineddata file with the app (in assets folder)
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
// This area needs work and optimization
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
init();
}
private void init() {
scanButton = (Button) findViewById(R.id.scanButton);
scanButton.setOnClickListener(new ScanButtonClickListener());
cameraButton = (Button) findViewById(R.id.cameraButton);
cameraButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_CAMERA));
mediaButton = (Button) findViewById(R.id.mediaButton);
mediaButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_MEDIA));
scannedImageView = (ImageView) findViewById(R.id.scannedImage);
}
private class ScanButtonClickListener implements View.OnClickListener {
private int preference;
public ScanButtonClickListener(int preference) {
this.preference = preference;
}
public ScanButtonClickListener() {
}
#Override
public void onClick(View v) {
startScan(preference);
}
}
protected void startScan(int preference) {
Intent intent = new Intent(this, ScanActivity.class);
intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
getContentResolver().delete(uri, null, null);
scannedImageView.setImageBitmap(bitmap);
///////////////////////////////////////////////////////////
Log.v(TAG, "Before baseApi");
Log.v(TAG, "ExternalStorageDirectory: "+Environment
.getExternalStorageDirectory().toString());
Log.v(TAG, "DATA_PATH: "+DATA_PATH);
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
// You now have the text in recognizedText var, you can do anything with it.
// We will display a stripped out trimmed alpha-numeric version of it (if lang is eng)
// so that garbage doesn't make it to the display.
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if ( lang.equalsIgnoreCase("eng") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap convertByteArrayToBitmap(byte[] data) {
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Edit:
here's my logcat
I/art: Explicit concurrent mark sweep GC freed 2044(210KB) AllocSpace objects, 6(395KB) LOS objects, 40% free, 3MB/6MB, paused 242us total 9.669ms
V/MainActivity.java: Before baseApi
V/MainActivity.java: ExternalStorageDirectory: /storage/emulated/0
V/MainActivity.java: DATA_PATH: /storage/emulated/0/ScanDemoExample/
W/linker: libjpgt.so: unused DT entry: type 0x6ffffffe arg 0x2114
W/linker: libjpgt.so: unused DT entry: type 0x6fffffff arg 0x1
W/linker: libpngt.so: unused DT entry: type 0x6ffffffe arg 0x4a04
W/linker: libpngt.so: unused DT entry: type 0x6fffffff arg 0x2
W/linker: liblept.so: unused DT entry: type 0x6ffffffe arg 0x1dc90
W/linker: liblept.so: unused DT entry: type 0x6fffffff arg 0x2
W/linker: libtess.so: unused DT entry: type 0x6ffffffe arg 0x5d2e8
W/linker: libtess.so: unused DT entry: type 0x6fffffff arg 0x3
E/Tesseract(native): Could not initialize Tesseract API with language=eng!
A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x8 in tid 2863 (om.scanner.demo)
Application terminated.
Have you tried to enable this permission?
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
there is a nice example:
Storage permission error in Marshmallow

Can't find method on extension class:

Hi Im making an android native extension in Gamemaker: Studio and when I run the game and try to use the extension i get this error code in the runner command window:
Can't find method on extension class:folderLoader[double, double]
It does not crash the game or throw any other errors, it just can't find my method in the java file. this is how I have it set up:
edit extension package properties-general tab-
name- DirectoryPicker
android checkbox ticked
inject to manifest-
<activity
android:name="${YYAndroidPackageName}.DirectoryPicker"
android:label="DirectoryPicker" />
inject to gradle (to activate my styles.xml)-
compile 'com.android.support:appcompat-v7:+'
edit extension package properties-android tab-
Class name- DirectoryPicker
Permissions- android.permission.WRITE_EXTERNAL_STORAGE
edit extension file properties box-
name- DirectoryPicker.extension.gmx
init function- set to folderLoader
copys to- ticked android and android yyc boxes only
edit extension functions box-
name- folderLoader
external name- folderLoader
help- folderLoader(double FolderOnly, double ShowHidden)
return type box- selected double
key and value box- argument 0 double argument1 double
the calling code for an object's left mouse pressed event:
folderLoader(1.0, 0.0);
the async event in the same object (set to social event):
var type2 = string(async_load[? "type2"])
var data2 = string(async_load[? "folder"])
if type2 == "folderFound"
{
var text = data2;
}
the java file- named DirectoryPicker.java
package ${YYAndroidPackageName};
import ${YYAndroidPackageName}.R;
import ${YYAndroidPackageName}.RunnerActivity;
import com.yoyogames.runner.RunnerJNILib;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class DirectoryPicker extends ListActivity {
private static final int EVENT_OTHER_SOCIAL = 70;
public static final String ONLY_DIRS = "onlyDirs";
public static final String SHOW_HIDDEN = "showHidden";
public static final String CHOSEN_DIRECTORY = "chosenDir";
public static final int PICK_DIRECTORY = 43522432;
private File dir;
private boolean onlyDirs = true;
private boolean showHidden = false;
public void folderLoader(double yesOrNo,double noOrYes)
{
if(yesOrNo == 0.0) onlyDirs = false;
if(yesOrNo == 1.0) onlyDirs = true;
if(noOrYes == 0.0) showHidden = false;
if(noOrYes == 1.0) showHidden = true;
findFolders();
}
public void findFolders() {
Bundle extras = getIntent().getExtras();
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
dir = new File(Root.getAbsolutePath());
}
if (extras != null) {
showHidden = extras.getBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.getBoolean(ONLY_DIRS, true);
}
setContentView(R.layout.chooser_list);
setTitle(dir.getAbsolutePath());
Button btnChoose = (Button) findViewById(R.id.btnChoose);
String name = dir.getName();
if(name.length() == 0)
name = "No folders found";
btnChoose.setText(name);
btnChoose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
returnDir(dir.getAbsolutePath());
}
});
ListView lv = getListView();
lv.setTextFilterEnabled(true);
if(!dir.canRead()) {
Context context = getApplicationContext();
String msg = "Could not read folders.";
Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
toast.show();
return;
}
final ArrayList<File> files = filter(dir.listFiles(), onlyDirs, showHidden);
String[] names = names(files);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, names));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!files.get(position).isDirectory())
return;
String path = files.get(position).getAbsolutePath();
Intent intent = new Intent((RunnerActivity.CurrentActivity), DirectoryPicker.class);
intent.putExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.putExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
(RunnerActivity.CurrentActivity).startActivityForResult(intent, PICK_DIRECTORY);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_DIRECTORY && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
String path = (String) extras.get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
int dsMapIndex = RunnerJNILib.jCreateDsMap(null, null, null);
RunnerJNILib.DsMapAddString( dsMapIndex, "type2", "folderFound" );
RunnerJNILib.DsMapAddString( dsMapIndex, "folder", path );
RunnerJNILib.CreateAsynEventWithDSMap(dsMapIndex, EVENT_OTHER_SOCIAL);
}
}
private void returnDir(String path) {
Intent result = new Intent();
result.putExtra(CHOSEN_DIRECTORY, path);
setResult(RESULT_OK, result);
finish();
}
public ArrayList<File> filter(File[] file_list, boolean onlyDirs, boolean showHidden) {
ArrayList<File> files = new ArrayList<File>();
for(File file: file_list) {
if(onlyDirs && !file.isDirectory())
continue;
if(!showHidden && file.isHidden())
continue;
files.add(file);
}
Collections.sort(files);
return files;
}
public String[] names(ArrayList<File> files) {
String[] names = new String[files.size()];
int i = 0;
for(File file: files) {
names[i] = file.getName();
i++;
}
return names;
}
}
There are 2 related xml files that i put in the layout folder which i put in the res folder, which is in the AndroidSource folder.
I have also downloaded some extensions to see how they did them, and they all have a file in the android source folder called yymanifest.xml, which is generated by gamemaker, this file never gets created in my extension project, I've tried saving, exporting the extension and re importing it but the file is never there, and it's not a file you can make yourself, gamemaker has to produce it when it makes the extension, but how can I get it to do this???
Any ideas or help would be greatly appreciated
Well everything seems fine you need to mention you folder in menifest file.

How to get the file extension in Android?

I am a newbie.
I have an EditText and a Browse Button to explore Folders and select files only.
From the Browse Button, when a file is clicked it stores the folder path in which that file is in one string and the file name without extension in other string, which I am using to store, either of these two, in the EditText.
I want to make the file name with the exactly file extension (whether one or two dots), but I don't have any idea how to get the file extension also.
All answers will be appreciated.
FileChooser.java
package com.threefriends.filecrypto;
/**
* Created by hp on 01-06-2016.
*/
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir=new File("/sdcard/");
fill(currentDir);
}
private void fill(File f)
{
File[]dirs=f.listFiles();
this.setTitle("Current Dir: "+f.getName());
List<Item>dir=new ArrayList<Item>();
List<Item>fls=new ArrayList<Item>();
try{
for(File ff: dirs)
{
Date lastModDate=new Date(ff.lastModified());
DateFormat formater=DateFormat.getDateTimeInstance();
String date_modify=formater.format(lastModDate);
if(ff.isDirectory()){
File[] fbuf=ff.listFiles();
int buf=0;
if(fbuf != null){
buf=fbuf.length;
}
else
buf=0;
String num_item=String.valueOf(buf);
if(buf == 0)
num_item=num_item+" item";
else
num_item = num_item+" items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(), num_item, date_modify, ff.getAbsolutePath(), "directory_icon"));
}
else
{
fls.add(new Item(ff.getName(), ff.length()+" Byte", date_modify, ff.getAbsolutePath(), "file_icon"));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0, new Item("..", "Parent Directory", "", f.getParent(), "directory_up"));
adapter=new FileArrayAdapter(FileChooser.this, R.layout.file_view, dir);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon") || o.getImage().equalsIgnoreCase("directory_up")){
currentDir=new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o);
}
}
private void onFileClick(Item o)
{
//Toast.makeText(this, "Folder Clicked: "+ currentDir, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("GetPath", currentDir.toString());
intent.putExtra("GetFileName", o.getName());
setResult(RESULT_OK, intent);
finish();
}
}
Part of MainActivity.java
//Defined for file edittext.
EditText editText2;
private static String TAG = MainFragment.class.getSimpleName(); //For File Exploring.
private static final int REQUEST_PATH = 1;
String curFileName;
String filePath;
EditText edittext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_main, container, false);
edittext = (EditText) view.findViewById(R.id.editText); //Done for File Exploring, EditText, Browse Button.
Button b1 = (Button) view.findViewById(R.id.skipButton);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent1 = new Intent(v.getContext(), FileChooser.class);
startActivityForResult(intent1, REQUEST_PATH);
}
}
);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// See which child activity is calling us back.
if (requestCode == REQUEST_PATH)
{
if (resultCode == Activity.RESULT_OK)
{
curFileName = data.getStringExtra("GetFileName");
filePath=data.getStringExtra("GetPath");
edittext.setText(filePath);
}
}
}
lots of ways . here are 2 sample-
String someFilepath = "image.fromyesterday.test.jpg";
String extension = someFilepath.substring(someFilepath.lastIndexOf("."));
So in you case, it should be something like that
String extension = ff.getAbsolutePath().substring(ff.getAbsolutePath().lastIndexOf("."));
In case if you don't want to do it yourself-
use FilenameUtils.getExtension from Apache Commons IO-
String extension = FilenameUtils.getExtension("/path/to/file/mytext.txt");
or in your case -
String extension = FilenameUtils.getExtension(ff.getAbsolutePath());
You could just do it with one line of code using MIME Type Map.
First grab the file:
Uri file = Uri.fromFile(new File(filePath));
Then
String fileExt = MimeTypeMap.getFileExtensionFromUrl(file.toString());
You can put your code in your activity like this:
private String getfileExtension(Uri uri)
{
String extension;
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
extension= mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
return extension;
}
"uri" is the file uri from the result of "Browse button" selected file
Kotlin Approach:
val fileExtention: String = file.extension
Check this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/extension.html
Function:
public String getExt(String filePath){
int strLength = filePath.lastIndexOf(".");
if(strLength > 0)
return filePath.substring(strLength + 1).toLowerCase();
return null;
}
Usage:
String ext = getExt(path);
if(ext != null && ext.equals("txt")){
// do anything
}
PS: If you don't use toLowerCase(), possible the function returns upper and lower cases (dependent the exists file).
In Kotlin
You can read the MimeTypeMap documentation here
This is example if you are using startActivityForResult and you get data from it. Then you define Content Resolver to get mime type from the uri.
val uri: Uri? = it.data?.data
val contentResolver = requireContext().contentResolver
val stringMimeType = contentResolver.getType(uri!!)
Using that code, if you choose pdf file you will get something like
"application/pdf"
After that, using the MimeTypeMap you'll get the extensions. Don't forget that you should add getSingleton() because it's only available in singleton.
val stringFileType = MimeTypeMap.getSingleton().getExtensionFromMimeType(stringMimeType)
I used DocumentFile to get the file name and extension
DocumentFile documentFile = DocumentFile.fromSingleUri(YourActivity.this, fileUri);
String fileName = documentFile.getName();
String extension = fileName.substring(fileName.lastIndexOf("."));
For example, if your file name is 'your_image.jpg' then the extension will be '.jpg'
In Java
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
In Kotlin
fun getFileExt(fileName: String): String? {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)
}
Kotlin
import android.webkit.MimeTypeMap
MimeTypeMap.getFileExtensionFromUrl("my.xlsx") // xlsx
MimeTypeMap.getFileExtensionFromUrl("my.pdf") // pdf
MimeTypeMap.getFileExtensionFromUrl("http://www.google.com/my.docx") // docx
MimeTypeMap.getFileExtensionFromUrl(File.createTempFile("aaa", ".txt").absolutePath) // txt
Getting extension of file in Kotlin:
fun getExtension(fileName: String): String {
return fileName.substring(if (fileName.lastIndexOf(".") > 0) fileName
.lastIndexOf(".") + 1 else return "",fileName.length)
}
getContentResolver().getType(theReceivedUri); // return "media/format"

user select image and detect colour

package com.example.hello;
//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
* This activity displays the gallery image picker.
* It displays the image that was picked.
*
* #author ITCuties
*
*/
public class GalleryActivity extends Activity implements OnClickListener {
// Image loading result to pass to startActivityForResult method.
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
// Find references to the GUI objects
button = (Button)findViewById(R.id.button);
image = (ImageView)findViewById(R.id.image);
// Set button's onClick listener object.
button.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
#Override
public void onClick(View v) {
// Create the Intent for Image Gallery.
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i, LOAD_IMAGE_RESULTS);
}
}
this code select image from gallery ..
package com.example.hello;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
public class ColourPickerActivity extends Activity {
TextView touchedXY, invertedXY, imgSize, colorRGB;
ImageView imgSource1, imgSource2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colourpicker);
// touchedXY = (TextView)findViewById(R.id.xy);
// invertedXY = (TextView)findViewById(R.id.invertedxy);
// imgSize = (TextView)findViewById(R.id.size);
colorRGB = (TextView)findViewById(R.id.colorrgb);
// imgSource1 = (ImageView)findViewById(R.id.source1);
imgSource2 = (ImageView)findViewById(R.id.source2);
//imgSource1.setOnTouchListener(imgSourceOnTouchListener);
imgSource2.setOnTouchListener(imgSourceOnTouchListener);
}
OnTouchListener imgSourceOnTouchListener
= new OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] {eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView)view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int)eventXY[0]);
int y = Integer.valueOf((int)eventXY[1]);
// touchedXY.setText(
// "touched position: "
// + String.valueOf(eventX) + " / "
// + String.valueOf(eventY));
// invertedXY.setText(
// "touched position: "
// + String.valueOf(x) + " / "
// + String.valueOf(y));
Drawable imgDrawable = ((ImageView)view).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
// imgSize.setText(
// "drawable size: "
// + String.valueOf(bitmap.getWidth()) + " / "
// + String.valueOf(bitmap.getHeight()));
//Limit x, y range within bitmap
// if(x < 0){
// x = 0;
// }else if(x > bitmap.getWidth()-1){
// x = bitmap.getWidth()-1;
// }
//
// if(y < 0){
// y = 0;
// }else if(y > bitmap.getHeight()-1){
// y = bitmap.getHeight()-1;
// }
int touchedRGB = bitmap.getPixel(x, y);
colorRGB.setText("touched color: " + "#" + Integer.toHexString(touchedRGB));
colorRGB.setTextColor(touchedRGB);
return true;
}};
}
this code tell colour of pixel on touch of image which is in drawable folder .. how can i integrate these two activities .. i want to select image from gallery and apply colour detector on this image which is selected from gallery
Firs you'll need to call the second class from the fist one inside onActivityResult, adding the imagePath to the Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
(previous code)
Intent intent = new Intent(this, ColourPickerActivity.class);
intent.putExtra("IMAGE_PATH", imagePath);
startActivity(intent)
}
}
Then in your ColourPickerActivity you'll need to extract that path and load it into your ImageView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(previous code)
String imagePath = getIntent().getStringExtra("IMAGE_PATH");
//Load image into the ImageView
imgSource2.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
Hope that helps, cheers!

Categories

Resources