0

Notes를 사용하여 간단한 구성 도우미를 프로그래밍하고 싶습니다.SQLite의 데이터로 동적 목록 뷰를 만드는 좋은 방법은 무엇입니까?

public class Note { 
    private int id; 
    private String time; 
    private String date; 
    private String text; 
    public Note(final int id, final String time, final String date, final String text){ 
     setId(id); 
     setTime(time); 
     setDate(date); 
     setText(text); 
    } 
    public int getId(){ 
     return id; 
    } 
    public String getTime(){ 
     return time; 
    } 
    public String getDate(){ 
     return date; 
    } 
    public String getText(){ 
     return text; 
    } 

    void setId(final int id){ 
     this.id = id; 
    } 
    void setTime(final String time){ 
     this.time = time; 
    } 
    void setDate(final String date){ 
     this.date = date; 
    } 
    void setText(final String text){ 
     this.text = text; 
    } 
} 

그리고 NotesManager :

_id | time | date | text 
1 | 9:45 | 12.01| blabla 
2 | 21:01| 13.01| albalb 
...| ... | ... | ... 

또한 I 클래스 Note 있습니다

public class NotesManager { 
    private static final String TABLE_NAME = "NotesListTable"; 
    private static final String KEY_TIME = "time"; 
    private static final String KEY_DATE = "date"; 
    private static final String KEY_TEXT = "text"; 
    private static final String KEY_ID = "_id"; 

    private final SQLiteDatabase db; 
    public NotesManager(SQLiteDatabase db){ 
     this.db = db; 
    } 
    public void save(final ContentValues cv){ 
     db.insert(TABLE_NAME, null, cv); 
    } 
    public void delete(final int id){ 
     db.delete(TABLE_NAME, KEY_ID + "=" + id, null); 
    } 
    public Note getNoteById(final int id){ 
     Cursor mCursor = db.query(TABLE_NAME, null, KEY_ID + "=" + id, null, null, null, null, null); 
     if (mCursor != null) { 
      mCursor.moveToFirst(); 
     } 
     return new Note(mCursor.getInt(mCursor.getColumnIndex(KEY_ID)), 
       mCursor.getString(mCursor.getColumnIndex(KEY_TIME)), 
       mCursor.getString(mCursor.getColumnIndex(KEY_DATE)), 
       mCursor.getString(mCursor.getColumnIndex(KEY_TEXT))); 
    } 
    public Cursor getAllDataFromDB(){ 
     return db.query(TABLE_NAME, null, null, null, null, null, null); 
    } 
    public String[] getKeysArray(){ 
     return new String[] {KEY_ID, KEY_TIME, KEY_DATE, KEY_TEXT}; 
    } 
} 

내가 ListView에있는 조각을 아래 그림과 같이 나는 몇 가지 데이터를 SQLite 데이터베이스를 : 그것은 안드로이드 스튜디오에 의해 생성되었습니다, 너트, SimpleCursorAdapter를 추가했습니다.

,
public class NotesListFragment extends Fragment implements AbsListView.OnItemClickListener { 

    private static final String ARG_SECTION_NUMBER = "section_number"; 
    private int mSectionNumber = 0; 
    private OnFragmentInteractionListener mListener; 
    private AbsListView mListView; 
    private SimpleCursorAdapter scAdapter; 
    private Cursor cursor; 
    ImageButton deleteButton; 
    NotesManager notesManager = new NotesManager(OrganizerApp.db); 

    public static NoesListFragment newInstance(int param1) { 
     NoesListFragment fragment = new NotesListFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ARG_SECTION_NUMBER, param1); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    public NotesListFragment() { 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (getArguments() != null) { 
      mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER); 
     } 
     cursor = NotesManager.getAllDataFromDB(); 
     //TODO: startManagingCursor(cursor) 

     //mAdapter = new ArrayAdapter<NotesListContent.NotesItem>(getActivity(), 
     //  android.R.layout.simple_list_item_1, android.R.id.text1, NotesListContent.ITEMS); 
     scAdapter = new SimpleCursorAdapter(getActivity(), 
       R.layout.note_list_rowlayout, 
       cursor, 
       notesManager.getKeysArray(), 
       new int[]{R.id.note_list_rowlayout_item1, 
         R.id.note_list_rowlayout_item2, 
         R.id.note_list_rowlayout_item3, 
         R.id.note_list_rowlayout_item4 }); 
     deleteButton = (ImageButton) getView(). 
       findViewById(R.id.note_list_rowlayout_deleteButton); 
     deleteButton.setOnClickListener(onClickDeleteButton); 
    } 

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

     // Set the adapter 
     mListView = (AbsListView) view.findViewById(android.R.id.list); 
     mListView.setAdapter(scAdapter); 
     //((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter); 

     // Set OnItemClickListener so we can be notified on item clicks 
     mListView.setOnItemClickListener(this); 

     return view; 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     try { 
      mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER); 
      mListener = (OnFragmentInteractionListener) activity; 
      ((MainActivity) activity).onSectionAttached(mSectionNumber); 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() 
        + " must implement OnFragmentInteractionListener"); 
     } 
    } 

    @Override 
    public void onDetach() { 
     super.onDetach(); 
     mListener = null; 
    } 


    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     if (null != mListener) { 
      // Notify the active callbacks interface (the activity, if the 
      // fragment is attached to one) that an item has been selected. 
      // mListener.onFragmentInteraction(NotesListContent.ITEMS.get(position).id); 
     } 
    } 

    public void setEmptyText(CharSequence emptyText) { // If list is empty. 
     View emptyView = mListView.getEmptyView(); 

     if (emptyView instanceof TextView) { 
      ((TextView) emptyView).setText(emptyText); 
     } 
    } 

    public interface OnFragmentInteractionListener { 
     // TODO: Update argument type and name 
     public void onFragmentInteraction(String id); 
    } 

    View.OnClickListener onClickDeleteButton = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

     } 
    }; 

} 

