如何在带有DatabaseConnector类的SQLite Android中检查数据库是否为空

时间:2015-02-06 16:53:44

标签: android sqlite cursor

我有一个DatabaseConnector类,我想检查数据库是否为空,然后显示警告,点击它将关闭活动。

这是我的DatabaseConnector类

public class DatabaseConnector {

    // Declare Variables
    private static final String DB_NAME = "MyNotes";
    private static final String TABLE_NAME = "tablenotes";
    private static final String TITLE = "title";
    private static final String ID = "_id";
    private static final String NOTE = "note";
    private static final int DATABASE_VERSION = 2;
    private SQLiteDatabase database;
    private DatabaseHelper dbOpenHelper;
    public static final String MAINCAT = "maincat";
    public static final String SUBCAT = "subcat";

    public DatabaseConnector(Context context) {
        dbOpenHelper = new DatabaseHelper(context, DB_NAME, null,
                DATABASE_VERSION);

    }

    // Open Database function
    public void open() throws SQLException {
        // Allow database to be in writable mode
        database = dbOpenHelper.getWritableDatabase();
    }

    // Close Database function
    public void close() {
        if (database != null)
            database.close();
    }

    // Create Database function
    public void InsertNote(String title, String note , String maincat, String subcat) {
        ContentValues newCon = new ContentValues();
        newCon.put(TITLE, title);
        newCon.put(NOTE, note);
        newCon.put(MAINCAT,  maincat);
        newCon.put(SUBCAT, subcat);

        open();
        database.insert(TABLE_NAME, null, newCon);
        close();
    }

    // Update Database function
    public void UpdateNote(long id, String title, String note) {
        ContentValues editCon = new ContentValues();
        editCon.put(TITLE, title);
        editCon.put(NOTE, note);

        open();
        database.update(TABLE_NAME, editCon, ID + "=" + id, null);
        close();
    }

    // Delete Database function
    public void DeleteNote(long id) {
        open();
        database.delete(TABLE_NAME, ID + "=" + id, null);
        close();
    }

    // List all data function
    //String selection = dbOpenHelper.MAINCAT + " = 'quiz'"  
       //     +" AND " + dbOpenHelper.SUBCAT + " = 'test'";

//  public Cursor ListAllNotes() {
//      return database.query(TABLE_NAME, new String[] { ID, TITLE }, null,
//              null, null, null, TITLE);
//  }

    public Cursor ListAllNotes(String selection) {
        return database.query(TABLE_NAME, new String[] { ID, TITLE }, selection,
                null, null, null, TITLE);
    }



    // Capture single data by ID
    public Cursor GetOneNote(long id) {
        return database.query(TABLE_NAME, null, ID + "=" + id, null, null,
                null, null);
    }

这里是ListActivity,我想用警报关闭活动

public class dbMainactivty extends ListActivity {

    // Declare Variables
    public static final String ROW_ID = "row_id";
    private static final String TITLE = "title";
    private ListView noteListView;
    private CursorAdapter noteAdapter;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        Tracker t = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
        t.setScreenName("dbMainactivty");
        t.send(new HitBuilders.AppViewBuilder().build());
        // Locate ListView
        noteListView = getListView();
        //  setContentView(R.layout.list_note);
        //noteListView = (ListView) findViewById(R.id.listview);

        // Prepare ListView Item Click Listener
        noteListView.setOnItemClickListener(viewNoteListener);

        // Map all the titles into the ViewTitleNotes TextView
        String[] from = new String[] { TITLE };

        int[] to = new int[] { R.id.ViewTitleNotes };

        // Create a SimpleCursorAdapter
        noteAdapter = new SimpleCursorAdapter(dbMainactivty.this,
                R.layout.list_note, null, from, to);

        // Set the Adapter into SimpleCursorAdapter
        setListAdapter(noteAdapter);


    }


    // Capture ListView item click
    OnItemClickListener viewNoteListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            // Open ViewNote activity
            Intent viewnote = new Intent(dbMainactivty.this, ViewNote.class);

            // Pass the ROW_ID to ViewNote activity
            viewnote.putExtra(ROW_ID, arg3);
            startActivity(viewnote);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        // Execute GetNotes Asynctask on return to MainActivity
        new GetNotes().execute((Object[]) null);
        GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
    }

    @Override
    protected void onStop() {
        Cursor cursor = noteAdapter.getCursor();

        // Deactivates the Cursor
        if (cursor != null)
            cursor.deactivate();

        noteAdapter.changeCursor(null);
        super.onStop();
        GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStop(this);
    }



    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        Intent i = null;
        switch (item.getItemId()) {
        case R.id.action_rate:
                        String webpage = "http://developer.android.com/index.html";
            Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
            startActivity(intent2);
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);


        case R.id.action_share:
            i = new Intent();
            i.setAction(Intent.ACTION_SEND);
            //i.putExtra(Intent.EXTRA_TEXT, feed.getItem(pos).getTitle().toString()+ " to know the answer download http://developer.android.com/index.html");
            i.setType("text/plain");
            startActivity(i);
            return true;


        }
        return super.onOptionsItemSelected(item);
    };


    // GetNotes AsyncTask
    private class GetNotes extends AsyncTask<Object, Object, Cursor> {
        DatabaseConnector dbConnector = new DatabaseConnector(dbMainactivty.this);

        @Override
        protected Cursor doInBackground(Object... params) {
            // Open the database
            dbConnector.open();

            return dbConnector.ListAllNotes("maincat LIKE 'quiz' AND subcat LIKE 'test'");


        }

        @Override
        protected void onPostExecute(Cursor result) {
            noteAdapter.changeCursor(result);

            // Close Database
            dbConnector.close();
        }
    }
    @Override
    protected void onStart() {
        super.onStart();

        ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() == null) {


            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(
                    "Please check your Internet Connection.")
                    .setTitle("tilte")
                    .setCancelable(false)
                    .setPositiveButton("Exit",
                            new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int id) {
                            //loader.cancel(true);
                            finish();
                        }
                    });


            AlertDialog alert = builder.create();

            alert.show();

        } else {
            Cursor cursor = noteAdapter.getCursor();
            if(cursor != null && cursor.getCount() > 0){
                cursor.moveToFirst();
                //do your action
                //Fetch your data
                GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);

                Toast.makeText(getBaseContext(), "Yipeee!", Toast.LENGTH_SHORT).show();
            }
            else {

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage(
                        "oops nothing pinned yet!   ....")
                        .setTitle("title")
                        .setCancelable(false)
                        .setPositiveButton("Exit",
                                new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                //loader.cancel(true);
                                finish();
                            }
                        });


                AlertDialog alert = builder.create();

                alert.show();
                Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();

            }  

        }

    }

}

我正在尝试检查

cursor != null && cursor.getCount()>0如果它变为false,则显示警告 nothing has been pinned yet 但是,即使光标返回数据,也应显示警报仍然显示。

1 个答案:

答案 0 :(得分:1)

首先,请查看您的活动的生命周期:http://www.android-app-market.com/wp-content/uploads/2012/03/Android-Activity-Lifecycle.png

正如你所看到的,在onStart()之后调用onResume(),这意味着检查onStart()上的光标是行不通的。

其次,您在onResume()方法上启动AsyncTask(GetNotes),这意味着您此时正在运行并行线程,并且在调用新的GetNotes()之后无法检查结果.execute((Object [])null);

您的问题是您需要在AsyncTask完成之后检查数据加载后光标的空虚(cursor != null && cursor.getCount()>0)。换句话说,在onPostExecute(Cursor result)方法中移动光标上的空白检查。