androidjsonmicrosoft-bandgson

How to convert object to GSON(JSON) in the right way?


I have problem to convert bandClient Object into JSON (i want to save object for later usage in the SHARED PREFS (ANDROID) ).

I tried to do it by using GSON, but during execution

String json = gson.toJson(bandClient);

I always get following exception:

Process: xxr.com.mitracker, PID: 19040 java.lang.StackOverflowError at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380) at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375) at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380) at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375) at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)

How can i solve it in the right way please?

Many thanks for any advice

Method code:

private AdapterView.OnItemClickListener onListItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            BandInfo[] pairedBands =
                    BandClientManager.getInstance().getPairedBands();

            Logger.d("Clicked on item " + position);
            final BandClient bandClient =
                    BandClientManager.getInstance().create(context, pairedBands[position]);
            //mBandList.get(position).getBandClient();

            MsBandHelperAssync asyncTask = new MsBandHelperAssync(new AsyncResponse() {
                @Override
                public void processFinish(Boolean output) {
                    try {
                        Logger.d("RETURNED " + output);
                        Gson gson = new Gson();
                        Logger.d("PLAIN OBJECT" + bandClient);
                        gson.toJsonTree(bandClient);
                        Logger.d("PASSED");
                        String json = gson.toJson(bandClient);
                        Logger.d("PASSED JSON" + json);
                        //Prefs.putString(Constants.Global.SHARED_PREFS_KEY_PAIRED_DEVICES, json);
                        Logger.d("Saved");
                        //CommonHelper.redirectToActivity(context, mActivity, DashboardActivity.class);
                    } catch (Exception e) {
                        Logger.e(e.getMessage());
                    }

                }
            });
            asyncTask.execute(bandClient);

Solution

  • A BandClient represents a connection to the BandService held by Micrsoft Health. Thus it holds a reference to the activity, service, or application context used to create it. And it won't work if you save it for later use.

    So, instead, you will probably want to save the mac address of the BandInfo object associated with the BandClient you want to save and then recreate the BandClient when you want to use it.