检测加载器的SQLite数据库的更改

时间:2013-12-13 16:04:29

标签: java android sqlite broadcastreceiver loader

我一直在构建一个简单的笔记应用程序并成功使用SQlite数据库和加载器在listview上加载数据。接下来我要做的是当我在数据库中添加,更改或删除注释但不知道如何时,make loader会自动重新加载。我搜索但主要是内容提供商的教程,我读到这个:http://developer.android.com/reference/android/content/AsyncTaskLoader.html#q=addAll 但不太了解,因为他们使用BroadcastReceiver来改变SD卡。 我非常感谢任何建议,并感谢您提前提供任何帮助!

这是我的代码:WhiteNote.java

public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.white_note, container, false);

    context=getActivity();
    note_database = new NoteDatabase(context);

    final EditText text_ed_1;
    final EditText text_ed_2;
    Button button_addNote;
    Button button_listallNote;
    Button button_delallNote;

    text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
    text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
    button_addNote = (Button)rootView.findViewById(R.id.button1);
    button_listallNote = (Button)rootView.findViewById(R.id.button2);
    button_delallNote = (Button)rootView.findViewById(R.id.button3);
    note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
    noteListAdapter=new NoteListAdapter(context, new ArrayList<NoteItems>());

    note_database.open();
    getLoaderManager().initLoader(0, null,WhiteNote.this);  
    note_database.close();

    button_addNote.setOnClickListener(new OnClickListener() {     
        @Override
        public void onClick(View v) {
            note_database.open();

            note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
            //i++;
            note_database.close();
        }
    });

    button_listallNote.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            note_database.open();

            note_database.get_NoteListAdapter();
            note_listview_container.setAdapter(note_database.dbnoteListAdapter);

            note_database.close();
            //note_list.setText(ds);
        }
    });

    button_delallNote.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            note_database.open();
            note_database.deleteAllNote();
            note_database.close();
        }
    });
    return rootView;
}

@Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
    return new NoteItemsLoader(context,note_database);
}

@Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
                       ArrayList<NoteItems> data) {
    note_listview_container.setAdapter(new NoteListAdapter(context, data));
}

@Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
    note_listview_container.setAdapter(null);
}
}

class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
    private ArrayList<NoteItems> loader_noteitems= new ArrayList<NoteItems>();
    private NoteDatabase loader_db;

    public NoteItemsLoader(Context context, NoteDatabase db) {
        super(context);
        loader_db = db;
        loader_noteitems=loader_db.get_NoteListArray(loader_noteitems,loader_db);
    }

    @Override
    protected void onStartLoading() {
        if (loader_noteitems != null) {
            deliverResult(loader_noteitems); // Use the cache
        }
        else
            forceLoad();
    }

    @Override
    protected void onStopLoading() {
        cancelLoad();
    }

    @Override
    public ArrayList<NoteItems> loadInBackground() {              
        loader_db.open(); 

        ArrayList<NoteItems> note_items = new ArrayList<NoteItems>();
        loader_db.get_NoteListArray(note_items,loader_db);

        loader_db.close();
        return note_items;
    }

    @Override
    public void deliverResult(ArrayList<NoteItems> data) {
        if (isReset()) {
            if (data != null) {
                onReleaseResources(data);
            }
        }
        ArrayList<NoteItems> oldNotes = loader_noteitems;
        loader_noteitems = data;

        if (isStarted()) {
            super.deliverResult(data);
        }

        if (oldNotes != null) {
            onReleaseResources(oldNotes);
        }
    }

    @Override
    protected void onReset() {
        super.onReset();
        onStopLoading();
        loader_noteitems = null;
    }

    @Override
    public void onCanceled(ArrayList<NoteItems> data) {
         super.onCanceled(data);
         loader_noteitems = null;
    }

    protected void onReleaseResources(ArrayList<NoteItems> data) {}

}

my NoteDatabase.java

