Cdn_Dev
Cdn_Dev

Reputation: 765

Adding static JSON to an Android Studio project

I'd like to add static JSON to an Android Studio project which can then be referenced throughout the project. Does anyone know the best method of doing this?

In more detail what I'm trying to do is this: 1) Pull data out of the Google Places API 2) Find Google places that match with places in a static JSON object 3) Place markers on a map based on the matches

I have numbers 1 and 3 working, but would like to know the best way of creating a static (constant) JSON object in my project and using it for step 2.

Upvotes: 4

Views: 13460

Answers (3)

SzabK
SzabK

Reputation: 105

You should replace the String datatype to StringBuilder in the while loop for the properly optimized solution. So in the while loop instead of concatenating you would append the readString to the str StringBuilder.

str.append(readString);

Upvotes: 0

Cdn_Dev
Cdn_Dev

Reputation: 765

The answer posted above is indeed what I'm looking for, but I thought I'd add some of the code I implemented to help others take this problem further:

1) Define JSON object in a txt file in the assets folder

2) Implement a method to extract that object in string form:

private String getJSONString(Context context)
{
    String str = "";
    try
    {
        AssetManager assetManager = context.getAssets();
        InputStream in = assetManager.open("json.txt");
        InputStreamReader isr = new InputStreamReader(in);
        char [] inputBuffer = new char[100];

        int charRead;
        while((charRead = isr.read(inputBuffer))>0)
        {
            String readString = String.copyValueOf(inputBuffer,0,charRead);
            str += readString;
        }
    }
    catch(IOException ioe)
    {
        ioe.printStackTrace();
    }

    return str;
}

3) Parse the object in any way you see fit. My method was similar to this:

public void parseJSON(View view)
{
    JSONObject json = new JSONObject();

    try {
        json = new JSONObject(getJSONString(getApplicationContext()));
    } catch (JSONException e) {
        e.printStackTrace();
    }

   //implement logic with JSON here       
}

Upvotes: 8

user468311
user468311

Reputation:

You can just place your JSON file into assets folder. Later on you'll be able to read the file, parse it and use values.

Upvotes: 7

Related Questions