开发者

Saving List to a File android

*INITIALIZE VARIABLES

String serfilename;

List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>();

ON CREATE METHOD

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.addscreen);
//getPainItems from the saved file
if(loadListFromFile((ArrayList<HashMap<String, String>>) painItems) != 
      null)
    painItems = loadListFromFile((ArrayList<HashMap<String, String>>) 
        painItems);
}

LOAD LIST FROM FILE开发者_JAVA百科 METHOD

private ArrayList<HashMap<String, String>> loadListFromFile(

    ArrayList<HashMap<String, String>> masterlistrev) {
try {

    FileInputStream fis = openFileInput(serfilename);
    ObjectInputStream ois = new ObjectInputStream(fis);
    masterlistrev = (ArrayList<HashMap<String, String>>) ois.readObject();
 } catch (Exception e) {
    e.printStackTrace();
 }
return masterlistrev;
}

WRITE LIST TO FILE METHOD

private void writeListToFile(ArrayList<HashMap<String, String>> masterlistrev){

    File myfile = getFileStreamPath(serfilename);
    try {
        if(myfile.exists() || myfile.createNewFile()){
            FileOutputStream fos = openFileOutput(serfilename, MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(masterlistrev);
     }
 } catch (Exception e) {
     e.printStackTrace();
 }

 }

ONSTOP() METHOD

 protected void onStop(){
    super.onStop();
    writeListToFile((ArrayList<HashMap<String, String>>) painItems);
}

I am getting a NULL Pointer exception at File myfile = getFileStreamPath(serfilename);. How do I fix this.. is there a better way to do this...?


Based on what you have pasted, your serfilename is null and is never set to a path.

That said, even without all that,

File myfile = getFileStreamPath(serfilename);

would be expected to throw a NullPointerException due to your (null) input.

Convince yourself. Try:

if(null == serfilename)
    throw new RuntimeException ("serfilename is null!");

File myfile = getFileStreamPath(serfilename);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