Android

[Android Studio] 인물 정보 입력 & 등록하기 (3)

https.. 2024. 5. 12. 13:35

PersonRegistApp 
애뮬레이터 안에 갤러리에 찾아가 거기서 사진을 선택한다.
애뮬레이터에는 사진이 없다.
사진 안 찍었기 때문이다. 그래서 사진을 넣어줘야 한다.
 
사진 업로드
애뮬레이터 파일 구조를 봐야 한다.
안드 스튜디오 뷰 > 툴 윈도즈 >  디바이스 파일 익스플로러
이미지는 sdcard > pictures에 저장
픽처스 우클릭 업로드에서 사진 경로 찾아서 넣기
 
에뮬레이터 재시작.. 위로 끌어올려서 restart
사진 등록은 클릭하면 sdcard 사진이 저장된 곳으로 이동한다. (아직 사진 등록은 안 됨 코딩 안 해서)
 
컨텐트 퍼스널 레그에서 이미지에 클릭커블 트루... 클릭했을 때 파인드포토를 줌
 
파인드포토는 펄슨레그에서 구현한다.
 
이미지 여러 개 중 하나를 선택할 것이다.
갤러리에 있던 이미지의 uri링크 주소를 가져올 것인데 이미지 삽입이 아니라 sd카드에 있는 이미지 uri 가져와서 원하는 이미지뷰에 넣어주는 것이다.
외부에서 sd카드로 들어가서 전환, 인텐트로 전환을 하는데 어디로 가느냐 이미지로 간다.
이미지 uri 가져와야 하기 때문에 uri객체를 만든다.
Uri photoUri;

인텐트
클래스로 넘어 가는 게 아니라 sd카드로 가야 한다.

public void findPhoto(View view) {
    Intent it = new Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    it.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult();
} // findPhoto


선택한 이미지 uri을 가져올 것이다.
결과를 위한 스타트액티비티이기 때문에 ForResult로 가져온다.
설명하자면, 외부에서 sd카드로 들어갈 때 입장권 가지고 들어가야 된다. 예를 들어 1이라는 입장권 가져가면 네가 얘기한 1 맞아? 요청코드가 1 맞니? 맞다면 들어가게 한다.
입장권과 같은 의미의 변수를 전달해야 함
입장권에 좌석 이런 정보가 있는데 이게 변경되면 안 된다.
뭐에 데이터값이 변하면 안 됨
이거를 상수로 표현
상수 제어 변수를 만든다. 상수는 final

public final static int REQUEST_PHOTO_CODE = 1;

상수는 보통 대문자로 선언한다.
final startActivityForResult(it, REQUEST_PHOTO_CODE);
변수 넣어주고 collback메시지를 구현한다.

public void onActivityResult(int requestcode, int resultcode, Intent it) {

} // onActivityResult

리퀘스트 리절트 인텐트 3가지를 변수로 받는다.

public void onActivityResult(int requestcode, int resultcode, Intent it) {
    super.onActivityResult(requestcode, resultcode, it);
    if (requestcode == REQUEST_PHOTO_CODE) {
        if (resultcode == RESULT_OK) {
            photoUri = it.getData();
        }
    }
} // onActivityResult

유알아이를 파인드이미지에 지정한다.

findimage.setImageURI(photoUri);

public void onActivityResult(int requestcode, int resultcode, Intent it) {
    super.onActivityResult(requestcode, resultcode, it);
    if (requestcode == REQUEST_PHOTO_CODE) {
        if (resultcode == RESULT_OK) {
            photoUri = it.getData();
            findimage.setImageURI(photoUri);
        }
    }
} // onActivityResult

 
사진 크게 하려면..

findimage.setMaxWidth(200);
findimage.setMaxHeight(250);

해당 코드로 조절한다.

regist.setOnClickListener(new View.OnClickListener() {
    
}); // regist

String str_name, str_studentid, str_grade, str_major_value, str_hobby;

name.getText().toString();

네임을 겟텍스트로 가져오고 이걸 문자열로 변환

전공은 스피너를 사용했었음
전공은 어레이어뎁터로 붙인 거
그래서 여기서 아이템 선택했다면 메이저벨류
이벤트 리스너 생기게 된다. 메이저라는 스피너에 

major.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        str_major_value = str_major[i];
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        Toast.makeText(getApplicationContext(), "전공선택필수", Toast.LENGTH_SHORT).show();
    }
});

뭘 선택했다면 순번에 해당하는 값을 테스티알 메이저 벨류에 넣고 아무것도 선택되지 않았다면 
전공선택필수라는 오류메시지를 띄울 것이다.

regist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        str_name = name.getText().toString();
        str_studentid = studentid.getText().toString();
        str_grade = "";
        if (one.isChecked()) str_grade = one.getText().toString();
        if (two.isChecked()) str_grade = two.getText().toString();
        if (three.isChecked()) str_grade = three.getText().toString();
        
        if (hobby01.isChecked()) str_hobby = str_hobby + hobby01.getText().toString();
        if (hobby02.isChecked()) str_hobby = str_hobby + hobby02.getText().toString();
        if (hobby03.isChecked()) str_hobby = str_hobby + hobby03.getText().toString();
    }
}); // regist

str_photoUri 선언 추가
아래로 내려와서 str_photoUri = photoUri.toString(); 추가한다.

