[Android] 나만의 다이어리 앱 만들기 프로젝트8
이제 필요한 기능들을 구현해 볼시간입니다.
기능들
앱에 필요한 기능들은 다음과 같습니다.
- 검색
- 추가
- 수정
- 삭제
이제 이 4가지 기능들을 하나씩 구현 해보도록 하겠습니다.
검색 기능
일정 메인화면과 연락처 메인화면에서 입력한 텍스트를 필터링하여 아래 리스트에 보여주는 기능입니다.
이것을 위해선 기존 어댑터 코드를 조금 수정하고, EditText의 기능을 사용해야합니다.
ListViewAdapter.java
package com.example.mydiary;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
public class ListViewAdapter extends BaseAdapter implements Filterable {
//원본 데이터 리스트
private ArrayList<ListViewAdapterData> list = new ArrayList<ListViewAdapterData>();
//필터링된 데이터 저장 리스트
private ArrayList<ListViewAdapterData> filteredList = list;
Filter listFilter;
@Override
public int getCount() {
return filteredList.size();
}
@Override
public Object getItem(int i) {
return filteredList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
final Context context = viewGroup.getContext();
//리스트뷰에 아이템이 없을 때
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_listview,viewGroup,false);
}
//객체들을 찾아 가져옴
TextView tvTitle = (TextView)view.findViewById(R.id.item_tv_Title);
//TextView tvContent = (TextView)view.findViewById(R.id.item_tv_Content);
//현재 위치의 list배열에서 객체를 가져온다.
ListViewAdapterData listdata = filteredList.get(i);
//뷰에 적용
tvTitle.setText(listdata.getTitle());
//tvContent.setText(listdata.getContent());
return view;
}
//list에 아이템 추가
public void addItemToList(String title, String content){
ListViewAdapterData listdata = new ListViewAdapterData();
listdata.setTitle(title);
listdata.setContent(content);
list.add(listdata);
}
@Override
public Filter getFilter() {
if(listFilter == null){
listFilter = new ListFilter();
}
return listFilter;
}
//커스텀 Filter 클래스 정의 및 구현
private class ListFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults() ;
if (constraint == null || constraint.length() == 0) {
results.values = list;
results.count = list.size();
} else {
ArrayList<ListViewAdapterData> itemList = new ArrayList<ListViewAdapterData>() ;
for (ListViewAdapterData item : list) {
if (item.getTitle().toUpperCase().contains(constraint.toString().toUpperCase()))
{
itemList.add(item);
}
}
results.values = itemList;
results.count = itemList.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//update listview by filtered data list
filteredList = (ArrayList<ListViewAdapterData>) results.values ;
// notify
if (results.count > 0) {
notifyDataSetChanged() ;
} else {
notifyDataSetInvalidated() ;
}
}
}
}
필터를 사용하여 입력한 텍스트를 검색할 수 있도록 만들어 주었습니다.
DiaryActivity.java
package com.example.mydiary;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
public class DiaryActivity extends AppCompatActivity {
private ImageButton button_home;
private Button button_GotoAddList;
private EditText searchTitle;
public ListView lvList = null;
public DBHelper helper = new DBHelper(this);
ListViewAdapter adapter = new ListViewAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diary_main);
initView();
displayList();
lvList.setAdapter(adapter);
//홈 버튼
button_home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent goHome = new Intent(getApplicationContext(),MainActivity.class);
startActivity(goHome);
finish();
}
});
//글 쓰기 화면 이동
button_GotoAddList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent GotoAddList = new Intent(getApplicationContext(),DiaryAddActivity.class);
startActivity(GotoAddList);
finish();
}
});
//일정 리스트 선택시
lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ListViewAdapterData listViewAdapterData = (ListViewAdapterData) adapter.getItem(i);
String title = listViewAdapterData.getTitle().toString();
String content = listViewAdapterData.getContent().toString();
Intent intent = new Intent(getBaseContext(),DiaryDetail.class);
intent.putExtra("제목",title);
intent.putExtra("내용",content);
startActivity(intent);
finish();
}
});
//제목을 통한 검색
searchTitle.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
String filterText = editable.toString();
((ListViewAdapter)lvList.getAdapter()).getFilter().filter(filterText) ;
}
});
}
//뷰 초기화
public void initView(){
lvList = findViewById(R.id.lv_list);
searchTitle = findViewById(R.id.searchTitle);
button_home = findViewById(R.id.button_home);
button_GotoAddList = findViewById(R.id.button_GotoAddList);
}
//화면에 db 띄우기
public void displayList(){
SQLiteDatabase database = helper.getReadableDatabase();
//목록 가져오기
Cursor cursor = database.rawQuery("SELECT * FROM DIARY ORDER BY title ASC",null);
//목록의 개수만큼 반복하며 Add
while(cursor.moveToNext()){
//제목, 글 내용 순서
adapter.addItemToList(cursor.getString(0),cursor.getString(1));
}
}
}
ListViewAdapter1.java
package com.example.mydiary;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
public class ListViewAdapter1 extends BaseAdapter implements Filterable {
//원본 데이터 리스트
private ArrayList<ListViewAdapterData1> list1 = new ArrayList<ListViewAdapterData1>();
//필터링된 데이터 저장 리스트
private ArrayList<ListViewAdapterData1> filteredList1 = list1;
Filter listFilter1;
@Override
public int getCount() {
return filteredList1.size();
}
@Override
public Object getItem(int i) {
return filteredList1.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
final Context context = viewGroup.getContext();
//리스트뷰에 아이템이 없을 때
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_listview1, viewGroup, false);
}
//객체들을 찾아 가져옴
TextView tvName = (TextView) view.findViewById(R.id.item_tv_Name);
TextView tvPhone = (TextView) view.findViewById(R.id.item_tv_Phone);
//현재 위치의 list배열에서 객체를 가져온다.
ListViewAdapterData1 listdata1 = filteredList1.get(i);
//뷰에 적용
tvName.setText(listdata1.getName());
tvPhone.setText(listdata1.getPhonenum());
return view;
}
//list에 아이템 추가
public void addItemToList(String name, String phonenum) {
ListViewAdapterData1 listdata1 = new ListViewAdapterData1();
listdata1.setName(name);
listdata1.setPhonenum(phonenum);
list1.add(listdata1);
}
@Override
public Filter getFilter() {
if (listFilter1 == null) {
listFilter1 = new ListFilter1();
}
return listFilter1;
}
//커스텀 Filter 클래스 정의 및 구현
private class ListFilter1 extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
results.values = list1;
results.count = list1.size();
} else {
ArrayList<ListViewAdapterData1> itemList = new ArrayList<ListViewAdapterData1>();
for (ListViewAdapterData1 item : list1) {
if (item.getName().toUpperCase().contains(constraint.toString().toUpperCase())) {
itemList.add(item);
}
}
results.values = itemList;
results.count = itemList.size();
}
return results;
}
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
//update listview by filtered data list
filteredList1 = (ArrayList<ListViewAdapterData1>) results.values;
// notify
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
PhoneBookActivity.java
package com.example.mydiary;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
public class PhoneBookActivity extends AppCompatActivity {
private ImageButton button_home;
private Button button_GotoAddPhone;
private EditText searchName;
public ListView lvList1;
public DBHelper1 helper = new DBHelper1(this);
ListViewAdapter1 adapter = new ListViewAdapter1();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phonebook_main);
initViews();
displayList();
lvList1.setAdapter(adapter);
//홈 버튼클릭
button_home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent goBack = new Intent(getApplicationContext(),MainActivity.class);
startActivity(goBack);
finish();
}
});
//연락처추가 버튼클릭
button_GotoAddPhone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent GotoAddPhone = new Intent(getApplicationContext(),PhoneBookAddActivity.class);
startActivity(GotoAddPhone);
finish();
}
});
//리스트 목록 클릭
lvList1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ListViewAdapterData1 listViewAdapterData1 = (ListViewAdapterData1) adapter.getItem(i);
String name = listViewAdapterData1.getName().toString();
String phonenum = listViewAdapterData1.getPhonenum().toString();
Intent intent = new Intent(getBaseContext(),PhoneBookDetail.class);
intent.putExtra("이름",name);
intent.putExtra("전화번호",phonenum);
startActivity(intent);
finish();
}
});
//검색기능
searchName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
String filterText = editable.toString();
((ListViewAdapter1)lvList1.getAdapter()).getFilter().filter(filterText) ;
}
});
}
//뷰 초기화
public void initViews(){
lvList1 = findViewById(R.id.lv_list1);
searchName = findViewById(R.id.searchName);
button_home = findViewById(R.id.button_home);
button_GotoAddPhone = findViewById(R.id.button_GotoAddPhone);
}
//화면에 db 띄우기
public void displayList(){
SQLiteDatabase database = helper.getReadableDatabase();
//목록 가져오기
Cursor cursor = database.rawQuery("SELECT * FROM PHONEBOOK ORDER BY name ASC",null);
//목록의 개수만큼 반복하며 Add
while(cursor.moveToNext()){
//제목, 글 내용 순서
adapter.addItemToList(cursor.getString(0),cursor.getString(1));
}
}
}
댓글남기기