J2me RecordStore error : java.lang.NullPointerException: 0 - What is wrong in below code

1.1k views Asked by At

Is there anything wrong in function shown below. The only bug that I found while running this code in debugger is "java.lang.NullPointerException: 0". I wasted my last many hours in figuring out "what is causing this error", Somebody pls help.

 public String[] addRECORD(String mydata){
            String[] output = null;
        try {
            RecordStore rs = null;
            String sb = null;
            RecordStore.openRecordStore(REC_STORE, true);
            if (mydata.equals("Logged")) {
                      byte[] recData = new byte[5];
                      int len;
                      for(int i = 1; i <= rs.getNumRecords(); i++){
                          if(rs.getRecordSize(i) > recData.length){
                          recData = new byte[rs.getRecordSize(i)];
                          }
                          len = rs.getRecord(i, recData, 0);
                          sb += new String(recData, 0, len);
                      }
                if (sb != null) {
                    output[0] = "rexists";
                    output[1] = sb.trim();
                } else {
                    output[0] = "notlogged";
                    output[1] = sb.trim();
                }
            }else{
                  byte[] rec = mydata.getBytes();
                  try{
                  rs.addRecord(rec, 0, rec.length);
                  }catch (Exception e){}
                    output[0] = "radded";
                    output[1] = mydata;
                }
                rs.closeRecordStore();
        } catch (RecordStoreException ex) {
            responder(ex.getMessage());
        }
            return output;
    }
2

There are 2 answers

1
Zohaib On BEST ANSWER

First Null pointer exception can come here, if string passed to the function is null

 if (mydata.equals("Logged")) {

change this to if ("Logged".equals(myData)) {

Second Null pointer Exception can come here, you cannot invoke function on null object

for(int i = 1; i <= rs.getNumRecords(); i++){

Initialize rs

Third NUll pointer exception can come here

output[0] = "rexists";
output[1] = sb.trim();

because array output is not initialized, initialize array as String [] output = new String[2]

0
Albert Tedja On

Change this:

RecordStore.openRecordStore(REC_STORE, true);

To this:

rs = RecordStore.openRecordStore(REC_STORE, true);