NPE on HTC Sensation, works in the emulator - java

I have used some code to create a simple app to allow the adding of contact details. The code is very simple and works fine in the emulator and on a number of devices that I have, except on the new HTC Sensation.
Here is the code:
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, number.getText().toString().trim())
.withValue(Phone.TYPE, "TYPE_MOBILE")
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, name.getText().toString().trim())
.build());
try {
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I run it I get the following:
java.lang.NullPointerException
at android.os.Parcel.readException(Parcel.java:1328)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:160)
at android.database.DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(DatabaseUtils.java:137)
at android.content.ContentProviderProxy.applyBatch(ContentProviderNative.java:491)
at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:95)
at android.content.ContentResolver.applyBatch(ContentResolver.java:641)
at uk.co.androidfun.getthatnumber.mainActivity.saveCallContact(mainActivity.java:157)
at uk.co.androidfun.getthatnumber.mainActivity$3.onClick(mainActivity.java:74)
at android.view.View.performClick(View.java:2532)
at android.view.View$PerformClick.run(View.java:9277)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:4196)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
I have looked and looked at the code and cannot see an issue, and as I say works well in the emulator run 2.3.3 but not on the phone running the same.
Thanks
John

I know this is an old question, but I was just hit by that weird NPE too, so this might help someone.
After some digging I found that one of the values I gave the newInsert was of the wrong type (damn refactoring!)
I had:
String val = ...;
builder.withValue(Data.RAW_CONTACT_ID, val);
Instead of:
long val = ...;
builder.withValue(Data.RAW_CONTACT_ID, val);
Fixing that solved the NPE.
So, looking at your code, I would first change "TYPE_MOBILE" to the Android const CommonDataKinds.Phone.TYPE_MOBILE (since this value might change among different vendors),
Second, make sure all the keys you're using in withValue have the same type as the one you're giving them (not sure 'null' is legal for ACCOUNT_TYPE), and print trimmed strings to make sure they have meaningful values.
Hope this helps!

Check what code refers to line of
androidfun.getthatnumber.mainActivity.saveCallContact(mainActivity.java:157)
There also should be more to your logcat, a Caused by etc etc that is usually more direct in pointing to the bad code.

