Polyglot's language & programming story.

Firebase2 ) Udacity 예제 분석 및 스튜디오에 파이어베이스 SDK 설치하기 본문

Programming/AndroidProgramming

Firebase2 ) Udacity 예제 분석 및 스튜디오에 파이어베이스 SDK 설치하기

Polyglot 2018. 7. 6. 21:17

Udacity 예제 분석 및 스튜디오에 파이어베이스 SDK 설치하기

안녕하세요. 저번 포스팅에서는 파이어베이스와 파이어베이스를 이용한 데이터베이스의 구조를 살펴보았습니다. 이번에는 udacity 주말안에 파이어베이스를 이용해서 채팅앱 만들기 강의 예제를 분석하고 안드로이드에 파이어베이스 SDK를 설치해보도록 하겠습니다.

먼저 예제 파일을 받습니다.

firebase예제 파일

깃을 통해 예제를 받았으면. 이 예제를 한번 분석해봅시다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class FriendlyMessage {
 
    private String text;
    private String name;
    private String photoUrl;
 
    public FriendlyMessage() {
    }
 
    public FriendlyMessage(String text, String name, String photoUrl) {
        this.text = text;
        this.name = name;
        this.photoUrl = photoUrl;
    }
 
    public String getText() {
        return text;
    }
 
    public void setText(String text) {
        this.text = text;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getPhotoUrl() {
        return photoUrl;
    }
 
    public void setPhotoUrl(String photoUrl) {
        this.photoUrl = photoUrl;
    }
}

위 코드는 메시지 데이터를 정의한 메시지 클래스입니다. 단순히 텍스트, 네임, 사진 주소 등으로 셋터와 겟터, 생성자만 있는 POJO 클래스입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class MessageAdapter extends ArrayAdapter<FriendlyMessage> {
    public MessageAdapter(Context context, int resource, List<FriendlyMessage> objects) {
        super(context, resource, objects);
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_message, parent, false);
        }
 
        ImageView photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
        TextView messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
        TextView authorTextView = (TextView) convertView.findViewById(R.id.nameTextView);
 
        FriendlyMessage message = getItem(position);
 
        boolean isPhoto = message.getPhotoUrl() != null;
        if (isPhoto) {
            messageTextView.setVisibility(View.GONE);
            photoImageView.setVisibility(View.VISIBLE);
            Glide.with(photoImageView.getContext())
                    .load(message.getPhotoUrl())
                    .into(photoImageView);
        } else {
            messageTextView.setVisibility(View.VISIBLE);
            photoImageView.setVisibility(View.GONE);
            messageTextView.setText(message.getText());
        }
        authorTextView.setText(message.getName());
 
        return convertView;
    }
}

위 코드는 리스트뷰에 데이터를 표시하기 위해 사용되는 어뎁터입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class MainActivity extends AppCompatActivity {
 
    private static final String TAG = "MainActivity";
 
    private static final int RC_SIGN_IN = 100;
 
    public static final String ANONYMOUS = "anonymous";
    public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
 
    private ListView mMessageListView;
    private MessageAdapter mMessageAdapter;
    private ProgressBar mProgressBar;
    private ImageButton mPhotoPickerButton;
    private EditText mMessageEditText;
    private Button mSendButton;
 
    private String mUsername;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        mUsername = ANONYMOUS;
 
        // 뷰를 초기화합니다.
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mMessageListView = (ListView) findViewById(R.id.messageListView);
        mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
        mMessageEditText = (EditText) findViewById(R.id.messageEditText);
        mSendButton = (Button) findViewById(R.id.sendButton);
 
        // 어뎁터와 리스트뷰를 초기화합니다.
        List<FriendlyMessage> friendlyMessages = new ArrayList<>();
        mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
        mMessageListView.setAdapter(mMessageAdapter);
 
        // 프로그레스바를 설정합니다.
        mProgressBar.setVisibility(ProgressBar.INVISIBLE);
 
        // 이미지 선택 버튼이 클릭 되었을 때 처리를 합니다.
        mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: Fire an intent to show an image picker
            }
        });
 
        // 텍스트를 입력했을 때 전송버튼이 활성화 됩니다.
        mMessageEditText.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) {
                if (charSequence.toString().trim().length() > 0) {
                    mSendButton.setEnabled(true);
                } else {
                    mSendButton.setEnabled(false);
                }
            }
 
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
 
        // 전송버튼이 클릭되었을 때 처리
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: Send messages on click
                // Clear input box
                mMessageEditText.setText("");
            }
        });
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
 
}

위 코드는 텍스트를 입력받고 버튼을 눌렀을 때 처리가 되는 부분 및 리스트뷰와 어뎁터를 정의한 부분 입니다.

위 예제는 카카오톡처럼 메시지를 입력받아 전송버튼을 누르면 리스트뷰에 내용이 갱신이되는 단순한 채팅 어플입니다.

firebase SDK 받고 사용할 준비 하기

firebase를 안드로이드 스튜디오에서 사용하기 위해서는 firebase에 들어가서 프로젝트를 만들고 SDK 추가하는 부분이 필요합니다. firebase SDK를 안드로이드 스튜디오에서 사용하기 위해서는 다음과 같은 과정이 필요합니다.

  1. firebase 프로젝트 생성 및 설정
  2. 안드로이드에 라이브러리 추가

그렇다면 한번 실습을 해보겠습니다.

  1. firebase 프로젝트 생성 및 설정


파이어베이스 홈페이지를 들어가서 프로젝트 추가를 눌러 프로젝트를 추가합니다. (당연히... 구글 계정이 필요합니다.)


프로젝트 이름을 짓는건 어떻게 짓든 자유고. 지역은 대한민국으로 지정합니다.


프로젝트를 만들고 조금 기다리면 메인 페이지가 나옵니다. 이 메인 페이지에서 "Android 앱에 Firebase 추가"를 클릭합니다.


Mainfest.xml에 들어가서 패키지명을 입력합니다.


SHA1 키를 받기위해서 안드로이드 스튜디오 오른쪽에 위치하고있는 Gradle 탭을 클릭합니다.


거기서 signingReport 파일을 눌러서 console창에 뜨는 SHA1 키를 받아냅니다.



다음을 누르게 되면 google-service.json을 다운받아 프로젝트 보기로 전환한 뒤 app폴더 안에 파일을 이동시킵니다.


위 사진을 보면 google-services.json이 app 폴더 아래에 있는 것을 확인할 수가 있습니다.

  1. 안드로이드에 라이브러리 추가


프로젝트 수준의 build.gradle 파일에 가서 다음과 같이 설정합니다.


그리고 앱 수준의 build.gradle 파일에 가서 다음과 같이 설정합니다.

마지막에 apply plugin을 넣는것을 잊지맙시다.!!

위 예제는 udacity에 있는 버전을 참고하고 있지만.

최신 버전의 firebase를 사용하기 위해서는 firebase 문서를 통해서 확인 하실 수 있습니다.

Comments