Sugar ORM is not saving data into the database
Asked Answered
B

1

6

I am currently using Sugar ORM and Android Async Http Client for my Android application.

I read through the documentation of Sugar ORM and did exactly what is written there. My HttpClient is using the singleton pattern and provides methods for calling some APIs.

Now comes the bad part about it. I am not able to save the data persistently into my database which is created by Sugar ORM. Here is the method, that is calling an API:

public void getAvailableMarkets(final Context context, final MarketAdapter adapter) {
        String url = BASE_URL.concat("/markets.json");
        client.addHeader("Content-Type", "application/json");
        client.addHeader("Accept", "application/json");

        client.get(context, url, null, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {

                Log.i(TAG, "Fetched available markets from server: " + response.toString());


                Result<Markets> productResult = new Result<Markets>();
                productResult.setResults(new Gson().<ArrayList<Markets>>fromJson(response.toString(),
                        new TypeToken<ArrayList<Markets>>() {
                        }.getType()));
                ArrayList<Markets> marketsArrayList = productResult.getResults();

                // This lines tells me that there are no entries in the database
                List<Markets> marketsInDb = Markets.listAll(Markets.class);

                if(marketsInDb.size() < marketsArrayList.size() ||
                        marketsInDb.size() > marketsArrayList.size()) {

                    Markets.deleteAll(Markets.class);

                    for(Markets m : marketsArrayList) {
                        Markets market = new Markets(m.getId(), m.getName(), m.getChainId(), m.getLat(),
                                m.getLng(), m.getBusinessHourId(), m.getCountry(), m.getZip(), m.getCity(),
                                m.getStreet(), m.getPhoto(), m.getIcon(), m.getUrl());

                        market.save();

                        adapter.add(market);
                    }

                    adapter.notifyDataSetChanged();

                } 

                List<Markets> market = Markets.listAll(Markets.class);
                // This lines proves that Sugar ORM is not saving the entries   
                Log.i(TAG, "The market database list has the size of:" + market.size());
            }
        });
    }

This is what Logcat is printing:

D/Sugar: Fetching properties
I/Sugar: Markets saved : 3
I/Sugar: Markets saved : 5
I/RestClient: The market database list has the size of:0

Also I took a look at the Sugar ORM tag here at stackoverflow, but no answers or questions could give me a hint on how to solve that problem. I am a newbie to the android ecosystem and would love any help of you guys to solve this problem. Thanks in advance

Bridal answered 1/10, 2014 at 21:20 Comment(0)
W
10

I just solve it the same problem as you have. It was a pain in the neck but after few hours I find out what caused this problem.

Using Sugar ORM you must not set id property as it's belongs to SugarRecord class, otherwise ORM will try to update objects instead of insert them. As I need to have field with my object id, I used json annotation to assign it to another field. Last step was configure GSON to exclude fields without Expose annotation.

So my class looks like one below now:

public class MyClass
{
    @Expose
    @SerializedName("id")
    private long myId;
    @Expose 
    private String field1;
    @Expose
    private String field2;
    @Expose
    private byte[] field3;
    @Expose
    private double field4;

    public MyClass() { }

    // parametrized constructor and more logic  

}

Cheers!

Windbreak answered 2/12, 2014 at 23:24 Comment(5)
You are right. I solved this issue a while ago but forgot to add the solution to this thread. Here is the issue site on github of SugarORM: github.com/satyan/sugar/issues/171Bridal
So we cannot control the id ourselves?Midnight
@DeanWild unfortunately not. As this question has over 2500 Views, I wanted to tell you guys, that I switched from SQLite and SugarORM to Realm.io and I have to say it has a been a very good choice for me. Realm is an Object-oriented Database and you can use it for Android and iOS Development as well.Bridal
Haha I went from Realm to SugarORM! At first I was very pleased with Realm (particularly the performance) but after I while I had issues with it's threading rules. If you retrieve an object using realm on one thread and then try to access that object from another thread it will not work. This quickly became a big issue for me. It doesn't allow me to write a traditional Database "layer" for instance.Midnight
I totally agree with you, that querying and accessing objects from Realm is an issue, but it seems the Realm Core Developers are working on it. Take a look here: github.com/realm/realm-java/issues/1208Bridal

© 2022 - 2024 — McMap. All rights reserved.