Android Greendao,数据库无法打开

时间:2013-12-27 10:25:56

标签: android json sqlite greendao

我尝试通过Spring4Android获取一个Json对象,到目前为止一直有效。

但我也希望它将此对象添加到Android设备上的sqlite数据库中。 我想用greendao做这个,看起来像我的sql查询也是有效的(在调试器中看)。但是我的数据库仍然是空的,我不知道为什么。 我尝试使用Greendao助手并通过SQLiteOpenHelper直接进行。 此外,我使连接器成为单例,并使db静态。

我的JSON课程

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);
        }

    }

}

我的连接器类

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();
    }


}

1 个答案:

答案 0 :(得分:0)

由于您的DBConnector不是由android系统管理的,但您只是通过new创建它,我认为上下文无法在任何方法中使用。

编写一个扩展OpenHelper的类来实现costum-db-schema-update机制。

您可以将此类实现为singleton或将实例存储在costum应用程序类中。

作为未绑定到单个活动的事物的上下文,您应该使用应用程序上下文。否则可能是记忆泄漏。