str_photoUri = photoUri.toString();
Intent iit = new Intent(this, PersonInfo.class);

 
여기서 디스가 문제.. 온크릭 안에 레지스트버트 있다.
온크맄안에 버튼 있어서 버튼에서 현재 얘기한다면 액티비티 이름 말해줘야 하기 때문에
디스에 이름 말해줘야 됨 PersonReg.this
 
 
 
여기까지 PersonRegistApp의 총 코드이다.
 
AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.hyw_bpersonregistapp">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.HYW_BPersonRegistApp"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.HYW_BPersonRegistApp.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".PersonReg"
            android:theme="@style/Theme.HYW_BPersonRegistApp.NoActionBar"
            android:screenOrientation="portrait"
            android:label="인물등록"></activity>
    </application>

</manifest>

 
 
java > MainActivity

package com.example.hyw_bpersonregistapp;

import android.content.Intent;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

//import androidx.navigation.NavController;
//import androidx.navigation.Navigation;
//import androidx.navigation.ui.AppBarConfiguration;
//import androidx.navigation.ui.NavigationUI;

import com.example.hyw_bpersonregistapp.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
//    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings2) {
            // 인물 등록 액비티비 전환
            Intent it = new Intent(this, PersonReg.class);
            startActivity(it);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 
java > PresonReg

package com.example.hyw_bpersonregistapp;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
//import androidx.navigation.ui.AppBarConfiguration;

import com.example.hyw_bpersonregistapp.databinding.ActivityPersonregBinding;

public class PersonReg extends AppCompatActivity {
//    private AppBarConfiguration appBarConfiguration;
    private ActivityPersonregBinding binding;

    EditText name, studentid;
    RadioGroup grade;
    RadioButton one, two, three;
    CheckBox hobby01, hobby02, hobby03;
    ImageView findimage;
    Button regist;

    Spinner major;
    String[] str_major = {"스마트IT", "소프트웨어융합", "빅데이터", "AI융합"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        binding = ActivityPersonregBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);

        name = (EditText) findViewById(R.id.name);
        studentid = (EditText) findViewById(R.id.studentid);
        grade = (RadioGroup) findViewById(R.id.grade);
        one = (RadioButton) findViewById(R.id.one);
        two = (RadioButton) findViewById(R.id.two);
        three = (RadioButton) findViewById(R.id.three);
        hobby01 = (CheckBox) findViewById(R.id.hobby01);
        hobby02 = (CheckBox) findViewById(R.id.hobby02);
        hobby03 = (CheckBox) findViewById(R.id.hobby03);
        findimage = (ImageView) findViewById(R.id.findimage);
        regist = (Button) findViewById(R.id.regist);

        major = (Spinner) findViewById(R.id.major);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this, android.R.layout.simple_spinner_item, str_major);
        major.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_personreg, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings1) {
            // 홈 액비티비 전환
            Intent it = new Intent(this, MainActivity.class);
            startActivity(it);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 
 
res > layout > activity_main

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.HYW_BPersonRegistApp.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/Theme.HYW_BPersonRegistApp.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

 
res > layout > activity_personreg

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.HYW_BPersonRegistApp.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/Theme.HYW_BPersonRegistApp.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_personreg" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

 
 
res > layout > content_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:adjustViewBounds="true"/>
</LinearLayout>

 
res > layout > content_peronreg

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <!-- 설명 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="7dp">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="성 명"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="#61380B"
            android:gravity="center"/>
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/name"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="7dp">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="학 번"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="#61380B"
            android:gravity="center"/>
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/studentid"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="7dp">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="학 년"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="#61380B"
            android:gravity="center"/>

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/grade"
            android:orientation="horizontal">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1학년"
                android:id="@+id/one"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="2학년"
                android:id="@+id/two"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="3학년"
                android:id="@+id/three"/>
        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="7dp">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="전 공"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="#61380B"
            android:gravity="center"/>
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/major"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="7dp">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="취 미"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="#61380B"
            android:gravity="center"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="산행"
            android:id="@+id/hobby01"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="영화감상"
            android:id="@+id/hobby02"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="온라인게임"
            android:id="@+id/hobby03"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="7dp">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="사 진"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="#61380B"
            android:gravity="center"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/findimage"
            android:id="@+id/findimage"
            android:adjustViewBounds="true"
            android:clickable="true"
            android:onClick="findPhoto"/>
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="등록"
        android:layout_gravity="center"
        android:id="@+id/regist"/>
</LinearLayout>

 
 
res > menu > menu_main

<menu 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"
    tools:context="com.example.hyw_bpersonregistapp.MainActivity">
    <item
        android:id="@+id/action_settings2"
        android:orderInCategory="100"
        android:title="@string/action_settings2"
        app:showAsAction="never" />
</menu>

 
 
res > menu > menu_personinf

<menu 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"
    tools:context="com.example.hyw_bpersonregistapp.MainActivity">
    <item
        android:id="@+id/action_settings1"
        android:orderInCategory="100"
        android:title="@string/action_settings1"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_settings2"
        android:orderInCategory="100"
        android:title="@string/action_settings2"
        app:showAsAction="never" />
</menu>

 
res > menu > menu_personreg

<menu 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"
    tools:context="com.example.hyw_bpersonregistapp.MainActivity">
    <item
        android:id="@+id/action_settings1"
        android:orderInCategory="100"
        android:title="@string/action_settings1"
        app:showAsAction="never" />
</menu>

 
 
res > values > strings

<resources>
    <string name="app_name">LINC 인물관리</string>
    <string name="action_settings1">홈</string>
    <string name="action_settings2">인물등록</string>
    <string name="action_settings3">인물정보</string>
</resources>