简体   繁体   中英

where should I put json data inside android

I am planning to store some data in json in that way I can read and write this json data. I want to use it as a simple database instead of using sqlite .

Where should I create this json data in file hierarchy and how to write and read data from json .

just declare a string variable and then set that to your json like :

String myjson = "obj1: {}..."  //it is your json

JsonObject obj = new JsonObject(myJson);

then you can do

String s = obj.getString("key");

This is a very nice question for a beginner in Android so I will tell you about singleton class which we use to store data in any language.

"Singleton class" this is a class which have only one reference (object). Code how to make this class is below:

public class DataController {

    private static DataController ref;

    public static DataController getInstance()
    {
        if(ref==null)
            ref = new DataController();

        return ref;
    }

    public void deleteInstance()
    {
        ref=null;
    }
    public ArrayList<MediaWrapper>videoWrapper = new ArrayList<MediaWrapper>();
    public ArrayList<MediaWrapper>audioWrapper = new ArrayList<MediaWrapper>();
    public ArrayList<MediaWrapper>documentWrapper = new ArrayList<MediaWrapper>();
}// you can add any data type under this class

Now anywhere you can use this class like this put this code inside your activity on-create method where you want to use this.

private DataController controller;
    controller = DataController.getInstance();

Now just call that datatype in which you want to add your data like this.

controller.videoWrapper = //put your data inside this. This data will be save until or unless your activity in the stack

Also you can access that data like this controller.videoWrapper it will give you all data which you save in this.

Have you checked out google-gson library, which is a very useful class libray which can be used in Android. Check these links link 1 | link 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM