Eclipse warning about NullPointer Access - Android - java

I am trying to retrieve the UID of a Mifare Classic 1k card, and for that I use this code:
private String getUID(){
MifareClassic mfc = MifareClassic.get((Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
byte[] data;
byte[] sevenDigits = null;
String uid;
try{
mfc.connect();
boolean auth = false;
auth = mfc.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);
if(auth){
data = mfc.readBlock(mfc.sectorToBlock(0));
for (int i =0; i < 8; i++){
sevenDigits[i] = data[i];
}
return getHexString(sevenDigits);
} else {
return "Authenticatie mislukt";
}
} catch (IOException e) {
return null;
}
}
Eclipse keeps giving me a warning about this line
for (int i = 0; i < 8; i++) {
sevenDigits[i] = data[i];
}
, saying that it can only be null at that point... My question is: how do i rewrite this code so that this warning goes away?

sevenDigits
is defined as null and not modified. You probably need to call
sevenDigits = new byte[data.length];
before the loop

You declare the sevenDigits[] as null you must initialize this by its size before you used it
sevenDigits[] = new byte[size];
do not use the static value in iterator for length use the length of array which you want to use in that for loop
data = mfc.readBlock(mfc.sectorToBlock(0));
sevenDigits[] = new byte[data.length];
for (int i =0; i < data.length; i++){
sevenDigits[i] = data[i];
}

Related

Conversion Error in TEIID during function call

I have following function defined in a java jar file within the vdb folder:
public static Blob createSampleLogCurve(String indexType, String indexUnit, String curveName, String curveUnit, String curveDataType, Object depthArray, Object valueArray) throws BulkDataException, SQLException { NullValueDef nullDef = new NullValueDef();
byte[] bytes = null;
nullDef.setNullFloat(-98765.0F);
double[] depths = (double[])((double[])depthArray);
int totalsamples = depths.length;
String dataType = DataType.FLOAT.toString();
double increment = depths[1] - depths[0];
for(int i = 0; i < totalsamples - 1; ++i) {
if (increment != depths[i + 1] - depths[i]) {
increment = 0.0D;
break;
}
}
if (curveDataType.equalsIgnoreCase("INT")) {
dataType = DataType.INT.toString();
} else if (curveDataType.equalsIgnoreCase("DOUBLE")) {
dataType = DataType.DOUBLE.toString();
} else {
dataType = DataType.FLOAT.toString();
}
CurveIndexProtoBuf indexProtobuf = new CurveIndexProtoBuf(depths[0], increment, totalsamples, indexType, indexUnit, depths);
List<CurveValueProtoBuf> values = new ArrayList();
values.add(new CurveValueProtoBuf(SampleType.VALUE.toString(), dataType, (String)null, curveUnit, 1, 1, (List)null, curveName, (Index)null, (Index)null, valueArray));
LogCurveProtoBuf logCurveProtobuf = new LogCurveProtoBuf(indexType.equals("DEPTH") ? IndexType.DEPTH.toString() : IndexType.TIME.toString(), indexProtobuf, values);
PipedInputStream in = new PipedInputStream(1024);
PipedOutputStream out = null;
try {
out = new PipedOutputStream(in);
logCurveProtobuf.build().writeDelimitedTo(out);
out.close();
bytes = IOUtils.toByteArray(in);
} catch (Exception var29) {
System.out.println(var29);
} finally {
try {
out.close();
in.close();
} catch (IOException var28) {
var28.printStackTrace();
}
}
return new SerialBlob(bytes)
}
This is how I have declared the UDF in DDL
CREATE VIRTUAL FUNCTION createSampleLogCurve(indexType string, indexUnit string, curveName string, curveUnit string, curveDataType string, depthArray double[], valueArray float[]) returns Blob
OPTIONS(JAVA_CLASS 'com.common.udf.ProtoBufFunctions', JAVA_METHOD 'createSampleLogCurve');
When I call the function from SQL client, I get below error. I also tried object and object[]
java.lang.ClassCastException: org.teiid.core.types.ArrayImpl cannot be cast to [D
Appreciate any help on this
Thanks
The issue is with this line
double[] depths = (double[])((double[])depthArray);
Either try changing the method signature to use double[] depthArray if that does not work, try casting to ArrayImpl like
either one of the above solutions will work!
if (depthArray instanceof ArrayImpl) {
ArrayImpl array = (ArrayImpl) depth array;
Object[] arrayVals = array.getValues();
for (int i = 0; i < arrayVals.length; i++) {
double val = arrayVals[i];
// do
}
}
one of the above solutions should work!

How to append only one line/row for each iteration in appending values to CSV file in Java

I am having some issues in terms of appending data into my CSV file. The problem is that whenever I try to append data into my CSV file on a second time, the second value which is appended to the CSV file comes with the first appended value. It's like it brings the existing value with it when appending to the CSV file. Thus, because of this issue, it results into an array index out of bounds exception in this statement: cust[read2DStringIndex][newVarIndexer] = fromfile[g]; , the data of the CSV file repeats the existing values along with the latest appended values and also the first value is only displayed on my GUI table.
CSV File:
Table:
Here's my source code in writing and reading the CSV:
public void writeCustomerCSV(){ // this creates a CSV file which stores the inputs of the user
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv",true)); // when I set append mode to true, cust[read2DStringIndex][newVarIndexer] = fromfile[g] results to index array out of bounds to 10
StringBuilder sb = new StringBuilder();
int y;
for(int x = 0; x < itemTo2D.length; x++){
if(itemTo2D[x][0] != null){
for(y = 0; y < itemTo2D[0].length; y++){
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
}
catch (Exception ex){
}
}
public void readCustomerCSV(){ // reads the contents of the CSV file
String[][] twoDArray = new String[10][7];
int read2DStringIndex = 0;
int newVarIndexer = 0;
DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel(); // table
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
int ak = 0;
int sk = 0;
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null){
fromfile = line.split(","); //separates the columns by a comma
for(int c = 0; c < fromfile.length; c++){
if(fromfile[c].equals("-")){
sk = 0;
ak++;
if(c > 0){
if(!fromfile[c-1].equals("-")){
id = id + 1;
}
}
} else{
twoDArray[ak][sk] = fromfile[c];
sk++;
}
}
}
} catch (Exception ex){
}
for(int g = 0; g < fromfile.length; g++){
if(fromfile[g].equals("-")){ //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
newVarIndexer = 0;
}
else{
cust[read2DStringIndex][newVarIndexer] = fromfile[g]; //cust is the 2D array(declared universal) which is going to display the values to the table
newVarIndexer++;
}
}
for(int h = 0; h < cust.length; h++){ //prints cust (2D array) , just to check what data is being stored
for(int p = 0; p < cust[0].length; p++){
System.out.println(cust[h][p] + ",");
}
}
setrowcount = 0;
for(int r = 0; r < cust.length; r++){
if(setrowcount == 0){
tblmodelll.setRowCount(0);
}
try{
if(cust[r][0].equals("null") == false){
tblmodelll.addRow(cust[r]); //displays the cust(2D array) data to table
}
} catch(Exception e){
}
setrowcount++;
}
}
Is there something missing in my structure of the codes or is my logic in appending the values not right?
Your responses would indeed help me in resolving this issue.
Thank you very much.

Cannot access the value of a StringBuilder in a heap dump in VisualVM

I am willing to write the value of a large StringBuilder with index 827 to disk. I am trying to do that using the following OQL:
map(heap.objects('java.lang.StringBuilder'),
function(it, index) {
if (index == 827.0) {
var writer = new java.io.FileWriter("/Users/username/output/sb_0x" + it.id.toString(16) + ".txt");
var chars = it.value;
for (var i = 0; i < chars.length; i++) {
writer.write(chars[i]);
}
writer.close();
}
return index;
})
However, nothing gets written. I now that the builder exists, since I have inspected it:
All StringBuilder objects
It seems that the result gets truncated after the builder with index 99 (i.e. it works for 99, but doesn't work for 100):
Truncated after 100
Any suggestions how can I get the value of the StringBuilder with id 827?
You can use the following query:
filter(heap.objects('java.lang.StringBuilder'),
function(it, index) {
if (index == 827.0) {
var writer = new java.io.FileWriter("/Users/username/output/sb_0x" + it.id.toString(16) + ".txt");
var chars = it.value;
for (var i = 0; i < chars.length; i++) {
writer.write(chars[i]);
}
writer.close();
return true;
}
return false;
})

Why am I getting duplicates when combining multiple ArrayLists?

Why I am getting duplicate entries in my ArrayList<String[]>?
allStepsJSONStringArray contains an array of single strings in the format of JSON
I loop through and pass each JSON string to a function that writes it to a temporary internal file
I read the file
Then pass it to getStepsArray() which breaks down the JSON string and puts each entry into a String[]
Loop to add to master ArrayList - allStepsArray
for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
writer.writeToInternal(allStepsJSONStringArray.get(i));
reader.readFromInternal(writer.filename);
stepsArray = reader.getStepsArray();
for (int s = 0; s < stepsArray.size(); s++) {
allStepsArray.add(stepsArray.get(s));
}
}
getStepsArray()
public ArrayList<String[]> getStepsArray() {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("steps");
String stepOrder = null;
String stepName = null;
String stepType = null;
String stepId = null;
String checklistId = null;
String checklistName = null;
for (int i = 0; i < jArray.length(); i++) {
stepOrder = jArray.getJSONObject(i).getString("order");
stepName = jArray.getJSONObject(i).getString("name");
stepType = jArray.getJSONObject(i).getString("type");
stepId = jArray.getJSONObject(i).getString("id");
checklistId = jObject.getString("checklistId");
checklistName = jObject.getString("checklistName");
stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
}
} catch (Exception e) {
e.printStackTrace();
}
return stepsArray;
}
Word for word:
Because you don't seem to ever reset stepsArray. The second time you add elements to it, the previous elements will still be there and will get added to allStepsArray again.

Writing to a text file using Java gets cut short

I have a program reading from a text file (currently 653 lines long) all separated by a comma. But when I go to save the file to a new location, it only saves 490 lines. It also seems that the last line in the newly created text file is cut in half. Any ideas on what might be the problem?
Here is the code that I used to open and sort the data in the list:
try {
scanner = new Scanner(file);
// Put the database into an array and
// Make sure each String array is 13 in length
while (scanner.hasNext()) {
line = scanner.nextLine();
word = line.split(",");
if (word.length < 13) {
String[] word2 = {"","","","","","","","","","","","",""};
for (int i = 0; i < word.length; i++) {
word2[i] = word[i];
}
dataBaseArray.add(word2);
}
else {
dataBaseArray.add(word);
}
}
}
catch (FileNotFoundException exc) {
JOptionPane.showMessageDialog(this, "File cannot be found.", "error finding file", JOptionPane.ERROR_MESSAGE);
}
// Splitting the database into vacant numbers/dead lines/vacant cubicles
for (int i = 0; i < dataBaseArray.size(); i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
vacantNums.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
deadLines.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
vacantCubs.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[7].equals("")) {
people.add(dataBaseArray.get(i));
}
else {
people.add(dataBaseArray.get(i));
}
}
// Resetting the DB Array to put the values back in it
dataBaseArray = new ArrayList<>();
// Ordering the arrays I want them to appear in the list
// Orering the people to appear in alphabetical order
Collections.sort(people, new Comparator<String[]>() {
#Override
public int compare(String[] strings, String[] otherStrings) {
return strings[7].compareTo(otherStrings[7]);
}
});
// Put the people in the DB Array
for (int i = 0; i < people.size(); i++) {
dataBaseArray.add(people.get(i));
}
// Put the vacant numbers in the AB Array
for (int i = 0; i < vacantNums.size(); i++) {
dataBaseArray.add(vacantNums.get(i));
}
// Put the vacant cubicles in the AB Array
for (int i = 0; i < vacantCubs.size(); i++) {
dataBaseArray.add(vacantCubs.get(i));
}
// Put the dead lines in the AB Array
for (int i = 0; i < deadLines.size(); i++) {
dataBaseArray.add(deadLines.get(i));
}
list = new String[dataBaseArray.size()];
// Add the DB Array to the list
for (int i = 0; i < list.length; i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
list[i] = "VACANT";
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
list[i] = "DEAD";
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
list[i] = "Vacant Cubicle";
}
else if (dataBaseArray.get(i)[7].equals("")) {
list[i] = dataBaseArray.get(i)[6];
}
else {
list[i] = dataBaseArray.get(i)[7] + ", " + dataBaseArray.get(i)[6];
}
}
// Populate the list
lstAdvance.setListData(list);
Here is what I used to save the file:
try {
saveFile = new FileWriter("Save Location");
String newLine = System.getProperty("line.separator");
for (int i = 0; i < dataBaseArray.size(); i++) {
for (int j = 0; j < dataBaseArray.get(i).length; j++) {
saveFile.append(dataBaseArray.get(i)[j] + ",");
}
saveFile.append(newLine);
}
}
catch (IOException exc) {
JOptionPane.showMessageDialog(this,"error", "error", JOptionPane.ERROR_MESSAGE);
}
Writing to a file is buffered. You have to close() or flush() your writer (saveFile) at the end of writing.
Even better: you should do close() on your writer in the finally block.
Try it using the FileWriter and BufferedWriter....
File f = new File("Your_Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
And yes..its very important to do bw.close() (Closing the Buffer)
See this question : Java FileWriter with append mode
The problem is that your FileWriter object needs to be "append mode" . Then, you append to the file with the "write" method rather than the "append" method. Use a finally catch clause to call "close" . You don't need to flush ( I dont think).

Categories