2

I have been building a simple note app and have successfully SQlite database and loaders to load data on a listview. Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how. I've search but mainly tutorials are for Content provider, I read this: http://developer.android.com/reference/android/content/AsyncTaskLoader.html#q=addAll but not understand much because they use BroadcastReceiver to get change on sd card. Im all ears to any suggestion and thanks for any help in advance!

this is my code: 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

1 Answer 1

2

Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how.

There is no way to make that happen automatically. Either:

  • Something tells the loader that the data changed, so it knows to reload, or

  • The Loader is the one that is doing the "add, change, or delete a note in database"

I went with the latter approach with my CWAC-LoaderEx project and its SQLiteCursorLoader.

1
  • k, this must be the worst news I received today, should have used content provider for this, just thought it would be a little bit overkill because i don't need sharing content
    – bblackbb
    Dec 13, 2013 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.