I had the same problem with two HTC devices.
What solved it for me is adding some more values to the last data entry (I've added five more, other then the raw contact ID, phone number and mime tyep).
I have no idea why it works now, but it does.

Related

ImageIO.read(stream) fails to read the stream no matter the given stream

I have a method called createBufferedImageFromURI that takes a string that could be either a file system path or an URL, and creates a BufferedImage from the resource corresponding to that string.
The method code is the following:
private static BufferedImage createBufferedImageFromURI(String filePathOrUrl)
throws IOException
{
IHttpContext httpContext = com.genexus.ModelContext
.getModelContext().getHttpContext();
InputStream is = null;
try {
if (filePathOrUrl.toLowerCase().startsWith("http://") ||
filePathOrUrl.toLowerCase().startsWith("https://") ||
(httpContext.isHttpContextWeb() &&
filePathOrUrl.startsWith(httpContext.getContextPath())))
is = new URL(GXDbFile.pathToUrl(filePathOrUrl, httpContext))
.openStream();
else
is = getGXFile(filePathOrUrl).getStream();
return ImageIO.read(is);
} catch (IOException e) {
log.error("Failed to read image stream: " + filePathOrUrl);
throw e;
} finally {
is.close();
}
}
As you can see, the first part of the if - else block corresponds to the case where the string is an URL. It was working just fine until it suddenly didn't. The following started appearing in the webapp logs:
2023-02-14T09:25:30,286 [http-nio-8080-exec-13] ERROR com.genexus.GxImageUtil - getImageWidth https://static3.depositphotos.com/1000575/154/i/600/depositphotos_1549339-stock-photo-lithuania-landscape-panorama.jpg failed
java.lang.NullPointerException: Cannot invoke "java.awt.image.BufferedImage.getWidth()" because the return value of "com.genexus.GxImageUtil.createBufferedImageFromURI(String)" is null
at com.genexus.GxImageUtil.getImageWidth(GxImageUtil.java:79) ~[gxclassR-2.10-SNAPSHOT.jar:?]
at com.pruebasjavastable.webpanelimageapi_impl.e12042(webpanelimageapi_impl.java:771) ~[classes/:?]
at com.pruebasjavastable.webpanelimageapi_impl.strup040(webpanelimageapi_impl.java:736) ~[classes/:?]
at com.pruebasjavastable.webpanelimageapi_impl.start042(webpanelimageapi_impl.java:525) ~[classes/:?]
at com.pruebasjavastable.webpanelimageapi_impl.executeStartEvent(webpanelimageapi_impl.java:122) ~[classes/:?]
...
There is no other trace what could be the cause of this error. Neither on Tomcat's console or even in the browser console or network tab
I did some debugging to discard some obvious possible causes, but none of them where the case
GXDbFile.pathToUrl( filePathOrUrl, httpContext) builds the URL just fine. I even tried hard coding one and it still didn't work
Discarded some firewall or proxy issue by testing it on other PCs and networks. Even tried it on online playgrounds
Is there a problem with this implementation? As I said, it was working just fine until it suddenly didn't. Only change I can think of is that I changed my JDK from 17.0.4 to 17.0.6 but I read the release notes and nothing seems to affect my case.

Can we open channel without AID and control the power of embedded SE?

We are now developing a payment card with NXP NQ220 (has embedded SE, called eSE) on Android N. The platform is MTK. Now, we can interact with eSE using OMA (using org.simalliance.openmobileapi.jar). It works as expected.
I was wondering if there is any ways to open channel in session without AID? Besides, is there any ways to control the power of eSE(power-on and power-off) and reset eSE in some situations?
My investigation as follows:
About open channel without AID, I have found following sentences in page 16 of Open Mobile API specification V3.
(h)Method: Channel openLogicalChannel(byte[] aid, Byte P2)
Open a logical channel with the SE, selecting the applet represented by the >given AID. If the AID is null, which means no applet is to be selected on >this channel, the default applet is used. It's up to the SE to choose which >logical channel will be used.
However, if we set aid to null in openLogicalChannel(byte[] aid), following exception will be shows. What happens about it? Is the default applet or eSE have problems?
01-30 01:06:39.941 V/SmartcardService( 2587): OpenLogicalChannel Exception: Access Control Enforcer: no APDU access allowed!
01-30 01:06:39.947 E/SeControlClient( 3239): Error occured:
01-30 01:06:39.947 E/SeControlClient( 3239): java.lang.SecurityException: Access Control Enforcer: no APDU access allowed!
01-30 01:06:39.947 E/SeControlClient( 3239): at org.simalliance.openmobileapi.SEService.checkForException(SEService.java:255)
01-30 01:06:39.947 E/SeControlClient( 3239): at org.simalliance.openmobileapi.Session.openLogicalChannel(Session.java:295)
It seems there is no method in OMA to reset eSE. But I found reset() method in INxpNfcAdapterExtras. However, when I use INxpNfcAdapterExtras.reset(), it always return false. Following codes is how we get INxpNfcAdapterExtras.
private INxpNfcAdapterExtras getNxpNfcAdapterExtras() {
if (mNfcAdapter != null) {
try {
INxpNfcAdapter nxpNfcAdapter =
mNfcAdapter.getService().getNxpNfcAdapterInterface();
return nxpNfcAdapter.getNxpNfcAdapterExtrasInterface();
} catch (Exception e) {
Log.e(LOGTAG, "Exception occured:", e);
}
} else {
Log.e(LOGTAG, "Please initialize NfcAdapter first.");
}
return null;
}
About control the power of eSE, is it related to the platform? Can you give me some suggestions? Thank you very much.
Dont known
To access SE functions your application must be execute with owner of android device.
You could check this in : https://github.com/NXPNFCLinux/android_nxp-nci/blob/1d95fe24334fa12c9d9eccd1141f8739972c4288/aosp/packages/apps/Nfc/src/com/android/nfc/NfcService.java
The reset method check permission before:
public boolean reset(String pkg) throws RemoteException {
NfcService.this.enforceNfceeAdminPerm(pkg);
Bundle result;
boolean stat = false;
try {
stat = _nfcEeReset();
result = writeNoException();
} catch (IOException e) {
result = writeEeException(EE_ERROR_IO, e.getMessage());
}
Log.d(TAG,"reset" + stat);
return stat;
}
The check permission method:
public void enforceNfceeAdminPerm(String pkg) {
if (pkg == null) {
throw new SecurityException("caller must pass a package name");
}
NfcPermissions.enforceUserPermissions(mContext);
if (!mNfceeAccessControl.check(Binder.getCallingUid(), pkg)) {
throw new SecurityException(NfceeAccessControl.NFCEE_ACCESS_PATH +
" denies NFCEE access to " + pkg);
}
if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
throw new SecurityException("only the owner is allowed to call SE APIs");
}
}
To execute your app with device owner, you could follow my anwser here:
Device Admin API, how to be a device owner?
I'm not sure about what you mean "control the power of eSE". If it's on/off eSE, then eSE is integrated with NFC chip so if you disable NFC in Android eSE will be power off.
I have found another way to solve this issue. It used NXP's own class NxpNfcAdapterExtrasService.
1.I still don't know why the exception happens when we open channel use the default Applet(without AID). But, with the method in NxpNfcAdapterExtrasService, we can establish connection with eSE.
2.About the second question. The codes is right but the way of how to use INxpNfcAdapterExtras.reset() is wrong. This method will return true only when you do something with eSE. Like transmit and execute APDU commands. So you can use this method when you want to disconnect the connection with eSE.
3.About the third question, I don't know whether the openUicc()/closeUicc() method can control the eSE power. But, it seems this two method works as expected.

