如何检查sqlite数据库中的表是否存在,是否创建并插入数据

时间:2022-09-25 23:25:36

I am now writing an app which needs some prepared data in the database, I tried the method from this question

我现在正在写一个需要数据库中准备数据的app,我尝试了这个问题中的方法

Ship an application with a database

使用数据库发送应用程序

and it turn out you can't copy database in android 2.3.

结果显示你无法在android 2.3中复制数据库。

So I set up a splash screen and want to run some data initialisation there.

所以我设置了一个启动屏幕,并想在那里运行一些数据初始化。

I tried Thread and Asyctask but still getting this curious problem that my insert_data method keep getting exception

我尝试了Thread和Asyctask,但仍然遇到了这个奇怪的问题,我的insert_data方法一直有异常

It's getting me mad,plz help

我快疯了,求求你

Splash.java

Splash.java

public class Splash extends Activity {

     private ChannelDB mDB;
     private TextView loading;
     private String channelS_TABLE;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);  
        new SetDB().execute();

    }

    private class SetDB extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            try {
                Log.d("Splash","table check not running yet");
                if (tabIsExist(channelS_TABLE) != true ){
                    Log.d("Splash","table check complete and not exist");
                    mDB.Reset();
                    Log.d("Splash","database reset");
                      some data insert
                     ));
                }else{
                    synchronized(this){
                        Log.i("Splash", "the table is there");
                        wait(3000);}
                    Intent i = new Intent();
                    i.setClassName("com.appkon.hdtvs",
                                   "com.appkon.hdtvs.HDtvs");
                    finish();
                    startActivity(i);
                }   
               }catch (Exception e) {

                    Log.i("Splash", "setDB exception");
                        Intent i = new Intent();
                        i.setClassName("com.appkon.hdtvs",
                                       "com.appkon.hdtvs.HDtvs");
                        finish();
                        startActivity(i);
                    }
            return null;
        }


        protected void onPreExecute(String load) {

        }

        protected void onPostExecute(String finish) {
             Intent i = new Intent();
             i.setClassName("com.appkon.hdtvs",
                            "com.appkon.hdtvs.HDtvs");
             finish();
             startActivity(i);
        }
    }


        public boolean tabIsExist(String tableName){
            boolean result = false;
            if(tableName == null){
                    return false;
            }
            Cursor cursor= ChannelDB.check();
            startManagingCursor(cursor);
            try {
                    if(cursor.moveToNext()){
                            int count = cursor.getInt(0);
                            if(count>0){
                                    result = true;
                            }
                    }

            } catch (Exception e) {
                Log.e(this.toString(),"error:"+e.toString());
                Intent intent = new Intent(this,HDtvs.class);  
                startActivity(intent);  
                this.finish(); 
                Log.d("Splash","tabIsExist Exception");
            }                
            return result;
        }


    }

Error track

错误跟踪

12-05 07:52:20.542: INFO/System.out(575): debugger has settled (1460)
12-05 07:52:21.442: DEBUG/dalvikvm(575): GC freed 679 objects / 53552 bytes in 135ms
12-05 07:52:21.932: DEBUG/Splash(575): table check not running yet
12-05 07:52:21.932: DEBUG/Splash(575): table check complete and not exist
12-05 07:52:21.932: INFO/Splash(575): setDB exception
12-05 07:52:21.982: INFO/ActivityManager(51): Starting activity: Intent { cmp=com.appkon.hdtvs/.HDtvs }
12-05 07:52:22.482: WARN/ActivityManager(51): Duplicate finish request for HistoryRecord{44d4aa10 com.appkon.hdtvs/.Splash}
12-05 07:52:22.502: INFO/ActivityManager(51): Starting activity: Intent { cmp=com.appkon.hdtvs/.HDtvs }

Thx for Bindal's great solution, but I still have a problem, I defined a method to add entry in my database helper class and insert data into database using it, but it seems not working

对于Bindal的伟大解决方案,但是我仍然有一个问题,我定义了一个方法,在我的数据库助手类中添加条目,并使用它将数据插入到数据库中,但是它似乎不起作用。

this is my method defined in databasehelper class

这是我在databasehelper类中定义的方法

 public void createchannelEntry(ChannelPoster channel) {
        openDB();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        channel.getPoster().compress(Bitmap.CompressFormat.PNG, 100, out);
        ContentValues cv = new ContentValues();
        cv.put(KEY_POSTER, out.toByteArray());            
        cv.put(KEY_CHANNEL, channel.getChannel());
        cv.put(KEY_PATH, channel.getPath());
        cv.put(KEY_DBLINK, channel.getDBlink());

        mDb.insert(channelS_TABLE, null, cv);
        closeDB();
    }

this is how I insert data

这就是我插入数据的方式

