Hello I am trying to read and print all the cell values of an excel file using Apache POI library. This is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
String name = null;
Uri uri = null;
private static final int STORAGE_PERMISSION_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
data.setType("*/*");
data = Intent.createChooser(data, "Choose a file");
launch_activity.launch(data);
}
});
}
ActivityResultLauncher<Intent> launch_activity = registerForActivityResult
(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
Uri uri = null;
if (data != null) {
uri = data.getData();
}
if (uri != null && uri.getScheme().equals("content")) {
try (Cursor returnCursor = getContentResolver().query(uri, null, null, null, null)) {
if (returnCursor != null && returnCursor.moveToFirst()) {
name = returnCursor.getString(returnCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
}
}
}
if(name == null){
if (uri != null) {
name = uri.getPath();
}
int cut = 0;
if (name != null) {
cut = name.lastIndexOf('/');
}
if(cut != 1){
if (name != null) {
name = name.substring(cut + 1);
}
}
}
String[] extension = null;
if (name != null) {
extension = name.split("\\.");
}
if (extension != null && (extension[extension.length - 1].equals("xls") || extension[extension.length - 1].equals("xlsx")))
checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE);
else if (extension != null) {
Toast.makeText(MainActivity.this,extension[extension.length - 1]+" file is not supported",Toast.LENGTH_SHORT).show();
}
}
}
});
public static void readExcelFromStorage(Context context, String fileName) {
InputStream fileInputStream = null;
try {
try {
fileInputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Create instance having reference to .xls/.xlsx file
Workbook workbook = null;
try {
if (fileInputStream != null) {
workbook = new HSSFWorkbook(fileInputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
// Fetch sheet at position 'i' from the workbook
Sheet sheet = null;
if (workbook != null) {
sheet = workbook.getSheetAt(0);
}
// Iterate through each row
if (sheet != null) {
for (Row row : sheet) {
if (row.getRowNum() > 0) {
// Iterate through all the cells in a row (Excluding header row)
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
Toast.makeText(context.getApplicationContext(), String.valueOf(cell.getNumericCellValue()),Toast.LENGTH_SHORT).show();
break;
case Cell.CELL_TYPE_STRING:
Toast.makeText(context.getApplicationContext(), cell.getStringCellValue(),Toast.LENGTH_SHORT).show();
break;
}
}
}
}
}
} finally {
try {
if (null != fileInputStream) {
fileInputStream.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void checkPermission(String permission, int requestCode)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode);
}
else {
Toast.makeText(MainActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Storage Permission Granted", Toast.LENGTH_SHORT).show();
readExcelFromStorage(MainActivity.this, uri);
} else {
Toast.makeText(MainActivity.this, "Storage Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
When I execute my code, I choose my desired excel file (which is inside my internal storage) and then I keep getting this error:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.example.uploadipaselectricdata/files/employee_details.xlsx: open failed: ENOENT (No such file or directory)
How do I fix this error? Please help.
I am testing this app on an actual android device
If you are sure the path to the file is correct but still get such an exception, check whether the app has enough permissions to access that location. After all the OS claims that there is no such file, and you won't be able to fix that inside your application code.
I'm not entirely sure what Excel's workbook wants, specifically FileInputStream or just InputStream, you can try opening using the URI the system returned with getContentResolver().openInputStream(uri) and try passing it instead (this is the data returned via Intent.getData().) That should work on API 30 and above as well.
Related
I am unable to rename and delete the pdf file in my pdf reader app using renameTo() method to rename the file and file.delete() method is also not working to delete the pdf file from the internal storage.
I am attaching all related code from my Android studio that might help to find the poblem:
My RecyclerAdapter code where i am trying to rename and delete the file based on MenuItem Selection:
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
int position = getBindingAdapterPosition();
File file=pdf.get(position);
file.delete();
pdf.remove(position);
notifyItemChanged(position);
notifyItemRangeChanged(position,pdf.size());
return true;
case R.id.menu_rename:
AlertDialog.Builder jumpto = new AlertDialog.Builder(mcontext);
jumpto.setTitle("Rename");
EditText page = new EditText(mcontext);
page.setText(pdfname.getText());
jumpto.setView(page);
jumpto.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File old = new File(pdf.get(getBindingAdapterPosition()).getAbsolutePath());
String name = old.getParentFile().getAbsolutePath();
String newpath = name + page.getText().toString();
File newfile = new File(newpath);
Boolean rename = old.renameTo(newfile);
if (rename) {
ContentResolver resolver = mcontext.getContentResolver();
resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?", new
String[]{
old.getAbsolutePath()});
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(newfile));
mcontext.getApplicationContext().sendBroadcast(intent);
}
}
});
Here is the code of how i am fetching pdf file from storage in my Documents Fragment:
protected List<File> getPdfList() {
Uri collection;
final String[] projection = new String[]{
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
final String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
}else{
collection = MediaStore.Files.getContentUri("external");
}
try (Cursor cursor =getContext().getApplicationContext().getContentResolver().query(collection, projection, selection, selectionArgs, sortOrder)) {
assert cursor != null;
if (cursor.moveToFirst()) {
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
String path=cursor.getString(columnData);
if(new File(path).exists()){
do {
pdf.add(new File((cursor.getString(columnData))));
// Log.d(TAG, "getPdf: " + cursor.getString(columnData));
//you can get your pdf files
} while (cursor.moveToNext());
}
}
}
return pdf;
}
Here is my MainActivity.java code where i am asking for Runtime permission:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
} else {
requestStoragePermission();
}
}
int Request_Code = 12;
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission() {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, Request_Code);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == Request_Code) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
}
} else {
}
You can check that your file is deleted or not for this you can check this may help you here is the code for delete
boolean b = documentList.get(position).getFile().delete();
if (b) {
documentList.remove(position);
notifyItemRemoved(position);
notifyDataSetChanged();
Toast.makeText(context, "File Deleted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "File Deletion Failed!", Toast.LENGTH_SHORT).show();
}
I use system permission.And I announced permission to read and write in sdcard. According to the past, the following writing methods were made. But in Android 8.0+ devices. I always get permission denied at logFile.createNewFile(). But if my file path replace to internal storage is pass.
Looking for the network data, only find a SAF mechanism may provide assistance, but this mechanism is the file manager of the intent machine itself, after returning a URI to perform the function of reading and writing files, the same URI is given to the same funtion Unable to create a new file successfully.(https://github.com/termux/termux-app/issues/812)
I try to use execute function Runtime.getRuntime().exec("push '/storage/emulated/0/eee.txt' '/storage/3630-6236/'"). But it doesn't work,either.
Is there any solutions to write on Android 8.0+ sdcard?Currently trying to use DocumentFile to do.(https://github.com/TeamAmaze/AmazeFileManager/blob/master/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java)
private final static String localFullPath = PATH_SDCARD + File.separator + nowFormat + "_log.txt";
public static void logWriter(String logText) {
try {
File logFile = new File(localFullPath);
if (!logFile.exists()) {
if (logFile.createNewFile()) {
Log.d("mkdir", "Create new file: " + localFullPath);
}
}
Date date = new Date(System.currentTimeMillis());
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
String nowFormat = simpleDateFormat.format(date);
FileWriter fileWriter = new FileWriter(localFullPath, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append("[").append(nowFormat).append("] ").append(logText);
bufferedWriter.newLine();
bufferedWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void CheckPermission() {
// CheckStoragePermission();
String PERMISSION_WRITE_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE";
String PERMISSION_READ_PHONE_STATE = "android.permission.READ_PHONE_STATE";
String PERMISSION_ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION";
String PERMISSION_ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((ContextCompat.checkSelfPermission(this, PERMISSION_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, PERMISSION_ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, PERMISSION_ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, PERMISSION_READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)) {
String[] perms = {PERMISSION_WRITE_STORAGE, PERMISSION_READ_PHONE_STATE, PERMISSION_ACCESS_FINE_LOCATION, PERMISSION_ACCESS_COARSE_LOCATION};
int permsRequestCode = 1;
requestPermissions(perms, permsRequestCode);
}
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
public static String[] getExtSdCardPathsForActivity(Context context) {
List <String> paths = new ArrayList <>();
for (File file : context.getExternalFilesDirs("external")) {
if (file != null) {
int index = file.getAbsolutePath().lastIndexOf("/Android/data");
if (index < 0) {
Log.w(LOG, "Unexpected external file dir: " + file.getAbsolutePath());
} else {
String path = file.getAbsolutePath().substring(0, index);
try {
path = new File(path).getCanonicalPath();
} catch (IOException e) {
// Keep non-canonical path.
}
paths.add(path);
}
}
}
if (paths.isEmpty()) paths.add("/storage/sdcard1");
return paths.toArray(new String[0]);
}
1 Only define permissions in AndroidManifest.xml is not enough, you have to requestPermissions in onCreate #MainActivity.
2 Another way to solve it is to target the sdk version to lower than M, for ex targetSdkVersion 15.
At Android 8+ you have to add also the READ_EXTRERNAL_STORAGE permission
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
Log.e(getClass().getSimpleName(), "missing permission: external storage");
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
builder.setTitle(getResources().getString(R.string.assign_permissions));
builder.setMessage(getResources().getString(R.string.permissions_prompt));
builder.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
requestPermissions(new String[]
{android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE);
}
dialog.dismiss();
}
});
builder.show();
return;
}
}
I am trying to create a text document with user inputted information but nothing is being created... Here is the code I have used for the button click:
runnerTestResultBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (capitanPasswordValidate()& permissionGranted) {
if (capitanPasswordET.getText().toString().equals(capitanPassword)) {
createFile();
} else {
capitanPasswordError.setText("Wrong Password!");
capitanPasswordError.requestFocus();
}
}
}
});
Also, here is the code I am using to create the file:
private void createFile() {
String familiaName = familiaNamesSpinner.getSelectedItem().toString();
String FILE_NAME = familiaName + "_Runner_Test_Results.txt";
String cafeteroTestResultString = runnerTestResult1.getText().toString();
FileOutputStream fos = null;
File file = new File(FILE_NAME);
try {
capitanPasswordError.setText("");
fos = new FileOutputStream(file);
fos.write(cafeteroTestResultString.getBytes());
fos.close();
Toast.makeText(this, "worked", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "did not work", Toast.LENGTH_SHORT).show();
} finally {
if (fos != null) try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Just a side note, I am making it so the user selects a choice from a spinner View in order to track down which file belongs to which person. it is under familiaName and will be part of the name of the file created. any feedback would be amazing, thank you!!
You must check for permissions before reading or writing a file, Please add permission requests to manifests and request permissions for READ, WRITE operations at runtime,
Here i have a simple solution, - (Multiple permission checking)
String[] permissions = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE}; // Here i used multiple permission check
Then call it in Oncreate
if (checkPermissions()) {
// permissions granted.
getCallDetails();
}
Finally, copy the below code
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(), p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permissions granted.
getCallDetails(); // Now you call here what ever you want :)
} else {
String perStr = "";
for (String per : permissions) {
perStr += "\n" + per;
}
// permissions list of don't granted permission
}
return;
}
}
}
I am using code listed here Check Incoming number is stored in Contacts list or not android for checking whether incoming number exist or not in contacts. This code does not give correct result always.
Is there some correction required in this or some other better way to check?
Code:
String res = null;
try {
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String a = uri.getLastPathSegment();
Cursor c = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone._ID + "=?", new String[]{a}, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.getCount() > 0) {
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return res;
Try the below code its simple & working for me.
public class TestActivity extends Activity {
private static final int REQUEST_CONTACT_NUMBER = 8512885487;
/** Pops the "select phone number" window */
public void onBrowseForNumbersButtonClicked(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, REQUEST_CONTACT_NUMBER);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data != null && requestCode == REQUEST_CONTACT_NUMBER) {
Uri uriOfPhoneNumberRecord = data.getData();
String idOfPhoneRecord = uriOfPhoneNumberRecord.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, Phone._ID + "=?", new String[]{idOfPhoneRecord}, null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
String formattedPhoneNumber = cursor.getString( cursor.getColumnIndex(Phone.NUMBER) );
Log.d("TestActivity", String.format("The selected phone number is: %s", formattedPhoneNumber));
}
cursor.close();
}
}
else {
Log.w("TestActivity", "WARNING: Corrupted request response");
}
}
else if (resultCode == RESULT_CANCELED) {
Log.i("TestActivity", "Popup canceled by user.");
}
else {
Log.w("TestActivity", "WARNING: Unknown resultCode");
}
}
}
I have a little camera app that is storing the image to the Pictures folder:
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "preview.jpg");
Later I want to copy this Image and save it with a new Filename. Therefore i used this copy function i found here:
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
The copyFile is called here:
// OLD FILE
File oldFile = new File(imageUri.getPath());
// NEW FILE
File newFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test123.jpg");
// COPY FILE
copyFile(oldFile,newFile);
But it is doing nothing. Also no Exception or something. What am I doing wrong?
EDIT: Full Code
public class ParticipateActivity extends AppCompatActivity {
private static String logtag = "Camera APP";
private static int TAKE_PICTURE = 1;
private Uri imageUri;
private Bitmap cameraImage;
static final String appDirectoryName = "album name";
static final File imageRoot = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageRoot.mkdirs();
verifyStoragePermissions(this);
setContentView(R.layout.activity_participate);
Button cameraButton = (Button) findViewById(R.id.camera_button);
Button saveButton = (Button) findViewById(R.id.save_button);
cameraButton.setOnClickListener(cameraListener);
saveButton.setOnClickListener(saveListener);
}
private View.OnClickListener cameraListener = new View.OnClickListener() {
public void onClick(View v) {
takePhoto(v);
}
};
private View.OnClickListener saveListener = new View.OnClickListener() {
public void onClick(View v) {
try {
savePhoto(v);
} catch (IOException e) {
e.printStackTrace();
Log.e(logtag,"Error copying file!");
}
}
};
private void takePhoto(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(imageRoot, "preview.jpg");
//Log.e(logtag,"test");
imageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PICTURE);
}
private Boolean copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
//Log.e(logtag,sourceFile.getAbsolutePath());
return false;
} else {
//Log.e(logtag,sourceFile.getAbsolutePath());
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
try {
destination.transferFrom(source, 0, source.size());
} catch (Exception e) {
e.printStackTrace();
return false;
}
//source.transferTo(0, source.size(), destination);
Log.e(logtag,"transfer started");
}
if (source != null) {
source.close();
} else {return false;}
if (destination != null) {
destination.close();
return true;
} else {return false;}
}
private void savePhoto(View v) throws IOException {
EditText input_name = (EditText) findViewById(R.id.input_name);
EditText input_mail = (EditText) findViewById(R.id.input_mail);
EditText input_phone = (EditText) findViewById(R.id.input_phone);
String name = input_name.getText().toString();
String mail = input_mail.getText().toString();
String phone = input_phone.getText().toString();
if (name.length() != 0 && mail.length() != 0) {
if (phone.length() == 0) {
phone = "NoPhone";
}
// set fileName
String fileName = name + "-" + mail + "-" + phone;
// Log.e(logtag,fileName);
// OLD FILE
File oldFile = new File(imageUri.getPath());
//Log.e(logtag,"Path: " + imageUri.getPath());
// NEW FILE
File newFile = new File(imageRoot, "test123.jpg");
Log.e(logtag,"path: " + newFile.getAbsolutePath());
// COPY FILE
if(oldFile.exists()) {
Boolean copied = copyFile(oldFile,newFile);
Log.e(logtag,copied.toString());
// log text
if(copied) Toast.makeText(ParticipateActivity.this, "Gespeichert!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ParticipateActivity.this, "Konnte nicht gespeichert werden! Kein Foto?", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(ParticipateActivity.this, "Bitte Name und Email ausfüllen!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.image_camera);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
// Change height of image
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.height = (int) getResources().getDimension(R.dimen.imageView_height);
imageView.setLayoutParams(layoutParams);
// Hide Label and Button
TextView uploadText = (TextView) findViewById(R.id.upload_text);
uploadText.setVisibility(View.GONE);
Button uploadButton = (Button) findViewById(R.id.camera_button);
uploadButton.setVisibility(View.GONE);
// Show Image Name
//Toast.makeText(ParticipateActivity.this,selectedImage.toString(),Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(logtag, e.toString());
}
}
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
* <p>
* If the app does not has permission then the user will be prompted to grant permissions
*
* #param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}