Error in OleControl causes JVM to crash completely - how to suppress?

I have some serious problem. We have in our application plugged in an external ole plugin in our eclipse rcp client. This plugin causes some error while running, which then kills the entire client.
Since we cannot fix the problem, we want to catch that error, so that the client at least won't crash. To be more precise, the client crashes because the JVM caused a fatal error. Is there any possibility to suppress those errors, to avoid the JVM from crashing?
This is the code where we include the plugin in our client, has anyone some idea how to achieve such a error-catch?
// create OLE frame and site (XMAX control).
clatFrame = new OleFrame(parent, SWT.NONE);
clatUtil = null;
try {
clatSite = new OleControlSite(clatFrame, SWT.NONE,
"Congree.XMax.Control");
clatSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
clatUtil = new OleUtil(clatSite);
// setzt die Dialogsprache
String dialogLanguage = Platform.getNL();
// Umgehung für Bug-20760
if (LOCALE_DE.equalsIgnoreCase(dialogLanguage)) {
// ClatIn Format 'de-DE'
dialogLanguage = dialogLanguage + "-DE"; //$NON-NLS-1$
} else {
dialogLanguage = dialogLanguage.replace("_", "-");
}
clatUtil.invokeMethod(null, "SetGuiLanguage", true, dialogLanguage);
GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 25).grab(true,
false).align(SWT.FILL, SWT.TOP).applyTo(clatFrame);
} catch (SWTException e) {
clatFrame.dispose();
LOG.warn("OLE control (CLAT) not installed");
}
LOG
http://www.file-upload.net/download-8284055/jvm_errorlog.log.html
You can try to catch the Throwable instead of the SWTException. If that doesn't help, you can try a different library like jacob for the OLE/COM automation: http://sourceforge.net/projects/jacob-project/ The crash is most likely caused by some invalid state in the c code, therefore a different library might help.

MediaRecorder - setOrientationHint() exception/fail

