안드로이드

안드로이드 프로그래밍 - 다용도 앱 만들기 5

2023. 1. 18. 17:08
728x90
  • 앱의 기능 설명
    • 1. 로그인 기능
    • 2. 메모장
    • 3. 달력
    • 4. 연락처
    • 5. 그림판
    • 6. 미니게임
    • 7. 계산기
    • 8. 스톱워치
    • 9. 가계부
  • 연락처

연락처 앱

  • 연락처 xml 코드
더보기
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#25E9FD35">

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginEnd="48dp"
        android:layout_marginRight="48dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="61dp"
        android:text="이름"
        android:textAppearance="?android:attr/textAppearanceMedium"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="34dp"
        android:layout_marginLeft="34dp"
        android:onClick="insert"
        android:text="추가"
        app:layout_constraintBaseline_toBaselineOf="@+id/button2"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="22dp"
        android:text="전화번호"
        android:textAppearance="?android:attr/textAppearanceMedium"
        app:layout_constraintBottom_toTopOf="@+id/button1"
        app:layout_constraintEnd_toEndOf="@+id/textView1"
        app:layout_constraintStart_toEndOf="@+id/textView1" />

    <EditText
        android:id="@+id/tel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:inputType="number|text"
        app:layout_constraintStart_toStartOf="@+id/name"
        app:layout_constraintTop_toBottomOf="@+id/name" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="11dp"
        android:onClick="search"
        android:text="탐색"
        app:layout_constraintStart_toStartOf="@+id/tel"
        app:layout_constraintTop_toBottomOf="@+id/tel" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="45dp"
        android:layout_marginBottom="48dp"
        android:text="여기에 모든 데이터가 표시됩니다."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="11dp"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"
        android:onClick="select_all"
        android:text="전체 조회"
        app:layout_constraintEnd_toEndOf="@+id/tel"
        app:layout_constraintTop_toBottomOf="@+id/tel" />

</android.support.constraint.ConstraintLayout>
  • EditText를 통하여 이름, 전화번호를 입력 받는다.
  • 추가 버튼을 클릭하면, 기록한 사항들이 저장이 된다.
  • 탐색 버튼을 클릭하여, 찾고자 하는 이름을 입력 한 후 탐색을 하면 해당 정보가 표출 된다.
  • 전체 조회 버튼을 클릭하면, 해당 연락처에 저장되어 있는 정보들이 모두 표출된다.

 

  • 연락처 java코드
더보기
class DBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "mycontacts.db";

    private static final int DATABASE_VERSION = 3;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE contacts ( _id INTEGER PRIMARY KEY" +
                " AUTOINCREMENT, name TEXT, tel TEXT);");
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }
}

