如何使用 DatabaseConnector class 检查 SQLite Android 中的数据库是否为空

How to check if database is empty in SQLite Android with DatabaseConnector class

我有一个 DatabaseConnector class,我想在其中检查数据库是否为空,然后显示警报,单击它会关闭 activity。

这是我的数据库连接器class

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

这里是列表Activity,我想用警报

关闭Activity
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 如果它变为假则显示警报 nothing has been pinned yet 但是应该显示,即使光标 returns 数据警报仍然显示。

第一步,查看您的 activity 的生命周期:http://www.android-app-market.com/wp-content/uploads/2012/03/Android-Activity-Lifecycle.png

如您所见,onResume() 在 onStart() 之后调用,这意味着在 onStart() 上检查光标无法工作。

其次,您在 onResume() 方法上启动了一个 AsyncTask (GetNotes),这意味着您此时 运行 是一个并行线程,无法在调用 new GetNotes() 后检查结果。执行((对象[])空);

您的问题是您需要在数据加载后检查光标是否为空 (cursor != null && cursor.getCount()>0),这意味着在 AsyncTask 完成后。换句话说,将光标上的空检查移动到 onPostExecute(Cursor result) 方法内。