I've been trying to fix this problem with MediaRecorder video Rotation on and off for weeks. I cannot get the line setOrientationHint(90) to work on a physical Samsung Galaxy S1 running Android 2.3.3 (SDK 10). This should run fine on anything above SDK 9.
When I call setOrientationHint(90) I get an exception : setParameters(video-param-rotation-angle-degrees=90) failed. Detailed error details below.
As a result I'm forced to check SDK and only call setOrientationHint() if SDK>10. ie, this code works fine on all other SDK versions above 10 which I have tested. I have tested on Samsung Galaxy Nexus running 4.2.2 and works fine.
Here is my code:
(cut down to show order of calls to MediaRecorder)
mCamera = getCameraInstance();
mCamera.setPreviewDisplay(holder);
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setOrientationHint(90);
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: recording setup
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoSize(720,480);
mMediaRecorder.setVideoFrameRate(15);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
// Step 4: Set output file
currentOutputFileName = DIRECTORY_PATH + "zzzz"+ iCount +".mp4";
mFile = new File(currentOutputFileName);
mMediaRecorder.setOutputFile(mFile.getAbsolutePath());
// Step 4.1: Set recording length
mMediaRecorder.setMaxDuration(10000);
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(cameraView.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
mMediaRecorder.prepare();
Has anyone had this problem? I can't find anyone else is experiencing this and I can't believe thats the case. Is it possible its just a Australian Samsung Galaxy S1 running 2.3.3 issue?
I've seen references to people having problems where that line runs but with the actual video does not rotate but I actually receive an Exception - the line doesn't run at all. I've checked and rechecked the command order and it seems fine. I think what is most important is that the setOrientationHint() command occurs before mediaRecorder.prepare()
Here is the Error:
AuthorDriver::setParameter() unrecognized key "video-param-rotation-angle-degrees"
setParameter(video-param-rotation-angle-degrees = 90) failed with result -5
Ln 1047 handleSetParameters("video-param-rotation-angle-degrees=90") error
Command (12) failed
setParameters(video-param-rotation-angle-degrees=90) failed: -2147483648
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x40015578)
FATAL EXCEPTION: main
java.lang.RuntimeException: setParameter failed.
at android.media.MediaRecorder.setParameter(Native Method)
at android.media.MediaRecorder.setOrientationHint(MediaRecorder.java:341)
at com.on3x.emergency.Recorder.prepareVideoRecorder(Recorder.java:196)
at com.on3x.emergency.Recorder.startRecording(Recorder.java:90)
at com.on3x.emergency.GUI.RecordActivity$1.onClick(RecordActivity.java:86)
at android.view.View.performClick(View.java:2538)
at android.view.View$PerformClick.run(View.java:9152)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Force finishing activity com.on3x.emergency/.GUI.RecordActivity
Dumpstate > /data/log/dumpstate_app_error
If anyone can give ANY help it would be much appreciated. For now I've had to tell our client that its not something I can fix at this moment and Video will have to be sideways.
Is there another way of rotating videos? Basically my app records videos and uploads them to the server. At the moment this 2.3.3 phone cannot rotate the video so its uploaded sideways
Cheers
Edit:
This is the code I now have in place. As suggested by Ashish Gupta, AuthorDriver does not contain the appropriate param on Samsung Galaxy S1 (australian model) running 2.3.3
if (android.os.Build.VERSION.SDK_INT>=9) {
// attempt to rotate the video 90 degrees.
try {
mMediaRecorder.setOrientationHint(90);
Utils.logLine("orientation rotated 90", this, Utils.LOG_TYPE_DEBUG);
} catch (Exception e) {
Utils.logLine("error trying setOrientationHint"+ e.getMessage(), this, Utils.LOG_TYPE_ERROR, e);
e.printStackTrace();
}
} else {
Utils.logLine("orientation set skipped ", this, Utils.LOG_TYPE_DEBUG);
}
Note: Utils.logLine is simply a Utilility function I have for printing debug and error statements to log. Hopefully that might help someone else...
Looking at the logs you have attached, it seems that Samsung Galaxy S1 running Android 2.3.3 does not support setOrientationHint.
This is the code from AuthorDriver.cpp
PVMFStatus AuthorDriver::setParameter(
const String8& key, const String8& value) {
if (key == "max-duration") {
int64_t max_duration_ms;
if (safe_strtoi64(value.string(), &max_duration_ms)) {
return setMaxDurationOrFileSize(
max_duration_ms, true /* limit_is_duration */);
}
} else if (key == "max-filesize") {
int64_t max_filesize_bytes;
if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
return setMaxDurationOrFileSize(
max_filesize_bytes, false /* limit is filesize */);
}
} else if (key == "audio-param-sampling-rate") {
int64_t sampling_rate;
if (safe_strtoi64(value.string(), &sampling_rate)) {
return setParamAudioSamplingRate(sampling_rate);
}
} else if (key == "audio-param-number-of-channels") {
int64_t number_of_channels;
if (safe_strtoi64(value.string(), &number_of_channels)) {
return setParamAudioNumberOfChannels(number_of_channels);
}
} else if (key == "audio-param-encoding-bitrate") {
int64_t audio_bitrate;
if (safe_strtoi64(value.string(), &audio_bitrate)) {
return setParamAudioEncodingBitrate(audio_bitrate);
}
} else if (key == "video-param-encoding-bitrate") {
int64_t video_bitrate;
if (safe_strtoi64(value.string(), &video_bitrate)) {
return setParamVideoEncodingBitrate(video_bitrate);
}
}
// Return error if the key wasnt found
LOGE("AuthorDriver::setParameter() unrecognized key \"%s\"", key.string());
return PVMFErrArgument;
}
The key video-param-rotation-angle-degrees is not supported on Samsung Galaxy S1 aith Android 2.3.3
You can compare the logs between Nexus 4.2.2 and S1 2.3.3 and see if you see any noticeable difference.

