This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
In my application i want to select image from gallery and compress it.
For compress i use this library : https://github.com/zetbaitsu/Compressor
I wrote below codes for it, but when i run the application and select image from gallery, it throws force close and show below errors in logCat :
My activity codes :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) {
if (data != null) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
cursor.close();
postPath = mediaPath;
uploadImageToServer(postPath);
}
}
} else if (resultCode != RESULT_CANCELED) {
}
}
}
private void uploadImageToServer(String imagePath) {
if (imagePath == null || imagePath.equals("")) {
return;
} else {
showpDialog();
Map<String, RequestBody> map = new HashMap<>();
File file = new File(imagePath);
try {
compressedImage = new Compressor(getActivity())
.setMaxWidth(2000)
.setMaxHeight(1400)
.setQuality(90)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
LogCat error :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:70)
at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33)
at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60)
at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
at com.app.android.Fragments.NewAddressFragment.uploadImageToServer(NewAddressFragment.java:486)
at com.app.android.Fragments.NewAddressFragment.onActivityResult(NewAddressFragment.java:353)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:156)
at android.app.Activity.dispatchActivityResult(Activity.java:7295)
Show error for this line : .compressToFile(file);
UPDATE : show this error just for some images no all images!
How can i fix it? please help me
Another assumption on GitHub is, that you probably try to store the changed file with the original name in the original path. This also may lead to problems. Please try this version of code. I added compressedFileName.
private void uploadImageToServer(String imagePath) {
if (imagePath == null || imagePath.equals("")) {
return;
} else {
showpDialog();
Map<String, RequestBody> map = new HashMap<>();
File file = new File(imagePath);
if(file != null && file.exists() && file.canRead()) {
try {
String compressedFileName = "_" + file.getName();
compressedImage = new Compressor(getActivity())
.setMaxWidth(2000)
.setMaxHeight(1400)
.setQuality(90)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(file, compressedFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please handle through try and catch block and show dialog message to user for select another image, may be selected image is corrupted.
Just make sure that file is not null.
private void uploadImageToServer(String imagePath) {
if (imagePath == null || imagePath.equals("")) {
return;
} else {
showpDialog();
Map<String, RequestBody> map = new HashMap<>();
File file = new File(imagePath);
if(file != null && file.exists() && file.canRead()) {
try {
compressedImage = new Compressor(getActivity())
.setMaxWidth(2000)
.setMaxHeight(1400)
.setQuality(90)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
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.
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 use a Intent to get pictures path and open them into a File. I can open files allocated in "Camera" folder like "/storage/emulated/0/DCIM/Camera/IMG_20160817_232858.jpg", but I cannot open files in locations like "/storage/emulated/0/Pictures/1634894_.png". Using file.exists() it just says that it doesn't.
Need to say that I'm using API 23 and I request READ_EXTERNAL_STORAGE, so this souldn`t be a problem... But I can't access those files even with that.
What can be wrong?
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
File file = new File(picturePath);
if(file.exists()) {
} else {
}
cursor.close();
}
}
Updated: it doesn't happens with all the files from the same folder, just some of them, but they really exist since I can open them from the gallery.
Update2:
I use this Intent.
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
Update3:
Running time permissions:
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
SomeWork();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
else {
SomeWork();
}
Permissions in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
The MediaStore will index images that are not accessible to you from the filesystem. There is no requirement for a DATA column to return a value that you can use.
Instead, stop trying to get a File, and use the Uri itself:
getContentResolver().openInputStream() to get an InputStream on it
DocumentFile.fromSingleUri() to get a DocumentFile for easy access to metadata (e.g., MIME type)
try{
// this works!!!
File csvfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/brcOrdersaved.csv");
final String filename = csvfile.toString();
if (!csvfile.exists()) {
// displayMsg(context, "No Saved Order: ");
return (false);
}
FileReader fr = new FileReader(filename);
BufferedReader reader = new BufferedReader(fr);
String csvLine = "";
final char Separator = ',';
final char Delimiter = '"';
final char LF = '\n';
final char CR = '\r';
boolean quote_open = false;
if (reader.equals(null)) {
displayMsg(context, "NULL");
return (false);//rww 11/13/2021
}
int i = 0;
while (!myendofcsvfile) {
csvLine = reader.readLine();
if (csvLine == null) {
myendofcsvfile = true;
}
// do stuff here
}
fr.close();
fileexists = true;
} catch (Exception e) {
String msg = "Can not Load Saved Order ";
fileexists = false;
return (fileexists);
}
I'm using a GestureImageView Project that I've got from Github, I have several images in my drawable folder : page1.jpg, page2.jpg, page3.jpg,.........page30.jpg. I have a variable called pagenumber, when I click on a button this variable will increment, alson I want to load the image in the GestureImageView. Here is my code in the Main Class :
pagenumber++;
GestureImageView view1 = (GestureImageView) findViewById(R.id.image);
String uriPath = "android.resource://"+getPackageName()+"/drawable/page"+String.valueOf(pagenumber);
Uri uri = Uri.parse(uriPath);
view1 .setImageURI(uri);
In the GestureImageView.java the code is :
#Override
public void setImageURI(Uri mUri) {
if ("content".equals(mUri.getScheme())) {
try {
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = getContext().getContentResolver().query(mUri, orientationColumn, null, null, null);
if (cur != null && cur.moveToFirst()) {
imageOrientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
InputStream in = null;
try {
in = getContext().getContentResolver().openInputStream(mUri);
Bitmap bmp = BitmapFactory.decodeStream(in);
if(imageOrientation != 0) {
Matrix m = new Matrix();
m.postRotate(imageOrientation);
Bitmap rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
bmp.recycle();
setImageDrawable(new BitmapDrawable(getResources(), rotated));
}
else {
setImageDrawable(new BitmapDrawable(getResources(), bmp));
}
}
finally {
if(in != null) {
in.close();
}
if(cur != null) {
cur.close();
}
}
}
catch (Exception e) {
Log.w("GestureImageView", "Unable to open content: " + mUri, e);
}
}
else {
setImageDrawable(Drawable.createFromPath(mUri.toString()));
}
if (drawable == null) {
Log.e("GestureImageView", "resolveUri failed on bad bitmap uri: " + mUri);
// Don't try again.
mUri = null;
}
}
Well I'm having an empty image in the GestureImageView, it's not loading. The logcat says Unable to decode stream : java.io.FileNotFoundException: /android.resource:/com.example.tests/drawable/page3 : open failed : ENOENT (No such file or directory). I also tried to add the .png extension but I had the same result.
Please note that when I use an imageview instead of GestureImageView it works
Any help please ?
Right now i am creating application based on android and dropbox.
I want to upload my recorded audio on dropbox based on my api key but i have tried lot in it. i cant find solution so any one can help me to overcome this situation.
Here is my code. I have done image capture and video capture with help of this code. The code was working fine but when i converting into my audio recorder it does't work. Thanks for the reply.
Audio recorder function:
mAudio=(Button)findViewById(R.id.audio_button);
mAudio.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
// Picture from camera
intent.setAction(Audio.Media.RECORD_SOUND_ACTION);
Uri fileUri = getOutputMediaFileUri(MEDIA_TYPE_AUDIO);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
Log.i(TAG, "Importing New Picture: " + mCameraFileName);
try {
startActivityForResult(intent, NEW_AUDIO);
} catch (ActivityNotFoundException e) {
showToast("There doesn't seem to be a camera.");
}
}
});
Upload Function:
else if(requestCode == NEW_AUDIO){
if (resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
}
if (uri == null && mAudioFileName != null) {
uri = Uri.fromFile(new File(mAudioFileName));
Log.v("Audio Uri", uri.toString()+" "+uri.getPath());
}
File file = new File(mAudioFileName);
Log.v("Audio file", ""+file.getPath());
if (uri != null) {
UploadFile upload = new UploadFile(Home.this, mApi, PHOTO_DIR, file);
upload.execute();
}
//showToast("till capture");
}
else if(resultCode == RESULT_CANCELED)
{
uriAudio = null;
Toast.makeText(Home.this,"Cancelled!",Toast.LENGTH_LONG).show();
}
As per official example given on site. I hope this will help you.
FileInputStream inputStream = null;
try {
File file = new File("/path/to/file.txt");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/testing.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}