I'm a Kotlin developer but I'm working on a java project, but when converting the classes through the sdk, this error appears.
How to solve?
fun deviceIsConnected(): Boolean {
var connected = false
val myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (myBluetoothAdapter != null && myBluetoothAdapter.isEnabled) {
if (configsAndModels!!.strMACPROBE != null && configsAndModels.strMACPROBE != "") {
val myDevice = myBluetoothAdapter.getRemoteDevice(
configsAndModels.strMACPROBE
)
try {
val m = myDevice.javaClass.getMethod("isConnected", null as Array<Class<*>>?)) //ERROR ON THIS LINE
connected = m.invoke(myDevice, *null as Array<Any?>?) as Boolean //ERROR ON THIS LINE
} catch (e: Exception) {
throw IllegalStateException(e)
}
}
}
return connected
}
JAVA :
public boolean deviceIsConnected() {
boolean connected = false;
BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (myBluetoothAdapter != null && myBluetoothAdapter.isEnabled()) {
if (configsAndModels.getStrMACPROBE() != null && !configsAndModels.getStrMACPROBE().equals("")) {
BluetoothDevice myDevice = myBluetoothAdapter.getRemoteDevice(configsAndModels.getStrMACPROBE());
try {
Method m = myDevice.getClass().getMethod("isConnected", (Class[]) null);
connected = (boolean) m.invoke(myDevice, (Object[]) null);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
return connected;
}
Your Java code is explicitly passing a null array as the varargs, which is unnecessary. You could simplify your Java code to the following, which implicitly passes an empty array:
Method m = myDevice.getClass().getMethod("isConnected");
connected = (boolean) m.invoke(myDevice);
Likewise, in Kotlin, you can omit the varargs if you're passing zero values:
val m = myDevice.javaClass.getMethod("isConnected")
connected = m.invoke(myDevice) as Boolean
Java allows the null array for backward compatibility (to versions that used arrays instead of varargs) and because it doesn't have null safety. Since Kotlin doesn't need the backward compatibility, it doesn't need to support null arrays.
Related
This is code in kotlin. Showing error Type inference failed: inline fun T.apply(block: T.() -> Unit): T cannot be applied to receiver: Message arguments: (Message.() -> Any) .
**map(From)' in 'Mapper' clashes with 'map(Object)' in 'CursorToMessageImpl'; both methods have same erasure, yet neither overrides the other
**
class CursorToMessageImpl #Inject constructor(
private val context: Context,
private val cursorToPart: CursorToPart,
private val keys: KeyManager,
private val permissionManager: PermissionManager,
private val preferences: Preferences) : CursorToMessage
{
private val uri = Uri.parse("content://mms-sms/complete-conversations")
private val projection = arrayOf(
MmsSms.TYPE_DISCRIMINATOR_COLUMN,
MmsSms._ID,
Mms.DATE,
Mms.DATE_SENT,
Mms.READ,
Mms.THREAD_ID,
Mms.LOCKED,
Sms.ADDRESS,
Sms.BODY,
Sms.SEEN,
Sms.TYPE,
Sms.STATUS,
Sms.ERROR_CODE,
Mms.SUBJECT,
Mms.SUBJECT_CHARSET,
Mms.SEEN,
Mms.MESSAGE_TYPE,
Mms.MESSAGE_BOX,
Mms.DELIVERY_REPORT,
Mms.READ_REPORT,
MmsSms.PendingMessages.ERROR_TYPE,
Mms.STATUS
)
override fun map(from: Pair<Cursor, CursorToMessage.MessageColumns>): Message {
val cursor = from.first
val columnsMap = from.second
return Message().apply {
type = when {
cursor.getColumnIndex(MmsSms.TYPE_DISCRIMINATOR_COLUMN) != -1 -> cursor.getString(columnsMap.msgType)
cursor.getColumnIndex(Mms.SUBJECT) != -1 -> "mms"
cursor.getColumnIndex(Sms.ADDRESS) != -1 -> "sms"
else -> "unknown"
}
id = keys.newId()
threadId = cursor.getLong(columnsMap.threadId)
contentId = cursor.getLong(columnsMap.msgId)
date = cursor.getLong(columnsMap.date)
dateSent = cursor.getLong(columnsMap.dateSent)
read = cursor.getInt(columnsMap.read) != 0
locked = cursor.getInt(columnsMap.locked) != 0
subId = if (columnsMap.subId != -1) cursor.getInt(columnsMap.subId)
else -1
when (type) {
"sms" -> {
address = cursor.getString(columnsMap.smsAddress) ?: ""
boxId = cursor.getInt(columnsMap.smsType)
seen = cursor.getInt(columnsMap.smsSeen) != 0
body = columnsMap.smsBody
.takeIf { column -> column != -1 } // The column may not be set
?.let { column -> cursor.getString(column) } ?: "" // cursor.getString() may return null
errorCode = cursor.getInt(columnsMap.smsErrorCode)
deliveryStatus = cursor.getInt(columnsMap.smsStatus)
}
"mms" -> {
address = getMmsAddress(contentId)
boxId = cursor.getInt(columnsMap.mmsMessageBox)
date *= 1000L
dateSent *= 1000L
seen = cursor.getInt(columnsMap.mmsSeen) != 0
mmsDeliveryStatusString = cursor.getString(columnsMap.mmsDeliveryReport) ?: ""
errorType = if (columnsMap.mmsErrorType != -1) cursor.getInt(columnsMap.mmsErrorType) else 0
messageSize = 0
readReportString = cursor.getString(columnsMap.mmsReadReport) ?: ""
messageType = cursor.getInt(columnsMap.mmsMessageType)
mmsStatus = cursor.getInt(columnsMap.mmsStatus)
val subjectCharset = cursor.getInt(columnsMap.mmsSubjectCharset)
subject = cursor.getString(columnsMap.mmsSubject)
?.takeIf { it.isNotBlank() }
?.let(_root_ide_package_.app.google.android.mms.pdu_alt.PduPersister::getBytes)
?.let { _root_ide_package_.app.google.android.mms.pdu_alt.EncodedStringValue(subjectCharset, it).string } ?: ""
textContentType = ""
attachmentType = Message.AttachmentType.NOT_LOADED
parts.addAll(cursorToPart.getPartsCursor(contentId)?.map { cursorToPart.map(it) } ?: listOf())
}
else -> -1
}
}
}
**and interference mapper is :-**
interface Mapper<in From, out To> {
fun map(from: From): To
}
I'm not 100% sure this is your issue, but since else -> -1 in your when statement doesn't accomplish anything, try removing it. A when statement doesn't have to be exhaustive when it isn't being forced to be evaluated as an expression (by assigning its result to a variable or property).
else -> -1 at the bottom of your when statement causes it to be a when expression that returns Any. Usually, the compiler can interpret a lambda ending in an expression other than Unit as having an implicit return of Unit if there are no overloads that it would otherwise match. But there may be some cases where the involved classes are complex enough to prevent it from deducing that.
For the below piece of code Sonar throws me a critical violation - Correctness - Nullcheck of status value previously dereferenced
Can someone suggest on this on what am I doing wrong here?
code
public boolean isExactMacthBill(AddressResponse response) {
boolean exactMatch = false;
if (null != response && null != response.getHostResponse()) {
HostResponseDetail hostResponse = response.getHostResponse();
String addressStatus = hostResponse.getMatchStatus();
ResponseDetail status = hostResponse.getStatus();
String addressMatchCode = status.getCode();
if (null != response.getMatchedAddresses() && response.getMatchedAddresses().size() > 0 && status != null) {
if (addressStatus.equalsIgnoreCase(Constants.USPS_MATCH)
|| (addressStatus.equalsIgnoreCase(Constants.PARTIAL_MATCH)
&& addressMatchCode.equalsIgnoreCase("3SXU"))) {
exactMatch = true;
} else
exactMatch = false;
}
}
return exactMatch;
}
The actual problem is in the line after the highlighted one - you've got:
if (... && status != null)
Just remove that check and I think SonarLint will be happy. It unnecessary, because if status is null then status.getCode() will already have thrown an exception before you reach that condition.
Fundamentally, you need to know whether getStatus() should ever return null - whether you have to handle that situation explicitly. If you do, you should check it before your call to status.getCode(), and react accordingly. If you don't, it's fine to call the getCode() method - if your assumption is incorrect, you'll get a NullPointerException as normal, which is probably the most appropriate result for the scenario of "the world isn't as I expect it to be". But you shouldn't try to "handle" it being null after you've already depended on it being non-null.
status can be null when it is received from hostResponse.getStatus();; so when the line String addressMatchCode = status.getCode(); is called it can result in a Null Reference Exception.
You should verify all the variables if there are null before calling methods on them.
Move your addressMatchCode inside your if condition which null check the status.
public boolean isExactMacthBill(AddressResponse response) {
boolean exactMatch = false;
if (null != response && null != response.getHostResponse()) {
HostResponseDetail hostResponse = response.getHostResponse();
String addressStatus = hostResponse.getMatchStatus();
ResponseDetail status = hostResponse.getStatus();
if (null != response.getMatchedAddresses() && response.getMatchedAddresses().size() > 0 && status != null) {
String addressMatchCode = status.getCode();
if (addressStatus.equalsIgnoreCase(Constants.USPS_MATCH)
|| (addressStatus.equalsIgnoreCase(Constants.PARTIAL_MATCH)
&& addressMatchCode.equalsIgnoreCase("3SXU"))) {
exactMatch = true;
} else
exactMatch = false;
}
}
return exactMatch;
}
I tried to find a similar question, but I didn't succeed.
In a bean, I'm looping through a ViewEntryCollection several times, adding or deleting entries. Could someone tell me exactly when these objects should be recycled? I want to be able to reuse the whole collection so I don't want to destroy any objects I might still need.
My code:
public static int FTSearchAll(ViewEntryCollection vec, View vw, String cat, String query) throws NotesException {
...
for (ViewEntry ve = nav.getFirst(); ve != null; ) {
ViewEntry next = nav.getNext(ve);
Document doc = ve.getDocument();
if (doc == null)
continue;
try {
Vector v = session.evaluate(query, doc);
if (v != null && v.size() > 0 && (Double) v.elementAt(0) != 0) {
vec.addEntry(ve, false);
} else {
for (ViewEntry dce = vec.getFirstEntry(); dce != null;) {
ViewEntry dcnext = vec.getNextEntry(dce);
if (dce.getNoteID().equals(ve.getNoteID())) {
vec.deleteEntry(dce);
incinerate(dce);
break;
}
dce = dcnext;
}
}
} catch (NotesException ne) {
} finally {
incinerate(ve, doc);
}
ve= next;
}
As always: thanks!
The rule is quite simple: when a Java object pointing to a Notes C object is about to go onto the garbage heap, .recycle() must have been called.
So you need to do that for all entries inside the loop.
My little rule of thumb: the block (think { ... } ) that created a Notes Java object must call its .recycle() function at the end.
Saves you lot of headaches
I see this, but not completely sure whether I miss something or the code keeps its functionality... :S
for (ViewEntry ve = nav.getFirst(); ve != null; ) {
ViewEntry next = nav.getNext(ve);
Document doc = ve.getDocument();
if (doc == null) {
incinerate(ve); // << new
ve = next; // << new
continue;
}
try {
Vector v = session.evaluate(query, doc);
if (v != null && v.size() > 0 && (Double) v.elementAt(0) != 0) {
vec.addEntry(ve, false);
} else {
for (ViewEntry dce = vec.getFirstEntry(); dce != null;) {
ViewEntry dcnext = vec.getNextEntry(dce);
if (dce.getNoteID().equals(ve.getNoteID())) {
vec.deleteEntry(dce);
incinerate(dce, dcnext); // << new
break;
}
incinerate(dce); // << new
dce = dcnext;
}
}
} catch (NotesException ne) {
} finally {
incinerate(ve, doc);
}
ve = next;
}
Maybe it would be better to check another implementation.
Anyway, I recommend you to use the OpenNTF Domino API and get rid of recycle, and you will get also a proper iteration over entries:
http://www.openntf.org/main.nsf/project.xsp?r=project/OpenNTF%20Domino%20API
I 'm havin a problem with resolving enum.
I checked previous answers like why enum could not be resolved in JAVA?
and I did the answer but I still get the error. also followed another solution to change the compiler compliance level. but in my case it is originally set to 1.6
what should be changed here ?
Code :
CellTypes.java
public enum CellTypes {
STRING,LIST,PATH
}
in the event of canModify which is overriden
desc :
/**
* #see org.eclipse.jface.viewers.ICellModifier#canModify(java.lang.Object,
* java.lang.String)
*/
just calling setEditor method and setEditor is as follows
public void setEditor(int editorIndex, List<Object> choices, CellTypes UIType) {
try {
if (choices != null) {
String[] choicesArray = new String[choices.size()];
for (int i = 0; i < choices.size(); i++) {
choicesArray[i] = choices.get(i).toString();
}
editors[editorIndex] = new ComboBoxCellEditor(table, choicesArray, SWT.READ_ONLY);
editors[editorIndex].getControl().addTraverseListener(traverseListener);
columnEditorTypes[editorIndex] = EditorTypes.COMBO;
} else if(UIType == CellTypes.PATH) { // it gives "cannot resolve type " here
editors[editorIndex] = standardEditors.get(EditorTypes.PATH);
columnEditorTypes[editorIndex] = EditorTypes.PATH;
}
else
{
editors[editorIndex] = standardEditors.get(EditorTypes.STRING);
columnEditorTypes[editorIndex] = EditorTypes.STRING;
}}
catch(Exception e)
{
e.printStackTrace();
}
}
causes an error of cannot resolve CellTypes type
where ct is recognised as enum and its type is STRING
Change
if (ct = CellTypes.STRING)
to
if (ct == CellTypes.STRING)
You are assigning iso. comparing.
If I understood you correctly, you are comparing the String name of the enum value to an enum value. Try this:
if (CellTypes.valueOf(ct) == CellTypes.STRING)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have this Hash Set code and when I try to run my compile method on it I get the Null Pointer Exception: null error on it. Here is the code:
private void initKeywords() {
keywords = new HashSet<String>();
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}
private boolean isIdent(String t) {
if (keywords.contains(t)) { ***//This is the line I get the Error***
return false;
}
else if (t != null && t.length() > 0 && Character.isLetter(t.charAt(0))) {
return true;
}
else {
return false;
}
}
The other lines that goes along with this error is:
public void compileProgram() {
System.out.println("compiling " + filename);
while (theToken != null) {
if (equals(theToken, "int") || equals(theToken, "final")) {
compileDeclaration(true);
} else {
compileFunction(); //This line is giving an error with the above error
}
}
cs.emit(Machine.HALT);
isCompiled = true;
}
private void compileFunction() {
String fname = theToken;
int entryPoint = cs.getPos();
if (equals(fname, "main")) {
cs.setEntry(entryPoint);
}
if (isIdent(theToken)) theToken = t.token(); ***//This line is giving an error***
else t.error("expecting identifier, got " + theToken);
symTable.allocProc(fname,entryPoint);
accept("(");
compileParamList();
accept(")");
compileCompound(true);
if (equals(fname, "main")) cs.emit(Machine.HALT);
else cs.emit(Machine.RET);
}
Are you sure you're running initKeywords() before isIdent()?
Either keywords or t is null. Using either a debugger or print statements it should be pretty simple to determine. If keywords is null, I'd assume that initKeywords() has not been called yet.
You probably want to call initKeywords from the constructor of this object.
I personally try to stay away from init methods. As previously mentioned, a constructor serves as an initializer, and so does the static block:
private final static Set<String> KEYWORDS = new HashSet<String>();
static {
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}