public class NoteDatabase {
private static final String DATABASE_NAME = "DB_NOTE";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NOTE = "NOTE";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TOPIC = "Topic";
public static final String COLUMN_NOTECONTENT = "Content";
public static final String COLUMN_NAME = "Name";

public NoteListAdapter dbnoteListAdapter;

private static Context my_context;
static SQLiteDatabase note_sqldb;
private OpenHelper noteopenHelper;

public NoteDatabase(Context c){
    NoteDatabase.my_context = c;
}

public NoteDatabase open() throws SQLException{
    noteopenHelper = new OpenHelper(my_context);
    note_sqldb = noteopenHelper.getWritableDatabase();
    return this;
}

public void close(){
    noteopenHelper.close();
}

public long createData(String chude_note, String noidung_note) { 
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_TOPIC, chude_note);
    cv.put(COLUMN_NOTECONTENT, noidung_note);
    cv.put(COLUMN_NAME, "by Black");
    return note_sqldb.insert(TABLE_NOTE, null, cv);
}

public String getData() {
    String[] columns = new String[] {COLUMN_ID,COLUMN_TOPIC,COLUMN_NOTECONTENT,COLUMN_NAME};
    Cursor c = note_sqldb.query(TABLE_NOTE, columns, null, null, null, null, null);
    /*if(c==null)
        Log.v("Cursor", "C is NULL");*/
    String result="";
    int iRow = c.getColumnIndex(COLUMN_ID);
    int iTopic = c.getColumnIndex(COLUMN_TOPIC);
    int iContent = c.getColumnIndex(COLUMN_NOTECONTENT);
    int iOwner = c.getColumnIndex(COLUMN_NAME);
    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){     
        result = result +" \n"+ c.getString(iRow)
                + "\n - Topic: " + c.getString(iTopic)
                + "\n - Content: " + c.getString(iContent)
                + "\n - Owner: " + c.getString(iOwner) + "\n";
    }
    c.close();
    //Log.v("Result", result);
    return result;
}

public Cursor selectQuery(String query) {
      Cursor c1 = null;
      try {

       if (note_sqldb.isOpen()) {
           note_sqldb.close();

       }
       note_sqldb = noteopenHelper.getWritableDatabase();
       c1 = note_sqldb.rawQuery(query, null);

      } catch (Exception e) {

       System.out.println("DATABASE ERROR " + e);

      }
      return c1;

     }

public void get_NoteListAdapter() {

  ArrayList<NoteItems> noteList = new ArrayList<NoteItems>();
  noteList.clear();


  open();
  String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
  note_sqldb = noteopenHelper.getWritableDatabase();
    Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
    int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
    int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
    int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
    int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
    for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){     
      NoteItems one_rowItems = new  NoteItems();

      one_rowItems.set_rowTopic(c1.getString(iTopic));
      one_rowItems.set_rowContent(c1.getString(iContent));
      one_rowItems.set_rowOwner(c1.getString(iOwner));

      noteList.add(one_rowItems);
    }
    c1.close();

    close();

  dbnoteListAdapter = new NoteListAdapter(my_context, noteList);

 }

public ArrayList<NoteItems> get_NoteListArray(ArrayList<NoteItems> noteitems_list,NoteDatabase db) {

      noteitems_list.clear();

      db.open();
      String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
      note_sqldb = noteopenHelper.getWritableDatabase();
      Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
      int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
      int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
      int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
      int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
      for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){     
          NoteItems one_rowItems = new  NoteItems();

          one_rowItems.set_rowTopic(c1.getString(iTopic));
          one_rowItems.set_rowContent(c1.getString(iContent));
          one_rowItems.set_rowOwner(c1.getString(iOwner));

          noteitems_list.add(one_rowItems);
      }
      c1.close();
      db.close();

      return noteitems_list;

 }

public int deleteNote(String topic) {
    return note_sqldb.delete(TABLE_NOTE, COLUMN_TOPIC + "='" + topic + "'", null);
}

public int deleteAllNote() {
    return note_sqldb.delete(TABLE_NOTE, null, null);
}
}

1 个答案:

答案 0 :(得分:2)

  

接下来我要做的是当我在数据库中添加,更改或删除注释但不知道如何时,make loader会自动重新加载。

没有办法让这种情况自动发生。之一:

  • 有东西告诉加载器数据已更改,因此它知道要重新加载,或者

  • Loader是“在数据库中添加,更改或删除记事”

我采用后一种方法my CWAC-LoaderEx project及其SQLiteCursorLoader