public class Activity5 extends AppCompatActivity {
    DBHelper helper;
    SQLiteDatabase db;
    EditText edit_name, edit_tel;
    TextView edit_result;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout5);
        helper = new DBHelper(this);
        try {
            db = helper.getWritableDatabase();
        } catch (SQLiteException ex) {
            db = helper.getReadableDatabase();
        }
        edit_name = (EditText) findViewById(R.id.name);
        edit_tel = (EditText) findViewById(R.id.tel);
        edit_result = (TextView) findViewById(R.id.textView);
    }

    public void insert(View target) {
        String name = edit_name.getText().toString();
        String tel = edit_tel.getText().toString();
        db.execSQL("INSERT INTO contacts VALUES (null, '" + name + "', '" + tel
                + "');");
        Toast.makeText(getApplicationContext(), "성공적으로 추가되었음",
                Toast.LENGTH_SHORT).show();
        edit_name.setText("");
        edit_tel.setText("");
    }

    public void search(View target) {
        String name = edit_name.getText().toString();
        Cursor cursor;
        cursor = db.rawQuery("SELECT name, tel FROM contacts WHERE name='"
                + name + "';", null);

        Toast.makeText(getApplicationContext(), ""+cursor.getCount() ,
                Toast.LENGTH_SHORT).show();

        while (cursor.moveToNext()) {
            String tel = cursor.getString(1);
            edit_tel.setText(tel);
        }
    }
    public void select_all(View target) {
        Cursor cursor;
        cursor = db.rawQuery("SELECT * FROM contacts", null);

        String s="Id         Name            Tel \r\n";
        while (cursor.moveToNext()) {
            s += cursor.getString(0) + "    ";
            s += cursor.getString(1) + "    ";
            s += cursor.getString(2) + "    \r\n";
        }
        edit_result.setText(s);

    }
}
  • DBHelper를 통하여, mycontacts.db라는 db를 생성한다.
  • TABLE에 접근하면, 기본키는 자동생성되고, 이름과 전화번호를 입력받는다.
  • 접근을 종료하면 테이블은 제거 된다.
  • insert가 눌리면, SQL의 INSERT INTO문이 실행되어 이름과 전화번호를 입력 받아 테이블에 저장한다.
  • search가 눌리면, Query에서 SELECT문을 이용하여 name을 입력 받고 해당 이름과 전화번호를 출력한다.
  • select_all이 눌리면, Query에서 SELECT *, 즉 모든 사항을 출력한다.

 

728x90
저작자표시 비영리 변경금지 (새창열림)

'안드로이드' 카테고리의 다른 글

안드로이드 프로그래밍 - 다용도 앱 만들기 7  (0) 2023.01.18
안드로이드 프로그래밍 - 다용도 앱 만들기 6  (0) 2023.01.18
안드로이드 프로그래밍 - 다용도 앱 만들기 4  (0) 2023.01.18
안드로이드 프로그래밍 - 다용도 앱 만들기 3  (0) 2023.01.18
안드로이드 프로그래밍 - 다용도 앱 만들기 2  (0) 2023.01.18
'안드로이드' 카테고리의 다른 글
  • 안드로이드 프로그래밍 - 다용도 앱 만들기 7
  • 안드로이드 프로그래밍 - 다용도 앱 만들기 6
  • 안드로이드 프로그래밍 - 다용도 앱 만들기 4
  • 안드로이드 프로그래밍 - 다용도 앱 만들기 3
IT의 큰손
IT의 큰손
IT계의 큰손이 되고 싶은 개린이의 Log 일지
Developer Story HouseIT계의 큰손이 되고 싶은 개린이의 Log 일지
IT의 큰손
Developer Story House
IT의 큰손
전체
오늘
어제
  • 분류 전체보기 (457)
    • 정보처리기사 필기 (18)
    • 정보처리기사 실기 (12)
    • 정보처리기사 통합 QUIZ (12)
    • 빅데이터 (11)
    • 안드로이드 (11)
    • 웹페이지 (108)
    • 자바 (49)
    • SQLD (3)
    • 백준 알고리즘 (76)
    • 데이터베이스 (41)
    • 깃허브 (2)
    • Library (14)
    • Server (31)
    • 크롤링&스크래핑 (3)
    • Spring (23)
    • Vue.js (13)
    • React (27)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Developer Stroy House

인기 글

태그

  • 자바
  • DB
  • java
  • 백엔드
  • jsp
  • 프론트엔드
  • IT자격증
  • 코딩테스트
  • JavaScript
  • html
  • 웹페이지
  • IT개발자
  • ajax
  • jquery
  • 웹개발자
  • 데이터베이스
  • 정보보안전문가
  • 백준
  • React
  • it
  • 정보처리기사필기
  • 웹개발
  • 앱개발자
  • css
  • 알고리즘
  • IT자격증공부
  • 개발블로그
  • DBA
  • 정보처리기사
  • 개발자

최근 댓글

최근 글

Designed By hELLO
IT의 큰손
안드로이드 프로그래밍 - 다용도 앱 만들기 5
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.