안드로이드 스튜디오도 생성 NotesListContent.java는 :

public class NotesListContent { 

    public static List<Note> ITEMS = new ArrayList<Note>(); 

    //public static Map<String, Note> ITEM_MAP = new HashMap<String, Note>(); 

    private static void addItem(Note item) { 
     ITEMS.add(item); 
     //ITEM_MAP.put(item.id, item); 
    } 



    /** 
    * A dummy item representing a piece of content. 

    public static class NoteItem { 
     public String id; 
     public String content; 

     public NoteItem(String id, String content) { 
      this.id = id; 
      this.content = content; 
     } 

     @Override 
     public String toString() { 
      return content; 
     } 
    }*/ 
} 

그래서 내 솔루션은 작동하지만, 나는 그것이 나쁜 것이라고 생각합니다.

  1. 내가 필요한 경우 NotesListContent.java가 필요합니까? 어떻게 사용할 수 있습니까?
  2. 사용하지 않는 SimpleCursorAdapter없이 ListView를 어떻게 사용할 수 있습니까?
  3. 새로 고침없이 항목을 삭제하고 추가하는 방법 모두 ListView?
  4. 특히이 코드는 매우 unconvenient 것으로 보인다

    scAdapter = 새로운 SimpleCursorAdapter (getActivity() R.layout.note_list_rowlayout, 커서 notesManager.getKeysArray() 새로운 INT [] {R .id.note_list_rowlayout_item1, R.id.note_list_rowlayout_item2, R.id.note_list_rowlayout_item3, R.id.note_list_rowlayout_item4});

+0

불편하십니까? 그 생성자에 불편한 점은 무엇입니까? – pskink

답변

1

본인이 작성한 메모 관리자가 귀하의 질문에 답변 해 드리겠습니다.

NotesListContent.java가 필요한 이유는 무엇입니까? 어떻게 사용할 수 있습니까?

이것은 약간 MVC 패턴,보기에서 데이터 분리입니다. 엔티티로 생각하거나 단일 노트 항목 설명으로 생각하는 것이 좋습니다.

사용하지 않는 SimpleCursorAdapter없이 ListView를 어떻게 사용할 수 있습니까?

a) simpleCursorAdapter은 언제 하락 했습니까? 그 중 하나만 생성자입니다.
b) 귀하가) 자신을 두 번째 생성자를 사용하거나 예를 ArrayAdapter와 위해 (일부 어댑터 클래스를 확장 할 수 있습니다

어떻게 모든 목록보기 삭제하고 새로 고침없이 항목을 추가하는 방법?

DataAdapter에 데이터를 추가 한 다음 dataAdapter를 ListView (listview.setAdapter (adapter))의 어댑터로 설정하십시오.
adapter.notifyDataSetChanged()를 호출하지 않으면 listview의 뷰가 업데이트되지 않습니다.

는 특히이 코드는 그것에 대해 잘못 무엇

매우 unconvenient (...) 것 같다? 그렇다면 다음과 같이 sth를 자유롭게 사용하십시오.

String[] columns = new String[] { // The desired columns to be bound 
     "timestamp", 
     "title", 
     "content", 
}; 

// the XML defined views which the data will be bound to 
int[] map_to = new int[] { 
     R.id.timestamp, 
     R.id.title, 
     R.id.content, 
}; 

dataAdapter = new SimpleCursorAdapter(
     this, R.layout.some_xml_here, 
     db.getAllItems(), 
     columns, 
     map_to, 
     0); 
+0

답변 해 주셔서 감사합니다! "데이터베이스 -> 임시 커서 -> ListView"방식을 사용하면 안되며 "데이터베이스 -> 임시 커서 -> Notes List (NotesListContent.java의 List ) -> ListView"와 같은 작업을 수행해야합니까? 왜냐하면 나는 작업하기 쉬운 노트 목록을 가질 것이기 때문입니다. 그보다 나은 방법이라면리스트 을 어떻게 만들 수 있습니까? 그리고 ArrayAdapter를 수정하여 각 행에 여러 개의 필드를 넣을 수 있습니까? Android에서 CursorAdapet을 사용하는 것이 좋습니다. – Porfiriy

+0

글쎄,이 모든 응용 프로그램이 얼마나 엄격하게 작성 되었는가에 달렸지 만 일반적으로 ArrayList 을 사용하는 것이 좋습니다. ArrayList를 만들려면 SimpleCursorAdapter와 같은 방법으로 DB에서 채우고 싶다면 CustomCursorAdapter를 만들고 기본 어댑터를 확장해야합니다. 그렇지 않으면 List list = new ArrayList ()입니다. 이를 수행하는 방법에 대한 여러 예제를 찾을 수 있으며 getView() 구현을 제공하면 충분합니다. 짧지 만 필요에 맞게 조정할 수 있습니다. – brainovergrow