0

创建数据库和表成功。我的 DatabaseHandler 类的 onCreate():

public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) 
    {
         try
         {  

            TableUtils.createTable(connectionSource, Category.class);
            TableUtils.createTable(connectionSource, Level.class);
            DataParsing a = new DataParsing();
            a.fillCategories();
            Log.i(DatabaseHandler.class.getName(), "created new entries in onCreate: " );
         }
         catch (SQLException e){
             Log.e(TAG, "error creating DB " + DATABASE_NAME);
             throw new RuntimeException(e);
         } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

我从 Web 服务获取数据 JSON 并使用 GSON 解析它。数据在 fillcategories() 方法中成功填充类数据。然后我想在 saveContacts() 方法中将所有数据放入 ORMLite 数据库:

    public class DataParsing {
    private static String KEY_STATUS = "status";
    private static String KEY_MESSAGE = "message";
    private static String KEY_CATEGORIES = "categories";
    private static String KEY_DATA = "data";
    private DatabaseHandler databaseHandler;
    private Context _context;
    public void fillCategories() throws JSONException, SQLException
    {   UserFunctions userFunction  = new UserFunctions();
        JSONObject json = userFunction.loginUser("shurko@ukr.net", "123456");
        JSONObject data = json.getJSONObject(KEY_DATA);
        // getting categories
        JSONArray categories = new JSONArray();
        categories = data.getJSONArray(KEY_CATEGORIES);
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(categories.toString()).getAsJsonArray();
        Type listType = new TypeToken<List<Category>>() {}.getType();
        List<Category> tasks = new ArrayList<Category>();
        tasks = gson.fromJson(array.toString(), listType);

        saveContacts(tasks);

    }

    public void saveContacts(List<Category> contacts) throws SQLException
        {

            OrmLiteSqliteOpenHelper dbHelper= DatabaseHandler.getInstance(_context);
            Dao<Category, Integer> daoContact=dbHelper.getDao(Category.class);

            QueryBuilder<Category, Integer> queryBuilder = daoContact.queryBuilder();
            Log.i("dao",queryBuilder.selectColumns("title").prepare().toString());


            for (Category contact : contacts) {
                Log.i("dao",contact.toString());
                HelperFactory.GetHelper().getCategoryDao().create(contact);
            }

        }


}

并在 ...create(contact) 行上获取一组异常:

    FATAL EXCEPTION: main
 java.lang.NullPointerException
    at com.library.DataParsing.saveContacts(DataParsing.java:61)
at com.library.DataParsing.fillCategories(DataParsing.java:45)
    at com.library.DatabaseHandler.onCreate(DatabaseHandler.java:85)
    at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.onCreate(OrmLiteSqliteOpenHelper.java:169)
    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
    at com.j256.ormlite.android.AndroidConnectionSource.getReadWriteConnection(AndroidConnectionSource.java:63)
    at com.j256.ormlite.android.AndroidConnectionSource.getReadOnlyConnection(AndroidConnectionSource.java:51)
    at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java:202)
    at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:155)
    at com.j256.ormlite.stmt.StatementExecutor.queryForAll(StatementExecutor.java:113)
    at com.j256.ormlite.dao.BaseDaoImpl.queryForAll(BaseDaoImpl.java:237)
    at com.assignmentexpert.LoginActivity$1.onClick(LoginActivity.java:97)
    at android.view.View.performClick(View.java:2485)
    at android.view.View$PerformClick.run(View.java:9080)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:3687)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    at dalvik.system.NativeStart.main(Native Method)

为什么会这样?

4

1 回答 1

0

通过将我的活动上下文传递给 OrmLiteSqliteOpenHelper 解决了问题。我使用这些类在应用程序生命周期中维护对数据库的访问:

public class ApplicationMemory extends Application{

   @Override
   public void onCreate() {
       super.onCreate();
       HelperFactory.SetHelper(getApplicationContext());
   }
   @Override
   public void onTerminate() {
       HelperFactory.ReleaseHelper();
       super.onTerminate();
   }
}

 public class HelperFactory {
 private static DatabaseHandler databaseHelper;

   public static DatabaseHandler GetHelper(){
       return databaseHelper;
   }

public static void SetHelper(Context context){
       databaseHelper = OpenHelperManager.getHelper(context,DatabaseHandler.class);
   }

public static void ReleaseHelper(){
       OpenHelperManager.releaseHelper();
       databaseHelper = null;
   }
   }

其中 DatabaseHandler - 类,从 OrmLiteSqliteOpenHelper 扩展并在我的问题中描述。

于 2012-08-14T08:45:23.870 回答