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.
Related
I build an app in which we can delete the duplicate file from external and internal storage. I am able to get all images, videos, songs, and files from phone and external storage. But now I want the size of each image which I get from list of storage.
MainActivity
package com.deitel.duplicatefileremoverapp.VideoContent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.deitel.duplicatefileremoverapp.R;
import java.io.File;
import java.util.ArrayList;
public class VideoMainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private VideoRecyclerViewAdapter videoRecyclerViewAdapter;
File video_storage;
File video_size;
String[] allpath;
String[] allpathsize;
ArrayList<Long> videomodelclassArrayList=new ArrayList<Long>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_main);
recyclerView = findViewById(R.id.video_recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
videoRecyclerViewAdapter = new VideoRecyclerViewAdapter(this);
recyclerView.setAdapter(videoRecyclerViewAdapter);
videoRecyclerViewAdapter.notifyDataSetChanged();
//Load video data here
allpath = VideoStorageUtil.getStorageDirectories(this);
for (String path : allpath) {
video_storage = new File(path);
VideoMethod.load_Directory_files(video_storage);
}
}
}
VideoMethod.class
package com.deitel.duplicatefileremoverapp.VideoContent;
import android.util.Log;
import java.io.File;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class VideoMethod {
public static void load_Directory_files(File file) {
File[] filelist = file.listFiles();
if (filelist != null && filelist.length > 0) {
for (int i = 0; i < filelist.length; i++) {
if (filelist[i].isDirectory()) {
load_Directory_files(filelist[i]);
} else {
String name = filelist[i].getName().toLowerCase();
long size = filelist[i].length()/1024;
Log.d(TAG, "load_Directory_files:"+size);
for (String extension : VideoConstant.videoextention) {
// Check the type of file
if (name.endsWith(extension)) {
VideoConstant.allmedialist.add(filelist[i]);
//when we found file
break;
}
}
}
}
}
}
}
VideoRecyclerAdapter.Class
package com.deitel.duplicatefileremoverapp.VideoContent;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.deitel.duplicatefileremoverapp.R;
import java.io.File;
public class VideoRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
// Constructore
VideoRecyclerViewAdapter(Context context) {
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_file_list, parent, false);
return new FileLayoutHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
((FileLayoutHolder) holder).title.setText(VideoConstant.allmedialist.get(position).getName());
**Line No.39**(FileLayoutHolder) holder).size.setText(VideoConstant.allmedialist.get(position).length);
Uri uri = Uri.fromFile(VideoConstant.allmedialist.get(position));
Glide.with(context).load(uri).thumbnail(0.1f).into(((FileLayoutHolder) holder).thumbnail);
}
#Override
public int getItemCount() {
return VideoConstant.allmedialist.size();
}
class FileLayoutHolder extends RecyclerView.ViewHolder {
ImageView thumbnail;
TextView title;
TextView size;
public FileLayoutHolder(#NonNull View itemView) {
super(itemView);
thumbnail = itemView.findViewById(R.id.video_thumbnail);
title = itemView.findViewById(R.id.video_name);
size = itemView.findViewById(R.id.video_size);
}
}
}
VideoStorageUtil.Class
package com.deitel.duplicatefileremoverapp.VideoContent;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Helper class for getting all storages directories in an Android device
* Solution of this problem
* Consider to use
* <a href="https://developer.android.com/guide/topics/providers/document-provider">StorageAccessFramework(SAF)</>
* if your min SDK version is 19 and your requirement is just for browse and open documents, images, and other files
*
* #author Dmitriy Lozenko, HendraWD
*/
public class VideoStorageUtil {
// Primary physical SD-CARD (not emulated)
private static final String EXTERNAL_STORAGE = System.getenv("EXTERNAL_STORAGE");
// All Secondary SD-CARDs (all exclude primary) separated by File.pathSeparator, i.e: ":", ";"
private static final String SECONDARY_STORAGES = System.getenv("SECONDARY_STORAGE");
// Primary emulated SD-CARD
private static final String EMULATED_STORAGE_TARGET = System.getenv("EMULATED_STORAGE_TARGET");
// PhysicalPaths based on phone model
#SuppressLint("SdCardPath")
#SuppressWarnings("SpellCheckingInspection")
private static final String[] KNOWN_PHYSICAL_PATHS = new String[]{
"/storage/sdcard0",
"/storage/sdcard1", //Motorola Xoom
"/storage/extsdcard", //Samsung SGS3
"/storage/sdcard0/external_sdcard", //User request
"/mnt/extsdcard",
"/mnt/sdcard/external_sd", //Samsung galaxy family
"/mnt/sdcard/ext_sd",
"/mnt/external_sd",
"/mnt/media_rw/sdcard1", //4.4.2 on CyanogenMod S3
"/removable/microsd", //Asus transformer prime
"/mnt/emmc",
"/storage/external_SD", //LG
"/storage/ext_sd", //HTC One Max
"/storage/removable/sdcard1", //Sony Xperia Z1
"/data/sdext",
"/data/sdext2",
"/data/sdext3",
"/data/sdext4",
"/sdcard1", //Sony Xperia Z
"/sdcard2", //HTC One M8s
"/storage/microsd" //ASUS ZenFone 2
};
public static String[] getStorageDirectories(Context context) {
// Final set of paths
final Set<String> availableDirectoriesSet = new HashSet<>();
if (!TextUtils.isEmpty(EMULATED_STORAGE_TARGET)) {
// Device has an emulated storage
availableDirectoriesSet.add(getEmulatedStorageTarget());
} else {
// Device doesn't have an emulated storage
availableDirectoriesSet.addAll(getExternalStorage(context));
}
// Add all secondary storages
Collections.addAll(availableDirectoriesSet, getAllSecondaryStorages());
String[] storagesArray = new String[availableDirectoriesSet.size()];
return availableDirectoriesSet.toArray(storagesArray);
}
private static Set<String> getExternalStorage(Context context) {
final Set<String> availableDirectoriesSet = new HashSet<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Solution of empty raw emulated storage for android version >= marshmallow
// because the EXTERNAL_STORAGE become something like: "/Storage/A5F9-15F4",
// so we can't access it directly
File[] files = getExternalFilesDirs(context, null);
for (File file : files) {
if (file != null) {
String applicationSpecificAbsolutePath = file.getAbsolutePath();
String rootPath = applicationSpecificAbsolutePath.substring(
0,
applicationSpecificAbsolutePath.indexOf("Android/data")
);
availableDirectoriesSet.add(rootPath);
}
}
} else {
if (TextUtils.isEmpty(EXTERNAL_STORAGE)) {
availableDirectoriesSet.addAll(getAvailablePhysicalPaths());
} else {
// Device has physical external storage; use plain paths.
availableDirectoriesSet.add(EXTERNAL_STORAGE);
}
}
return availableDirectoriesSet;
}
private static String getEmulatedStorageTarget() {
String rawStorageId = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// External storage paths should have storageId in the last segment
// i.e: "/storage/emulated/storageId" where storageId is 0, 1, 2, ...
final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
final String[] folders = path.split(File.separator);
final String lastSegment = folders[folders.length - 1];
if (!TextUtils.isEmpty(lastSegment) && TextUtils.isDigitsOnly(lastSegment)) {
rawStorageId = lastSegment;
}
}
if (TextUtils.isEmpty(rawStorageId)) {
return EMULATED_STORAGE_TARGET;
} else {
return EMULATED_STORAGE_TARGET + File.separator + rawStorageId;
}
}
private static String[] getAllSecondaryStorages() {
if (!TextUtils.isEmpty(SECONDARY_STORAGES)) {
// All Secondary SD-CARDs split into array
return SECONDARY_STORAGES.split(File.pathSeparator);
}
return new String[0];
}
private static List<String> getAvailablePhysicalPaths() {
List<String> availablePhysicalPaths = new ArrayList<>();
for (String physicalPath : KNOWN_PHYSICAL_PATHS) {
File file = new File(physicalPath);
if (file.exists()) {
availablePhysicalPaths.add(physicalPath);
}
}
return availablePhysicalPaths;
}
private static File[] getExternalFilesDirs(Context context, String type) {
if (Build.VERSION.SDK_INT >= 19) {
return context.getExternalFilesDirs(type);
} else {
return new File[]{context.getExternalFilesDir(type)};
}
}
}
Error
Process: com.deitel.duplicatefileremoverapp, PID: 24470
android.content.res.Resources$NotFoundException: String resource ID #0x30c9fd
at android.content.res.Resources.getText(Resources.java:336)
at android.widget.TextView.setText(TextView.java:4465)
at com.deitel.duplicatefileremoverapp.VideoContent.VideoRecyclerViewAdapter.onBindViewHolder(VideoRecyclerViewAdapter.java:39)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
I use broadcastreceiver of media folder android.hardware.action.NEW_PICTURE service to rename and move image using this code and it was running:
CameraReciver
package perim.ebrahimi.ir.perim;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
public class CameraReciver extends BroadcastReceiver {
private States states;
private SessionManager session;
private WriteService main;
#Override
public void onReceive(Context context, Intent intent) {
getStates(context);
if(states.getAPP()){
Cursor cursor = context.getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
if(cursor!=null){
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
main = new WriteService();
main.writeFolder(image_path, states, context);
}
cursor.close();
} else abortBroadcast();
}
// OK
private void getStates(Context context){
session = new SessionManager(context.getApplicationContext());
states = new States();
states = session.getSession();
}
}
and here is WriteService:
package perim.ebrahimi.ir.perim;
import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class WriteService extends Activity {
private States states;
private Context context;
private static CalendarJalalian cal;
private static int day ;
private static int month ;
private static int year ;
private static int saat ;
private static int minut ;
private static int secnd ;
private int orientation = -1;
private static final int REQUEST_EXTERNAL_STORAGE = 100;
private static final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS=200;
private boolean mExternalStorageAvailable = false;
private boolean mExternalStorageWriteable = false;
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// //setContentView(R.layout.activity_main);
//
// // A simple check of whether runtime permissions need to be managed
// if (Build.VERSION.SDK_INT >= 23) {
// checkMultiplePermissions();
// }
// }
public void writeFolder(String image_path, States _states, Context _context){
states = _states;
context= _context;
cal = new CalendarJalalian();
long fileSize = new File(image_path).length();
Cursor mediaCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.MediaColumns.SIZE },
MediaStore.MediaColumns.DATE_ADDED + ">=?",
new String[]{String.valueOf(cal.getTimeInMillis()/1000 - 1)},
MediaStore.MediaColumns.DATE_ADDED + " desc");
if (mediaCursor != null && mediaCursor.getCount() !=0 ) {
while(mediaCursor.moveToNext()){
long size = mediaCursor.getLong(1);
if(size == fileSize){
orientation = mediaCursor.getInt(0);
break;
}
}
}
orientation = (orientation<0)?0:orientation;
image_path = changeName(image_path);
if(image_path.length()==0) return;
String image_jadid = copyFile(image_path);
if(states.getMain() && image_jadid.length()>0){
removeMain(image_path);
removeMedia(context, new File(image_path));
}
if(states.getPayam()) Toast.makeText(this, getText(R.string.imageSaved)+": "+states.getKhas(), 500).show();
}
private void checkExternalStorage(){
String[] aaa = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, aaa , REQUEST_EXTERNAL_STORAGE);
if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
} else {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
}
private static void removeMedia(Context context, File f) {
ContentResolver resolver = context.getContentResolver();
resolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[] { f.getAbsolutePath() });
}
// OK
private String changeName(String image_path){
String result = "";
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
File from = new File(image_path);
if(from.exists()){
if(states.getOnimage()){
addTextToImage(image_path, persianDateName);
}
File to = new File(from.getParentFile(),persianDateName);
try
{
boolean b = from.renameTo(to);
if (!b) {
copy(from, to);
from.delete();
}
removeMedia(context, from);
sendToMedia(to, persianDateName);
result = to.getAbsolutePath();
}
catch(Exception ex){
ex.printStackTrace();
}
}
return result;
}
private void addTextToImage(String from, String persianDateName) {
Log.i("info","Draw "+persianDateName+" on image");
try
{
Log.i("info","1");
FileOutputStream fos = new FileOutputStream(from);
if(fos==null) Log.i("info","fos = null");
Log.i("info","2 = "+from);
Bitmap bitmap = BitmapFactory.decodeFile(from);
if(bitmap==null) Log.i("info","bitmap = null");
// Log.i("info","3");
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig==null) Log.i("info","bitmapConfig = null");
// Log.i("info","4");
// if (bitmapConfig == null) {
// bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
// }
Log.i("info","5");
bitmap = bitmap.copy(bitmapConfig, true);
Log.i("info","6");
Canvas canvas = new Canvas(bitmap);
Log.i("info","7");
Resources resources = this.getResources();
float scale = resources.getDisplayMetrics().density;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(61, 61, 61));
paint.setTextSize((int) (14 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
Rect qab = new Rect();
paint.getTextBounds(persianDateName, 0, persianDateName.length(), qab);
int x = (bitmap.getWidth() - qab.width()) / 2;
int y = (bitmap.getHeight() + qab.height()) / 2;
canvas.drawText(persianDateName, x, y, paint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
catch (IOException e)
{
e.printStackTrace();
}
Log.i("info","Text added on image");
}
private void copy(final File f1, final File f2) throws IOException {
if(f2.exists()) f2.delete();
//checkExternalStorage();
checkMultiplePermissions();
if(mExternalStorageAvailable && mExternalStorageWriteable) {
f2.createNewFile();
final RandomAccessFile file1 = new RandomAccessFile(f1, "r");
final RandomAccessFile file2 = new RandomAccessFile(f2, "rw");
file2.getChannel().write(file1.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f1.length()));
file1.close();
file2.close();
}
}
private boolean canRename(final File f1, final File f2) {
final String p1 = f1.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
final String p2 = f2.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
return p1.replaceAll("\\/\\w+", "").equals(p2.replaceAll("\\/\\w+", ""));
}
// OK
private void removeMain(String image_path){
File f = new File(image_path);
if(f.exists()) f.delete();
}
// OK
private File createFileName(){
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
String masirFolder = "";
if(states.getSal()) masirFolder += year;
if(states.getMah()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month);
if(states.getRuz()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day);
if(states.getSaat()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat);
if(states.getMinut()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat)+"_"+((minut<10)?"0"+minut:minut);
if(states.getKhas().length()>0) masirFolder += File.separator+states.getKhas();
File directTime = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), masirFolder);
if (!directTime.mkdir()) makeDir(directTime);
directTime = new File(directTime, persianDateName);
return directTime;
}
// OK
private void makeDir(File direct){
direct.mkdirs();
}
// OK
private String copyFile(String image_path){
String masir = "";
File sourceFile = new File(image_path);
if (!sourceFile.exists()) {return masir;}
File destinationFile = createFileName();
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destinationFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
masir = destinationFile.getName();
sendToMedia(destinationFile, masir);
masir = destinationFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return masir;
}
// OK
private void sendToMedia(File imageFile, String imageTitle){
ContentValues image = new ContentValues();
Date dateTaken = new Date();
File parent = imageFile.getParentFile();
String path = parent.toString().toLowerCase();
String name = parent.getName().toLowerCase();
image.put(MediaStore.Images.Media.TITLE, imageTitle);
image.put(MediaStore.Images.Media.DISPLAY_NAME, String.format(this.getText(R.string.imageDisplayName).toString(),states.getKhas()));
image.put(MediaStore.Images.Media.DESCRIPTION, String.format(this.getText(R.string.imageDescription).toString(),name));
image.put(MediaStore.Images.Media.DATE_ADDED, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_MODIFIED, dateTaken.toString());
image.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
image.put(MediaStore.Images.Media.ORIENTATION, orientation);//getImageOrientation(imageFile.getAbsolutePath()));
image.put(MediaStore.Images.ImageColumns.BUCKET_ID, path.hashCode());
image.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
image.put(MediaStore.Images.Media.SIZE, imageFile.length());
image.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
}
private void checkMultiplePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
List<String> permissionsNeeded = new ArrayList<String>();
List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
permissionsNeeded.add("GPS");
}
if (!addPermission(permissionsList, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
permissionsNeeded.add("Read Storage");
}
if (permissionsList.size() > 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
try {
if (Build.VERSION.SDK_INT >= 23)
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
} catch(Exception ex){
ex.printStackTrace();
}
return true;
}
}
But class addPermission raise error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
android.content.Context.checkSelfPermission(java.lang.String)' on a
null object reference
I think the way I call activity is not correct, but I have no idea how to do it, please help.
Edit:
I have found this difference in returned path:
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
The changed part is obvious:
old but correct path: /storage/emulated/0/DCIM/Camera/IMG_20161215_173334.jpg
new but incorrect path: /storage/3466-033/DCIM/Camera/IMG_20161215_173334.jpg
I think since new devices permit user to select where to save Images, then returning address is changed accordingly.
How to get correct address out of cursor?
You can't do that with a broadcast receiver. You can check if you have a permission via ContextCompat.checkSelfPermission, but in order to request the permission, you need to call ActivityCompat.requestPermissions. It needs an activity, and the result will also arrive to that activity.
Given that, the best solution for you is to implement some activity which will explain the user what is going on and request the permission. If the broadcast receiver detects that it doesn't have the necessary permission, it would launch this activity. When the permission is granted, the normal operation would be resumed.
I have to say that as a user it would be very weird to me if a dialog with a permission request suddenly popped up out of the blue, so I think it's for the best that you need to have an activity to request permissions.
Judging by your path, however, it is definitely somewhere on the SD card. This means that the SD card write restrictions apply. That means that requesting permissions for writing won't help. Take a look at this question: How to avoid the “EACCES permission denied” on SD card?
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"
I am trying to write data from EditText fields to a text file. I have verified that the data is being captured for output in an EditText field that I populate after clicking the Add button. The program runs successfully in the Emulator, but no output file is created. I have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" to the Android Manifest xml file. LogCat & Console do not show any errors. I have tried several different methods after reseaching examples here, but no luck. Can anyone point out my issue? Thanks in advance for your help.
package john.BRprogram;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
//import android.graphics.Color;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class BRprogramActivity extends Activity implements OnItemSelectedListener {
private static final String TAG = null;
//
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
Button addButton;
Button editButton;
Button sendButton;
//
Spinner array_spinner;
//
// activate soft Keyboard
this.getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
//
// .csv comma separated values file
//
try {
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.brdata));
//
List<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
String data = (scanner.next()); //read data record
String [] values = data.split(","); //parse data to fields
// String [] values = data.split(",(?=([^\"]\"[^\"]\")[^\"]$)");
if(values.length != 3)
Log.v("Example", "Malformed row: " + data);
else
list.add(values[0] + " " + values[1] + " $" + values[2]);
}
//
array_spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
array_spinner.setAdapter(adapter);
array_spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
//
scanner.close();
//
} catch (Exception e) {
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
//
addButton = (Button) findViewById(R.id.addbutton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
// get customer number,itemnumber,quantity,price
//
String writeCustomer = ((EditText) findViewById(R.id.editText1)).getText().toString().trim();
// itemNumber from list selection
String writeQuantity = ((EditText) findViewById(R.id.editText2)).getText().toString().trim();
String writePrice = ((EditText) findViewById(R.id.editText3)).getText().toString().trim();
//
String newRecord = writeCustomer + "," + writeQuantity + "," + writePrice;
EditText myString = (EditText)findViewById(R.id.editText4);
myString.setText(newRecord);
//
// write seq to output file
//
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("broutput.txt",0));
out.write(newRecord);
out.close();
}catch (Exception e){
Log.v("test", "record written");
}
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "ADD button clicked");
}
});
//
editButton = (Button) findViewById(R.id.editbutton);
editButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Log.v("test", "EDIT button clicked");
}
});
//
sendButton = (Button) findViewById(R.id.sendbutton);
sendButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "SEND button clicked");
}
});
}
// *** http://www.youtube.com/watch?v=Pfasw0bbe_4 ***
//
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//
String selection = parent.getItemAtPosition(position).toString();
String [] priceField = selection.split("\\$"); //parse price field
String [] item = selection.split("_"); //parse item number
String itemNumber = item[0];
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText(priceField[1]);
}
//
public void onNothingSelected(AdapterView<?> arg0) {
//nothing here
}
}
Looks like you need to create and/or specify the directory where you wish to save the file. I didn't see that anywhere in your code. It might look something like this:
if (Environment.getExternalStorageState() == null) {
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}
When you save data from your app, you have to remember that it is running on the Android, and not your computer, so all data is going to be written to your Android, not your comp. You have to pull the data after it is written to view it. Make sure you that you created a local directory on your device and make sure you check for an SD card. The code I listed will show you how to do everything you need.
Hope this helps!
I've actually experienced a problem like this; everything seemed fine, but my code wasn't working. My problem was the characters in the file name I was writing. For example, I tried writing the file name my_file - date 07/11/2012. This caused problems because it treated each / as a cue to begin a new directory! For this reason, I discovered I could not have any / (or :, for some reason) in my file names. Would this be your problem?
If this is your problem, then you could do what I did: perform a newRecord.replace('/', '-'); to replace all / in your file name with a - (if you are fine with having -'s instead).
On a side note, why are you logging "record written" in your the catch of your try/catch statement? If it catches a problem, doesn't that mean it wasn't written?
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.