iText Out of memory on a 5440032-byte allocation

I have encountered a problem when I am extracting text from PDF.
01-29 09:44:15.397: E/dalvikvm-heap(8037): Out of memory on a 5440032-byte allocation.
I looked up the contents of the page and it has a image above the text. What i want to know is how do I catch the error and skip that page? I have tried:
try {
pages = new String[pdfPage];
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
TextExtractionStrategy strategy;
for (int pageNum = 1; pageNum <= pdfPage; pageNum++) {
// String original_content = "";
// original_content = PdfTextExtractor.getTextFromPage(reader,
// pageNum, new SimpleTextExtractionStrategy());
Log.e("MyActivity", "PageCatch: " + (pageNum + fromPage));
strategy = parser.processContent(pageNum,
new SimpleTextExtractionStrategy());
readPDF(strategy.getResultantText(), pageNum - 1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The try catch above does not catch the error of strategy = parser.processContent(pageNum,
new SimpleTextExtractionStrategy());
I already tried commenting out all the lines inside the for loop and no error. but when i leave out strategy = parser.processContent(pageNum,
new SimpleTextExtractionStrategy()); and it errors.
as i have understood about the error, that occurs when the memory is not enough to hold the data that you are reading, I believe you can't catch that error.
I would strongly suggest you to drop some old data, and make sure to just hold not too heavy data in your variable.
or refer to this
Out of memory error due to large number of image thumbnails to display
You want to catch the error and skip that page and tried using
try {
...
} catch (Exception e) {
...
}
which didn't do the trick. Unless the DalvikVM handles out-of-memory situations completely different than Java VMs, this is no surprise: The Throwable used by Java in such situations is an OutOfMemoryError, i.e. not an Exception but an Error, the other big subtype of Throwable. Thus, you might want to try
} catch (OutOfMemoryError e) {
or
} catch (Error e) {
or even
} catch (Throwable e) {
to handle your issue. Beware, though, when an Error is thrown, this generally means something bad is happening; catching and ignoring it, therefore, might result in a weird program state.
Obviously, though, if you (as you said) only want to try and skip a single page and otherwise continue, you'll have to position the try { ... } catch() { ... } differently, more specifically around the handling of the single page, i.e. inside the loop.
On the other hand, dropping all references to objects held by the PDF library and re-opening the PDF might help, remember Kevin's answer to your question Search Text and Capacity of iText to read on the iText-Questions mailing list. Following that advice you'd have all iText use and a limited loop (for a confined number of pages) inside the try { ... } catch() { ... }, you'd merely remember the last page read in some outer variables.
Furthermore you can limit memory usage by using a PdfReader constructor taking a RandomAccessFileOrArray parameter --- readers constructed that way don't hold all the PDF in memory but instead only the cross reference table and some central objects. All else is read on demand.

Categories

Resources