For the past couple of days, I've been trying to figure out what I'm doing wrong. Whenever the user uploads a file (non-image), and I try to convert the URI object into a file and then into a byte array, I get this error:
java.io.FileNotFoundException: /document/2301 (No such file or directory)
I had obviously uploaded something because it was showing me some sort of path. Here is my code:
MAIN ACTIVITY-
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaFormat;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
getFile();
}
}
public void getFile() {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getFile();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedFile = data.getData();
Log.i("Path", selectedFile.getPath());
File file = new File(selectedFile.getPath());
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i]);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
}
}
}
Any sort of help is appreciated!
The file does not exist on Internal Storage. Use below code to solve the issue.
public static String getPath(Context context, Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else
if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
Use the below code to browse the file in any format.
public void browseClick() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
//intent.putExtra("browseCoa", itemToBrowse);
//Intent chooser = Intent.createChooser(intent, "Select a File to Upload");
try {
//startActivityForResult(chooser, FILE_SELECT_CODE);
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"),FILE_SELECT_CODE);
} catch (Exception ex) {
System.out.println("browseClick :"+ex);//android.content.ActivityNotFoundException ex
}
}
Then get that file path in the onActivityResult like below.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_SELECT_CODE) {
if (resultCode == RESULT_OK) {
try {
Uri uri = data.getData();
if (filesize >= FILE_SIZE_LIMIT) {
Toast.makeText(this,"The selected file is too large. Selet a new file with size less than 2mb",Toast.LENGTH_LONG).show();
} else {
String mimeType = getContentResolver().getType(uri);
if (mimeType == null) {
String path = getPath(this, uri);
if (path == null) {
filename = FilenameUtils.getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Uri returnUri = data.getData();
Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
String size = Long.toString(returnCursor.getLong(sizeIndex));
}
File fileSave = getExternalFilesDir(null);
String sourcePath = getExternalFilesDir(null).toString();
try {
copyFileStream(new File(sourcePath + "/" + filename), uri,this);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void copyFileStream(File dest, Uri uri, Context context)
throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = context.getContentResolver().openInputStream(uri);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
os.close();
}
}
After this you can open this file from your application external storage where you saved the file with appropriate action.
Courtesy: https://stackoverflow.com/a/36129285/6050536
private String fileToBase64Conversion(Uri file) {
InputStream inputStream = null;//You can get an inputStream using any IO API
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
inputStream = context.getContentResolver().openInputStream(file);
byte[] buffer = new byte[8192];
int bytesRead;
Base64OutputStream outputBase64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputBase64.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
outputBase64.close();
} catch (Exception ex) {
}
return outputBase64.toString();
}
Related
I'm using some code from a helpful stack exchange user to browse and select files on my Android. However, when selecting a file from a subfolder in Download, I get an error. Is there a way to extract the path from the Uri in the form: /storage/emulated/0/Download/subfolder/filename.gpx?
In the "Downloads Provider" section below, why is the /Download/ part hard coded?
When I select the file Download/subfolder/filename.gpx, getPath returns Download/filename.gpx resulting in an IOException, no file found.
Here's the line I have an issue with:
String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
private static Uri contentUri = null;
Context context;
public FileUtils( Context context) {
this.context=context;
}
#SuppressLint("NewApi")
public static String getPath( final Uri uri) {
// check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (isKitKat ) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
String fullPath = getPathFromExtSD(split);
if (fullPath != "") {
return fullPath;
} else {
return null;
}
}
// DownloadsProvider
if (isDownloadsDocument(uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String id;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String fileName = cursor.getString(0);
String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
if (!TextUtils.isEmpty(path)) {
return path;
}
}
}
finally {
if (cursor != null)
cursor.close();
}
id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
try {
final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
//In Android 8 and Android P the id is not a number
return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
}
}
}
}
else {
final String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
}
catch (NumberFormatException e) {
e.printStackTrace();
}
if (contentUri != null) {
return getDataColumn(context, contentUri, null, null);
}
}
}
// MediaProvider
if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri);
}
if(isWhatsAppFile(uri)){
return getFilePathForWhatsApp(uri);
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri);
}
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
{
// return getFilePathFromURI(context,uri);
return copyFileToInternalStorage(uri,"userfiles");
// return getRealPathFromURI(context,uri);
}
else
{
return getDataColumn(context, uri, null, null);
}
}
if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
}
else {
if(isWhatsAppFile(uri)){
return getFilePathForWhatsApp(uri);
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
private boolean fileExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
private String getPathFromExtSD(String[] pathData) {
final String type = pathData[0];
final String relativePath = "/" + pathData[1];
String fullPath = "";
// on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
// something like "71F8-2C0A", some kind of unique id per storage
// don't know any API that can get the root path of that storage based on its id.
//
// so no "primary" type, but let the check here for other devices
if ("primary".equalsIgnoreCase(type)) {
fullPath = Environment.getExternalStorageDirectory() + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
}
// Environment.isExternalStorageRemovable() is `true` for external and internal storage
// so we cannot relay on it.
//
// instead, for each possible path, check if file exists
// we'll start with secondary storage as this could be our (physically) removable sd card
fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
return fullPath;
}
private String getDriveFilePath(Uri uri) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getCacheDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
/***
* Used for Android Q+
* #param uri
* #param newDirName if you want to create a directory, you can set this variable
* #return
*/
private String copyFileToInternalStorage(Uri uri,String newDirName) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, new String[]{
OpenableColumns.DISPLAY_NAME,OpenableColumns.SIZE
}, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File output;
if(!newDirName.equals("")) {
File dir = new File(context.getFilesDir() + "/" + newDirName);
if (!dir.exists()) {
dir.mkdir();
}
output = new File(context.getFilesDir() + "/" + newDirName + "/" + name);
}
else{
output = new File(context.getFilesDir() + "/" + name);
}
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(output);
int read = 0;
int bufferSize = 1024;
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
}
catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return output.getPath();
}
private String getFilePathForWhatsApp(Uri uri){
return copyFileToInternalStorage(uri,"whatsapp");
}
private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
}
finally {
if (cursor != null)
cursor.close();
}
return null;
}
private boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
public boolean isWhatsAppFile(Uri uri){
return "com.whatsapp.provider.media".equals(uri.getAuthority());
}
private boolean isGoogleDriveUri(Uri uri) {
return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
}
}
i try many way but intent not return path that i want , how can i get absolute path ?
this is which i retrieved
/document/image:29163
code for intent
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 0);
}
});
when activityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
}
}
Try this code for getting absolute path:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
Object objImg = data.getExtras().get("path");
Log.e("Selected", "" + objImg.toString());
/*--getting image uri from object--*/
Uri selectedImage = Uri.parse(String.valueOf(objImg));
Log.e("Selected Image", "" + selectedImage);
/*--create file object using uri--*/
File myFile = new File(selectedImage.getPath());
String path = myFile.getAbsolutePath();
Log.e("AbsolutePath---", ""+path);
}
}
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
launcher.launch(intent);
}
});
ActivityResultLauncher<Intent> launcher = 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= data.getData();
File file = new File(FileMyutils.getPath(getContext(),uri));
}
}
});
public class FileMyutils {
private static final String TAG = "FileUtils";
#WorkerThread
#Nullable
public static String getReadablePathFromUri(Context context, Uri uri) {
String path = null;
if ("file".equalsIgnoreCase(uri.getScheme())) {
path = uri.getPath();
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
path = getPath(context, uri);
}
if (TextUtils.isEmpty(path)) {
return path;
}
Log.d(TAG, "get path from uri: " + path);
if (!isReadablePath(path)) {
int index = path.lastIndexOf("/");
String name = path.substring(index + 1);
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + name;
if (copyFile(context, uri, dstPath)) {
path = dstPath;
Log.d(TAG, "copy file success: " + path);
} else {
Log.d(TAG, "copy file fail!");
}
}
return path;
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
Log.d("External Storage", docId);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + getFileName(context,uri);
if (copyFile(context, uri, dstPath)) {
Log.d(TAG, "copy file success: " + dstPath);
return dstPath;
} else {
Log.d(TAG, "copy file fail!");
}
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getFileName(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri,null,null,null,null);
int nameindex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst();
return cursor.getString(nameindex);
}
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isReadablePath(#Nullable String path) {
if (TextUtils.isEmpty(path)) {
return false;
}
boolean isLocalPath;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (!TextUtils.isEmpty(path)) {
File localFile = new File(path);
isLocalPath = localFile.exists() && localFile.canRead();
} else {
isLocalPath = false;
}
} else {
isLocalPath = path.startsWith(File.separator);
}
return isLocalPath;
}
private static boolean copyFile(Context context, Uri uri, String dstPath) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(uri);
outputStream = new FileOutputStream(dstPath);
byte[] buff = new byte[100 * 1024];
int len;
while ((len = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
}
I am creating an Android application that needs to store some multimedia files in the internal storage. The user can choose that multimedia files from the picker. Those files must be available even when the user removes them, so they are copied to the internal storage.
Here's my code:
final Bitmap bitm = MediaStore.Images.Media.getBitmap( this.getContentResolver(), uri );
final int bitmapRawLength = bitm.getAllocationByteCount();
final ByteBuffer byteBuffer = ByteBuffer.allocate( bitmapRawLength );
bitm.copyPixelsToBuffer( byteBuffer );
data = byteBuffer.array();
final ByteArrayInputStream in = new ByteArrayInputStream( data );
db.store( in );
So, the bytes composing the image are copied into an average file inside the internal store through an InputStream. Apparently it works, since the file has contents.
Later the image is loaded in an ImageView:
private void loadImage(File imgFile)
{
if ( imgFile.exists() ) {
final Bitmap bitmap = BitmapFactory.decodeFile( mediaFile.getPath() );
this.ivPictureBox.setImageBitmap( bitmap );
} else {
this.abortDueToMissingFile( imgFile );
}
return;
}
Unfortunately, this does not work. When it is time to load that image, the ImageView goes blank, nothing is shown.
Actually, in the log appears the following message:
D/skia: --- Failed to create image decoder with message 'unimplemented'
If I use the file explorer in Android Studio and export the image to my computer, then GwenView fails with the message "Failed to load metadata".
How can I correctly store the image, with the complete information, or show it correctly, whatever is easier or feasible?
I have develop and test some code in this case. I hope it helps you.
Defining request codes:
private static final int REQUEST_CODE_KITKAT_PICK_PHOTO = 11;
private static final int REQUEST_CODE_PICK_PHOTO = 12;
To call image picker:
if (Build.VERSION.SDK_INT < 19) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a photo"), REQUEST_CODE_PICK_PHOTO);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_KITKAT_PICK_PHOTO);
}
To receive the picked image and copy it, in your Activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE_PICK_PHOTO) {
if (data == null || data.getData() == null) {
Toast.makeText(getApplicationContext(), "Error in retrieving photo!", Toast.LENGTH_SHORT).show();
return;
}
Uri uri = data.getData();
String destPath = getFilesDir() + File.separator + "image.jpg"; // an example path
File imageFile = null;
try {
imageFile = copy(uri, destPath);
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ivPictureBox.setImageBitmap(bitmap);
}
} else if (requestCode == REQUEST_CODE_KITKAT_PICK_PHOTO) {
if (data == null || data.getData() == null) {
Toast.makeText(getApplicationContext(), "Error in retrieving photo!", Toast.LENGTH_SHORT).show();
return;
}
Uri originalUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
}
String destPath = getFilesDir() + File.separator + "image.jpg"; // an example path
File imageFile = null;
try {
imageFile = copy(originalUri, destPath);
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ivPictureBox.setImageBitmap(bitmap);
}
}
}
}
// To copy the file:
private File copy(Uri inputUri, String destPath) throws IOException {
File inputFile = new File(ImageUtils.getPathFromUri(getApplicationContext(), inputUri));
File outputFile = new File(destPath);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileInputStream inStream = new FileInputStream(inputFile);
FileOutputStream outStream = new FileOutputStream(outputFile);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
return outputFile;
}
ImageUtils.java:
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
public class ImageUtils {
#SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
Here is the result:
Silly of me!
It is as simple as:
final InputStream in = this.getContentResolver().openInputStream( uri );
...and copy it whichever you want.
This works for URI's with both SCHEME_CONTENT and SCHEME_FILE schemes.
In my app, I am using webview to render a webpage from which I need to upload multiple files to the server. OnShowFileChooser() (for lollipop and upper versions) is working fine but onOpenFileChooser() (for other lower android versions). OnshowFileChooser() method not working if I pass an Uri array(Uri[]) to its onValueCallback(). It throws the classCastException. Below is my code which i have used for performing the required opertation. I need a solution to upload multiple file using webview which will work for all android versions.
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri[]> uploadMsg) {
openFileChooser(uploadMsg, "");
}
}
This is the onActivityResult code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
if (data.getData() != null) {
String dataString = data.getDataString();
if (dataString != null) {
// results = new Uri[]{Uri.parse(dataString)};
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(Uri.parse(dataString.replace("%3A", ":")));
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
results = new Uri[]{Uri.parse("file:" + filePath)};
}
cursor.close();
}
} else {
if (data.getClipData() != null) {
ClipData clipData = data.getClipData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item image = clipData.getItemAt(i);
Uri uri = image.getUri();
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String contentUri;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.DATA;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.DATA;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.DATA;
}
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
results[i] = Uri.parse("file:" + filePath);
}
}
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result[] = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
if (data.getData() != null)
result[0] = data.getData();
else {
if (data.getClipData() != null) {
result = new Uri[data.getClipData().getItemCount()];
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
result[i] = data.getClipData().getItemAt(i).getUri();
}
} else {
result = null;
}
}
// retrieve from the private variable if the intent is null
//result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
this is the Error report
Can someone help me to see what is wrong with these two functions
Method 1 returns empty String value without any error and Method 2 returns a null pointer exceptions
I have tried all the similar examples I could find here but still have issues for days. Thanks in advance.
//Funtion1 Converting File to Base64.encode String type but returns empty string
public String getStringFile(File f) {
InputStream inputStream = null;
String encodedFile= "", lastVal;
try {
String uriString = filePath2.toString();
f = new File(uriString).getAbsoluteFile();
inputStream = new FileInputStream(f);
byte[] buffer = new byte[10240];//specify the size to allow
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
encodedFile = output64.toString();
}
catch (FileNotFoundException e1 ) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Log.i("Base64 String", "=" + encodedFile);
Log.v("Base64 String", "=" + encodedFile);
Log.e("Base64 String", "=" + encodedFile);
lastVal = encodedFile;
return lastVal;
}
// Funtion 2 also Converting File to Base64 encode String but returns NullPointerException
public String getStringFile(File f) throws FileNotFoundEception, IOException {
InputStream inputStream = null;
String encodedFile= "", lastVal;
f = new File(f.getAbsoluthPath());
inputStream = new FileInputStream(f);
byte[] buffer = new byte[10240];//specify the size to allow
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
encodedFile = output.toString();
return = encodedFile;
}
This is the complete code below. Every other thing is working except for this task. Thanks
package com.aquacareer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
public class Employee_Reg extends Activity implements OnItemSelectedListener, OnClickListener {
byte[] bytes;
RelativeLayout rl;
String strCat1, strCat2, imagePath, docPath, result, displayName, encodedFile;
Spinner spCat1, spCat2;
Button b1, b2, b3;
EditText ed1, ed2, ed3, ed4, ed5, ed6, ed7, ed8, ed9, ed10, ed11;
String fullname, password, comfPassword, gender, email, contAddr, phoneNo, mobileNo, currLoc, currSal, currInd,
quali, carProfile, path, path2;
Intent intent;
TextView txt1, txt2, txt3, txt4, txt5, txt6, txt7;
int counter = 3;
Uri filePath, filePath2;
String URL = "http://www.aquabytestechnologies.com/aquacareer/android/employeeregister.php";
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
public static final String KEY_IMAGE = "image";
public static final String KEY_FILE = "file";
// Image request code
private int PICK_IMAGE_REQUEST = 2;
private int PICK_FILE_REQUEST = 1;
// storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
InputStream inputStream = null ;
ByteArrayOutputStream output = null;
Base64OutputStream output64 = null;
// Uri to store the image uri
// private Uri filePath;
private File fileDoc;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_reg);
// getActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF' >
// AquaCareer </font>"));
getActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF' ><h1>AquaCareer</h1></font>"));
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
ed1 = (EditText) findViewById(R.id.txt1);
ed2 = (EditText) findViewById(R.id.txt2);
ed3 = (EditText) findViewById(R.id.txt3);
ed4 = (EditText) findViewById(R.id.txt4);
ed5 = (EditText) findViewById(R.id.txt5);
ed6 = (EditText) findViewById(R.id.txt6);
ed7 = (EditText) findViewById(R.id.txt7);
ed8 = (EditText) findViewById(R.id.txt8);
ed9 = (EditText) findViewById(R.id.txt9);
ed10 = (EditText) findViewById(R.id.txt10);
ed11 = (EditText) findViewById(R.id.txt11);
txt1 = (TextView) findViewById(R.id.textView1);
txt2 = (TextView) findViewById(R.id.textView2);
txt3 = (TextView) findViewById(R.id.textView3);
txt4 = (TextView) findViewById(R.id.textView4);
txt5 = (TextView) findViewById(R.id.textView5);
txt6 = (TextView) findViewById(R.id.textView6);
txt7 = (TextView) findViewById(R.id.textView7);
txt2.setVisibility(View.GONE);
txt3.setVisibility(View.GONE);
txt5.setVisibility(View.GONE);
txt7.setVisibility(View.GONE);
spCat1 = (Spinner) findViewById(R.id.spinner1);
spCat2 = (Spinner) findViewById(R.id.spinner2);
List<String> listGender = new ArrayList<String>();
listGender.add("Select Gender");
listGender.add("Male");
listGender.add("Female");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Employee_Reg.this, R.layout.spinner_item,
listGender);
dataAdapter.setDropDownViewResource(R.layout.spinner_item2);
spCat1.setAdapter(dataAdapter);
List<String> listQual = new ArrayList<String>();
listQual.add("Select Highest Qualification");
listQual.add("PHD");
listQual.add("Masters");
listQual.add("First Degree");
listQual.add("HND");
listQual.add("OND");
listQual.add("Diploma");
listQual.add("Secondary Cert");
listQual.add("Primary Cert");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(Employee_Reg.this, R.layout.spinner_item,
listQual);
dataAdapter2.setDropDownViewResource(R.layout.spinner_item2);
spCat2.setAdapter(dataAdapter2);
spCat1.setOnItemSelectedListener(this);
spCat2.setOnItemSelectedListener(this);
this.b1.setOnClickListener(this);
this.b2.setOnClickListener(this);
this.b3.setOnClickListener(this);
ed3.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String strPass1 = ed2.getText().toString();
String strPass2 = ed3.getText().toString();
if (strPass1.equals(strPass2)) {
txt2.setVisibility(View.VISIBLE);
txt2.setText("Passwords Match");
} else {
txt2.setVisibility(View.VISIBLE);
txt2.setText("Passwords don't Match");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
showFileChooser();
}
else if (v.getId() == R.id.button2) {
fullname = ed1.getText().toString().trim();
password = ed2.getText().toString().trim();
comfPassword = ed3.getText().toString().trim();
gender = spCat1.getSelectedItem().toString().trim();
email = ed4.getText().toString().trim();
contAddr = ed5.getText().toString().trim();
phoneNo = ed6.getText().toString().trim();
mobileNo = ed7.getText().toString().trim();
currLoc = ed8.getText().toString().trim();
currSal = ed9.getText().toString().trim();
currInd = ed10.getText().toString().trim();
quali = spCat2.getSelectedItem().toString().trim();
carProfile = ed11.getText().toString().trim();
path = txt5.getText().toString().trim();
path2 = txt7.getText().toString().trim();
// Check if username, password is filled
if (fullname.trim().length() > 0 && password.trim().length() > 0 && comfPassword.trim().length() > 0
&& gender.trim().length() > 0 && email.trim().length() > 0 && contAddr.trim().length() > 0
&& phoneNo.trim().length() > 0 && mobileNo.trim().length() > 0 && currLoc.trim().length() > 0
&& currSal.trim().length() > 0 && currInd.trim().length() > 0 && carProfile.trim().length() > 0
&& path.trim().length() > 0) {
// For testing puspose username, password is checked with sample
// data3E 54
String strPass1 = ed2.getText().toString();
String strPass2 = ed3.getText().toString();
if (strPass1.equals(strPass2)) {
if (gender.equals("Male") || gender.equals("Female")) {
if (quali.equals("Select Highest Qualification")) {
alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Select Qualification",
false);
} else {
registerUser();
}
} else {
alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Select Genger", false);
}
} else {
alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Passwords don't Match", false);
}
} else {
// user didn't entered username or password
// Show alert asking him to enter the details
alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Please fill all details", false);
}
} else if (v.getId() == R.id.button3) {
showFileChooser2();
}
}
private void registerUser() {
register();
}
// method to show file chooser for image
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
try {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Employee_Reg.this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
}
// method to show file chooser for resume
private void showFileChooser2() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select Document"), PICK_FILE_REQUEST);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Employee_Reg.this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
}
// handling the image chooser activity result
#SuppressLint("InlinedApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// imageView.setImageBitmap(bitmap);
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
STORAGE_PERMISSION_CODE);
} else {
imagePath = getPath(filePath);
txt5.setVisibility(View.VISIBLE);
txt5.setText(imagePath);
Log.i("Base64 imagePath", "=" + imagePath);
alert.showAlertDialog(Employee_Reg.this, "Image Loaded..", "Photo Successfully Selected", true);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath2 = data.getData();
try {
// docPath = getPath2(filePath2);
String uriString = filePath2.toString();
fileDoc = new File(uriString);
docPath = fileDoc.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = Employee_Reg.this.getContentResolver().query(filePath2, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = fileDoc.getName();
}
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
STORAGE_PERMISSION_CODE);
} else {
txt7.setVisibility(View.VISIBLE);
txt7.setText(displayName);
//Log.i("Base64 URIString", "=" + uriString);
//Log.i("Base64 docPath", "=" + docPath);
alert.showAlertDialog(Employee_Reg.this, "Resume Loaded..", "Resume Successfully Selected", true);
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
// Converting Bitmap image to Base64.encode String type
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
// Converting File to Base64.encode String type
public String getStringFile(File f) {
InputStream inputStream = null;
String encodedFile= "", lastVal;
try {
String uriString = filePath2.toString();
f = new File(uriString).getAbsoluteFile();
inputStream = new FileInputStream(f);
byte[] buffer = new byte[10240];//specify the size to allow
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
encodedFile = output64.toString();
}
catch (FileNotFoundException e1 ) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Log.i("Base64 String", "=" + encodedFile);
Log.v("Base64 String", "=" + encodedFile);
Log.e("Base64 String", "=" + encodedFile);
lastVal = encodedFile;
return lastVal;
}
// method to get the file Name from uri
public String getPath(Uri uri) {
String uriString = uri.toString();
File myFile = new File(uriString);
#SuppressWarnings("unused")
String mPath = myFile.getAbsolutePath();
String dispName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = Employee_Reg.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
dispName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
dispName = myFile.getName();
}
return dispName;
}
// Requesting permission
#SuppressLint("InlinedApi")
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
// If the user has denied the permission previously your code will
// come to this block
// Here you can explain why you need this permission
// Explain here why you need this permission
}
// And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
STORAGE_PERMISSION_CODE);
}
// This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
// Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
// If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
// Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.signup, 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();
if (id == R.id.abt) {
Toast.makeText(this, "We are in About US", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.conUs) {
Toast.makeText(this, "We are in Contact Us", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private void register() {
class RegisterUser extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
final String fullname = ed1.getText().toString().trim();
final String password = ed2.getText().toString().trim();
// final String comfPassword = ed3.getText().toString().trim();
final String gender = spCat1.getSelectedItem().toString().trim();
final String email = ed4.getText().toString().trim();
final String contAddr = ed5.getText().toString().trim();
final String phoneNo = ed6.getText().toString().trim();
final String mobileNo = ed7.getText().toString().trim();
final String currLoc = ed8.getText().toString().trim();
final String currSal = ed9.getText().toString().trim();
final String currInd = ed10.getText().toString().trim();
final String quali = spCat2.getSelectedItem().toString().trim();
final String carProfile = ed11.getText().toString().trim();
final String path = txt5.getText().toString().trim();
final String path2 = txt7.getText().toString().trim();
final String image = getStringImage(bitmap);
final String file = getStringFile(fileDoc);
RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Employee_Reg.this, "Please Wait: ", "Performing Registration", true,
true);
}
#Override
protected String doInBackground(Void... params){
HashMap<String, String> param = new HashMap<String, String>();
param.put("fullname", fullname);
param.put("email", email);
param.put("password", password);
param.put("gender", gender);
param.put("contAddr", contAddr);
param.put("phoneNo", phoneNo);
param.put("mobileNo", mobileNo);
param.put("currLoc", currLoc);
param.put("currSal", currSal);
param.put("currInd", currInd);
param.put("quali", quali);
param.put("carProfile", carProfile);
param.put("path", path);
param.put("path2", path2);
param.put(KEY_IMAGE, image);
param.put(KEY_FILE, file);
String result = rh.sendPostRequest(URL, param);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if (s.equalsIgnoreCase("Sorry, email id already exists")) {
alert.showAlertDialog(Employee_Reg.this, "Registration Failed..",
"Sorry, email id already exists, choose another email.", false);
} else if (s.equalsIgnoreCase("success")) {
alert.showAlertDialog(Employee_Reg.this, "Successful Registration..",
"We have just sent you an email for confirmation before you log-in.", true);
ed1.setText("");
ed2.setText("");
ed3.setText("");
ed4.setText("");
ed5.setText("");
ed6.setText("");
ed7.setText("");
ed8.setText("");
ed9.setText("");
ed10.setText("");
ed11.setText("");
txt5.setText("");
txt7.setText("");
txt3.setVisibility(View.VISIBLE);
txt3.setText("We have just sent you an email for confirmation before you log-in.");
} else if (s.equalsIgnoreCase("test")) {
// username / password doesn't match
alert.showAlertDialog(Employee_Reg.this, "Registration Failed..",
"You cannot register empty details", false);
} else {
// if no category not is selected
alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", s, false);
}
}
}
RegisterUser ru = new RegisterUser();
ru.execute();
}
}
I noticed the particular function that was returning a null value was the right function then I decided to know why it was returning null value.
I decided to declare the following object and value type variables globally and then initialized them in the onCreate() method.
InputStream inputStream = null ;
ByteArrayOutputStream output = null;
Base64OutputStream output64 = null;
byte[] buffer;
int bytesRead;
String encodedFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buffer = new byte[10240];//specify the size to allow
output = new ByteArrayOutputStream();
output64 = new Base64OutputStream(output, Base64.DEFAULT);
encodedFile = output64.toString();
}
public String getStringFile(File f) {
InputStream inputStream = null;
try {
//Please remember that filePath2 is an object of Uri
String uriString = filePath2.toString();
f = new File(uriString).getAbsoluteFile();
inputStream = new FileInputStream(f);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
encodedFile = output64.toString();
}
catch (FileNotFoundException e1 ) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return encodedFile;
}
Finally, Let's take note that variables (i.e. value or object type variables) declared globally that are expected to be accessed severally within the activity class should be initialized in the onCreate Method for them to return their values at any point of the class that it will be called except otherwise we want to re-initialize them for a different values.