Question

I try to get an Json object via Spring4Android, that works so far.

But I also want it to add this object to the sqlite database on the android device. I want to make this with greendao, it seems as like as my sql query is valid as well (looked in debugger). But nevertheless my DB is still null and I don't know why. I tried with Greendao helper and direct via SQLiteOpenHelper. Also I made my connector a singleton and made the db static.

My JSON class

package org.springframework.android.showcase.rest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.android.showcase.AbstractAsyncListActivity;
import org.springframework.android.showcase.R;
import org.springframework.android.showcase.greendao.DBConnector;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.os.Looper;


public class HttpGetJsonActivity extends AbstractAsyncListActivity {


    protected static final String TAG = HttpGetJsonActivity.class.getSimpleName();

    // ***************************************
    // Activity methods
    // ***************************************
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();

        // when this activity starts, initiate an asynchronous HTTP GET request
        new DownloadStatesTask().execute();
    }

    // ***************************************
    // Private methods
    // ***************************************
    private void refreshStates(List<SurveyQuestion> SurveyQuestion) {
        if (SurveyQuestion == null) {
            return;
        }

        StatesListAdapter adapter = new StatesListAdapter(this, SurveyQuestion);
        setListAdapter(adapter);
    }

    // ***************************************
    // Private classes
    // ***************************************
    private class DownloadStatesTask extends AsyncTask<Void, Void, List<SurveyQuestion>> {

        @Override
        protected void onPreExecute() {
            showLoadingProgressDialog();
        }

        @Override
        protected List<SurveyQuestion> doInBackground(Void... params) {
            try {

                Handler mHandler = new Handler(Looper.getMainLooper());
                final ArrayList<SurveyQuestion> surveyQuestions = new ArrayList<SurveyQuestion>();
                // The URL for making the GET request
                final String url = getString(R.string.base_uri) + "/resource/json";

                // Set the Accept header for "application/json"
                HttpHeaders requestHeaders = new HttpHeaders();
                List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
                acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
                requestHeaders.setAccept(acceptableMediaTypes);

                // Populate the headers in an HttpEntity object to use for the request
                HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

                // Create a new RestTemplate instance
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

                // Perform the HTTP GET request
                ResponseEntity<SurveyQuestion[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
                        SurveyQuestion[].class);

                List list = Arrays.asList(responseEntity.getBody());
                for (Object obj : list) {
                    surveyQuestions.add((SurveyQuestion) obj);
                }


                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        for (SurveyQuestion surveyQuestion : surveyQuestions) {

                            System.out.println(surveyQuestion);
                            DBConnector.getInstance().addNote(surveyQuestion);

                        }
                    }
                });


                // convert the array to a list and return it
                return list;
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }

            return null;
        }


        @Override
        protected void onPostExecute(List<SurveyQuestion> result) {
            dismissProgressDialog();
            refreshStates(result);
        }

    }

}

My Connector class

package org.springframework.android.showcase.greendao;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


import org.springframework.android.showcase.rest.SurveyQuestion;



public class DBConnector extends ListActivity {

    private static SQLiteDatabase db;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;
    private static NoteDao noteDao;

    private static Cursor cursor;

    private static DBConnector connector;

    private DBConnector() {
        init();
    }


    private void init() {


        //direct try
        SQLiteOpenHelper helper2 = new SQLiteOpenHelper(this, "ecm_politik_mt", null,3) {
            @Override
            public void onCreate(SQLiteDatabase db) {
                System.out.println("onCreate: "+db);
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                System.out.println("onCreate: "+db);
            }
        };
        db = helper2.getWritableDatabase();

        //Greendao
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "ecm_politik_mt", null);

        db = helper.getWritableDatabase();

        daoMaster = new DaoMaster(db);

        daoSession = daoMaster.newSession();

        noteDao = daoSession.getNoteDao();


    }

    public static DBConnector getInstance() {
        if (connector == null)
            connector = new DBConnector();
        return connector;
    }

    public void addNote(SurveyQuestion surveyQuestion) {

        Note note = new Note();
        note.setId(surveyQuestion.getId());
        note.setSheet_id(surveyQuestion.getSheet_id());
        note.setTitle(surveyQuestion.getTitle());
        note.setFreetext((surveyQuestion.getFreetext()) ? 1l : 0l);
        note.setMultiplechoice((surveyQuestion.getMultiplechoice()) ? 1l : 0l);
        note.setIdx(surveyQuestion.getIdx().longValue());
        note.setMandatory((surveyQuestion.getMandatory()) ? 1l : 0l);
        System.out.println(note);
        noteDao.insert(note);

        System.out.println("Inserted new note, ID: " + note.getId());

        cursor.requery();
    }


}
Was it helpful?

Solution

Since your DBConnector isn't managed by the android-system, but you just create it via new, I think the context won't be valid for usage in any method.

Write a class extending OpenHelper to implement your costum-db-schema-update mechanism.

You can implement this class as singleton or store the instance in a costum application class.

As context for things that are not bound to a single activity you should use the application context. Otherwise memoryleaks may be the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top