Search code examples
androidstorageread-writedata-dictionary

how to read/write data dictionary in android programmatically


I want to read/write data dictionary in file which is in android internal/external memory. In WP7, they have used IsolatedStorage for storing the dictionary directly. In IOS, they can write NSDictionary directly to the file. Please anyone tell me the way to write DataDictionary into file.

Note: I have the keys and values in the Map variable. how to store this Map directly to file


Solution

  • I would suggest putting your words into a database for the following reasons

    DB lookups on android with SQLite are "fast enough" (~1ms) for even
    the most impatient of users

    Reading large files into memory is a dangerous practice in memory-limited environments such as android.

    Trying to read entries out of a file "in place" rather than "in
    memory" is effectively trying to solve all the problems that SQLite
    already solves for you.

    Embed a database in the .apk of a distributed application [Android]

    You can find more detailed examples by searching object serialization

    [EDIT 1]

    Map map = new HashMap();
    map.put("1",new Integer(1));
    map.put("2",new Integer(2));
    map.put("3",new Integer(3));
    FileOutputStream fos = new FileOutputStream("map.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(map);
    oos.close();
    
    FileInputStream fis = new FileInputStream("map.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Map anotherMap = (Map) ois.readObject();
    ois.close();
    
    System.out.println(anotherMap);
    

    [EDIT 2]

    try {
    
            File file = new File(getFilesDir() + "/map.ser");
    
            Map map = new HashMap();
            map.put("1", new Integer(1));
            map.put("2", new Integer(2));
            map.put("3", new Integer(3));
            Map anotherMap = null;
    
            if (!file.exists()) {
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(map);
                oos.close();
    
                System.out.println("added");                
            } else {
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                anotherMap = (Map) ois.readObject();
                ois.close();
    
                System.out.println(anotherMap);
            }
    
    
    
        } catch (Exception e) {
    
        }
    

    [EDIT 3]

    Iterator myVeryOwnIterator = meMap.keySet().iterator();
    while(myVeryOwnIterator.hasNext()) {
        String key=(String)myVeryOwnIterator.next();
        String value=(String)meMap.get(key);
    
         // check for value
    
    }