Bitmap sherlock = BitmapFactory.decodeResource(getResources(), R.drawable.sherlock);

mDB.createchannelEntry(new ChannelPoster(aa, "aa" ,"ll"  ,"ha" ));

and I have a JavaBean for holding an entry

我有一个用于保存条目的JavaBean

public class ChannelPoster {
    private Bitmap poster;
    private String channel;
    private String path;
    private String dblink;

    public ChannelPoster(Bitmap pi, String c, String p, String d) {
        poster = pi;
        channel = c;
        path = p;
        dblink = d;
    }

    public Bitmap getPoster() { return poster; }
    public String getChannel() { return channel; }
    public String getPath() { return path; }
    public String getDBlink() { return dblink; }
}

Now I am adding Logcat record here

现在我在这里添加Logcat记录。

this is my codes here

这是我的代码

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);  
        try {
            createDataBase();
        } catch (Exception e) {
               Intent intent = new Intent(this,HDtvs.class);  
               startActivity(intent);  
               this.finish(); 
               Log.d("Splash","createDataBaseException");
        }
    }

    public void createDataBase() throws Exception 
    {
       boolean dbExist = checkDataBase();
       if (dbExist){
           Intent intent = new Intent(this,HDtvs.class);  
           startActivity(intent);  
           this.finish(); 
           Log.d("Splash","table exist");
       }
       else
       {
           try{
                mDB.Reset();
                Log.d("Splash","database reset");
                Bitmap bigbang1 = BitmapFactory.decodeResource(getResources(), R.drawable.bigbang1);


                mDB.createchannelEntry(new ChannelPoster(bigbang1, "生活大爆炸(第一季)" ,"http://appkon.com/hdtvs/channel/bigbang1.xml"  ,"http://movie.douban.com/subject/5372374/" ));

           }catch (Exception e){
               Log.d("splash","data insert exception");
               Intent intent = new Intent(this,HDtvs.class);  
               startActivity(intent);  
               this.finish(); 
           }
       }
    }

   /**
    * Check if the database already exist to avoid re-copying the file each
    * time you open the application.
    * 
    * @return true if it exists, false if it doesn't
    */
   private boolean checkDataBase() 
    {
       SQLiteDatabase checkDB = null;
       try 
       {
           String myPath = "data/data/com.appkon.hdtvs/databases/" + "channelDB";
           checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
       }catch (Exception e){
           Log.d("Splash","database does't exist yet.");
       }

       if (checkDB != null){
           checkDB.close();

           return true;
       }
       else 
           return false;
    }
}

And this is my logcat record

这是我的logcat记录

> 12-05 08:35:14.222: INFO/System.out(824): debugger has settled (1435)
> 12-05 08:35:15.032: DEBUG/dalvikvm(824): GC freed 621 objects / 51304
> bytes in 98ms 12-05 08:35:15.373: ERROR/Database(824):
> sqlite3_open_v2("data/data/com.appkon.hdtvs/databases/channelDB",
> &handle, 2, NULL) failed 12-05 08:35:15.382: DEBUG/Splash(824):
> database does't exist yet. 12-05 08:35:15.382: DEBUG/splash(824): data
> insert exception 12-05 08:35:15.402: INFO/ActivityManager(51):
> Starting activity: Intent { cmp=com.appkon.hdtvs/.HDtvs } 12-05
> 08:35:16.753: INFO/ActivityManager(51): Displayed activity
> com.appkon.hdtvs/.HDtvs: 1298 ms (total 6152 ms)

1 个解决方案

#1


3  

public void createDataBase() throws Exception 
     {
        boolean dbExist = checkDataBase();
        if (dbExist){
            System.out.println("Database Exist");
        }
        else
        {
            this.getReadableDatabase();
            try{

            }catch (Exception e){
                throw new Error(e.getMessage());
            }
        }
     }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     * 
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() 
     {
        SQLiteDatabase checkDB = null;
        try 
        {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        }catch (Exception e){
            System.out.println("database does't exist yet.");
        }

        if (checkDB != null){
            checkDB.close();
            System.out.println("My db is:- " + checkDB.isOpen());
            return true;
        }
        else 
            return false;
     }

#1


3  

public void createDataBase() throws Exception 
     {
        boolean dbExist = checkDataBase();
        if (dbExist){
            System.out.println("Database Exist");
        }
        else
        {
            this.getReadableDatabase();
            try{

            }catch (Exception e){
                throw new Error(e.getMessage());
            }
        }
     }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     * 
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() 
     {
        SQLiteDatabase checkDB = null;
        try 
        {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        }catch (Exception e){
            System.out.println("database does't exist yet.");
        }

        if (checkDB != null){
            checkDB.close();
            System.out.println("My db is:- " + checkDB.isOpen());
            return true;
        }
        else 
            return false;
     }