Android在离线时从sqlite读取数据

时间:2013-12-22 16:56:10

标签: android sqlite nullpointerexception android-sqlite

当我在线时,我将所有数据存储在sqlite数据库中,然后当我离线时,我尝试每次都读取存储的数据库。

 if(isOnline(getActivity()))

        {
            db = new DataBaseHandler(getActivity());
            getDataInAsyncTask();
            storeData(db);
            //db.close();
        }
        else
                    {

        Toast.makeText(getActivity(), "No internet",
                    Toast.LENGTH_LONG).show();

            try {
                db.openDataBase();
            } catch (SQLException sqle) {
                throw sqle;
            }
            getDataInDataBase(db);
            flag=0;
        }

在else条件即离线模式下我执行db.openDataBase()以在线模式下打开/加载早期实现的数据库db

   public void openDataBase() throws SQLException{

        //Open the database
     String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);}

db.openDataBase给出nullpointerException

我哪里错了?加载/打开已经构建的数据库db的方法是对的吗?

2 个答案:

答案 0 :(得分:1)

您从未初始化 db 对象。

放线

  

db = new DataBaseHandler(getActivity());

在if / else语句之前或在try / catch语句中的

答案 1 :(得分:0)

  /*
   * intitlize object globaly
  **/
   db = new DataBaseHandler(getActivity()); 
   if(isOnline(getActivity()))

    {
       /**
        *  look at these you are
        *  intialize object when is online
        */
        //db = new DataBaseHandler(getActivity()); 
        getDataInAsyncTask();
        storeData(db);
        //db.close();
    }
    else
                {

    Toast.makeText(getActivity(), "No internet",
                Toast.LENGTH_LONG).show();

        try {
            db.openDataBase();
        } catch (SQLException sqle) {
            throw sqle;
        }
        getDataInDataBase(db);
        flag=0;
    }