firebase 안드로이드 2 단계 - tablayout framgment CustomAdapter 감사리스트 불러오기

소스코드

https://firebasestorage.googleapis.com/v0/b/testmemo-8978f.appspot.com/o/android_thanks_project%2FThanks2.zip?alt=media&token=41421387-7dbf-43a8-9e71-7dbdbe41750f



일지:

tablayout 을 구성하고, fragment를 만들어주었다. 

그리고 customAdaptView를 만들어서 listview에 넣어주었 (AdaptView를 통해서)

파이어베이스에서 데이터를 가져와서 리스트뷰에 뿌려주었다.


다음에 할 것:

1.감사리스트 써서 저장.

2.리스트뷰 갱신.

3.감사리스트 글 하나 클릭하면 다른 유저 프로필 페이지로 넘어가기.

4.(레이아웃만들어주고, 파이어 베이스에서 데이터 받아와서 뿌려주기, 뒤로가기 버튼 추가)

5.가입할 때 파이어베이스 user table에 user name 넣어주기.



소스코드








탭바 레이아웃


탭바 java

package me.happygate.thanks;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.Fragment;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {
//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;

private TextView mTextMessage;

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

switch (item.getItemId()) {
case R.id.navigation_home:
replaceFragment(Fragement_A_Activity.newInstnace());
return true;
case R.id.navigation_dashboard:
replaceFragment(Fragement_B_Activity.newInstnace());
return true;
case R.id.navigation_notifications:
replaceFragment(Fragement_C_Activity.newInstnace());
return true;
}
return false;
}

};

// Fragment 변환을 해주기 위한 부분, Fragment의 Instance를 받아서 변경
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content, fragment).commit();
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mTextMessage = (TextView) findViewById(R.id.message);

BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content, Fragement_A_Activity.newInstnace()).commit();

}


//로그인 되어있으면 currentUser 변수에 유저정보 할당. 아닌경우 login 페이지로 이동!
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if(currentUser == null){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}


}




리스트뷰



리스트뷰 소스코드

package me.happygate.thanks;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class Fragement_A_Activity extends Fragment {

public static Fragement_A_Activity newInstnace(){
return new Fragement_A_Activity();
}

//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;
//데이터 베이스 저장
private static FirebaseDatabase database;

//감사리스트 데이터 담을 리스트
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> contents = new ArrayList<String>();
ArrayList<String> dates = new ArrayList<String>();
ArrayList<String> thankPK = new ArrayList<String>();
ArrayList<String> userKey = new ArrayList<String>();

CustomAdapter ca; //커스텀 어뎁터

//제일 먼저 호출
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
Log.d("myTag1", "onCreate-0");
displayThanks();
}
//두번째 호출됨
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

Activity root = getActivity(); //이 클래스가 프레그먼트이기 때문에 액티비티 정보를 얻는다.
Log.d("myTag1", "onCreateView-1");
Log.d("myTag2", "onCreateView-2");
View view = inflater.inflate(R.layout.activity_fragement__a_,container,false);

ListView listView = (ListView)view.findViewById(R.id.listView);
final EditText editText = (EditText)view.findViewById(R.id.thanksTxtField);
final Button writeBtn = (Button)view.findViewById(R.id.thankWriteButton);
writeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
writeBtn.setText(editText.getText().toString());
}
});

ca = new CustomAdapter();
listView.setAdapter(ca);

return view;

}
//커스텀 뷰
class CustomAdapter extends BaseAdapter{
@Override
public int getCount() {
return names.size();
}
@Override
public long getItemId(int position) {
return 0;
}

@Override
public Object getItem(int position) {
return null;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {

Activity root = getActivity(); //이 클래스가 프레그먼트이기 때문에 액티비티 정보를 얻는다.
Toast.makeText(root,"getView" , Toast.LENGTH_SHORT).show();

//커스텀뷰에 있는 객체들 가져오기
convertView = getLayoutInflater().inflate(R.layout.custom_listview_layout,null);
TextView tName = (TextView)convertView.findViewById(R.id.textView_name);
TextView tDate = (TextView)convertView.findViewById(R.id.textView_date);
TextView tContent = (TextView)convertView.findViewById(R.id.textView_content);

tName.setText(names.get(position));
tDate.setText(dates.get(position));
tContent.setText(contents.get(position));
return convertView;
}
}

//감사 리스트 호출 함수
public void displayThanks(){
database.getReference("thanks/")
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//개수 만큼 돈다

//Activity root = getActivity(); //이 클래스가 프레그먼트이기 때문에 액티비티 정보를 얻는다.
//Toast.makeText(root,"onChildAdded-2" , Toast.LENGTH_SHORT).show();
Log.d("myTag3", "onChildAdded-2");


ThankDTo thankDTo = dataSnapshot.getValue(ThankDTo.class);
//키값이랑 같이 넣어주기
thankDTo.setThankPK(dataSnapshot.getKey());

//Activity root = getActivity(); //이 클래스가 프레그먼트이기 때문에 액티비티 정보를 얻는다.
//Toast.makeText(root, thankDTo.getName()+"/"+ thankDTo.getComment(), Toast.LENGTH_SHORT).show();

names.add(thankDTo.getName());
dates.add(thankDTo.getCreatetime());
contents.add(thankDTo.getComment());
thankPK.add(thankDTo.getThankPK());
userKey.add(thankDTo.getUserkey());

int a = names.size();
String aa = String.valueOf(a);
Log.d("myTagrsult", aa);
//이거를 해줘야지 adapter getView가 호출이 된다!!!!중요!!!
ca.notifyDataSetChanged();
//Toast.makeText(root, aa , Toast.LENGTH_SHORT).show();
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}

}



커스텀 레이아웃







  1. dk0011 2018.10.11 14:59 신고

    names.add(thankDTo.getName());
    dates.add(thankDTo.getCreatetime());
    contents.add(thankDTo.getComment());
    thankPK.add(thankDTo.getThankPK());
    userKey.add(thankDTo.getUserkey());

    int a = names.size();
    String aa = String.valueOf(a);
    Log.d("myTagrsult", aa);
    //이거를 해줘야지 adapter getView가 호출이 된다!!!!중요!!!

    여기서 정확히 어떤 코드가 adapter의 getView가 호출이 된다는건지 알려주실 수 있나요?

firebase 안드로이드 1 단계 - 설정 로그인 가입 기능




소스코드 다운로드


https://firebasestorage.googleapis.com/v0/b/testmemo-8978f.appspot.com/o/android_thanks_project%2FAndroid_Thanks1.zip?alt=media&token=f9cda798-6348-4bbd-8d89-d5e4c0af0f61



* 초기 설정


0. 안드로이드 플랫폼 설정해주기


1.Google-play.service.json app 수준에 넣어준다.


2.프로젝트 빌드 그래들 열어서 Sdk 추가하기


3.앱모듈안에도 sdk 넣어준다.


4.싱크 나우 눌러주기


5.안되면 구글 리파지토리, sdk 업데이트


 6.Apply plugin 아랫줄에 복사해서 넣어준다.


프로젝트 생성





구성파일 다운로드






프로젝트 수준 build.gradle




메니페스트





앱 수준 build.gradle




서명 인증서






서명인증서











--------------------------------------------------------------------------------------------------------------------------------------------------














join.activity


package me.happygate.thanks;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseAuthWeakPasswordException;
import com.google.firebase.auth.FirebaseUser;

public class JoinActivity extends AppCompatActivity {

//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;

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

mAuth = FirebaseAuth.getInstance();

//이메일
final EditText emailTxt = (EditText)findViewById(R.id.emailTxt);
//이름
final EditText nameTxt = (EditText)findViewById(R.id.nameTxt);
//비밀번호
final EditText pwTxt = (EditText)findViewById(R.id.pwTxt);
//버튼
Button joinBtn = (Button)findViewById(R.id.joinBtn);


//버튼이 눌렀을 때
joinBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String email = emailTxt.getText().toString();
String name = nameTxt.getText().toString();
String pw = pwTxt.getText().toString();


Toast.makeText(JoinActivity.this,email +"/=가입 버튼 눌리고" + name +"/" + pw,Toast.LENGTH_SHORT).show();


//가입 성공했을 때 -> 감사리스트 메인 페이지로 이동하기

//Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
//startActivityForResult(signInIntent, 100);Toast.makeText(AuthActivity.this,"btn",Toast.LENGTH_SHORT).show();
//Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
// startActivityForResult(signInIntent, 100);

joinStart(email,name,pw);
}
});

}
//가입 함수
public void joinStart(String email, final String name, String password){

mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

if(!task.isSuccessful()) {
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
Toast.makeText(JoinActivity.this,"비밀번호가 간단해요.." ,Toast.LENGTH_SHORT).show();
} catch(FirebaseAuthInvalidCredentialsException e) {
Toast.makeText(JoinActivity.this,"email 형식에 맞지 않습니다." ,Toast.LENGTH_SHORT).show();
} catch(FirebaseAuthUserCollisionException e) {
Toast.makeText(JoinActivity.this,"이미존재하는 email 입니다." ,Toast.LENGTH_SHORT).show();
} catch(Exception e) {
Toast.makeText(JoinActivity.this,"다시 확인해주세요.." ,Toast.LENGTH_SHORT).show();
}
}else{

currentUser = mAuth.getCurrentUser();

Toast.makeText(JoinActivity.this, "가입 성공 " + name + currentUser.getEmail() + "/" + currentUser.getUid() ,Toast.LENGTH_SHORT).show();

startActivity(new Intent(JoinActivity.this, MainActivity.class));
finish();
}
}
});

}
}




login.activity

package me.happygate.thanks;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseNetworkException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthInvalidUserException;
import com.google.firebase.auth.FirebaseUser;

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{

//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance(); //이메일 비밀번호 로그인 모듈 변수

//이메일
final EditText emailTxt = (EditText)findViewById(R.id.emailTxt);
//비밀번호
final EditText pwTxt = (EditText)findViewById(R.id.pwTxt);
//버튼
Button joinBtn = (Button)findViewById(R.id.joinBtn);


//이메일
final TextView goJoinTxt = (TextView)findViewById(R.id.goJoinTxt);

//로그인 버튼이 눌렀을 때
joinBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String email = emailTxt.getText().toString();
String password = pwTxt.getText().toString();

//로그인 성공했을 때 -> 감사리스트 메인 페이지로 이동하기
loginStart(email, password);
}
});

//가입하러 가기 버튼 눌렀을 때
goJoinTxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(LoginActivity.this,"가입하러 가기 버튼 눌렀을 때",Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, JoinActivity.class));
finish();
}
});

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this,"연결이 해제되었습니다",Toast.LENGTH_SHORT).show();
}

//public Boolean check;
public void loginStart(String email, String password){
Toast.makeText(LoginActivity.this,"loginStart 함수 안으로" ,Toast.LENGTH_SHORT).show();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

Toast.makeText(LoginActivity.this,"mAuth. onComplete 함수" ,Toast.LENGTH_SHORT).show();
if (!task.isSuccessful()) {
try {
throw task.getException();
} catch (FirebaseAuthInvalidUserException e) {
Toast.makeText(LoginActivity.this,"존재하지 않는 id 입니다." ,Toast.LENGTH_SHORT).show();
} catch (FirebaseAuthInvalidCredentialsException e) {
Toast.makeText(LoginActivity.this,"이메일 형식이 맞지 않습니다." ,Toast.LENGTH_SHORT).show();
} catch (FirebaseNetworkException e) {
Toast.makeText(LoginActivity.this,"Firebase NetworkException" ,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(LoginActivity.this,"Exception" ,Toast.LENGTH_SHORT).show();
}

}else{


currentUser = mAuth.getCurrentUser();

Toast.makeText(LoginActivity.this, "로그인 성공" + "/" + currentUser.getEmail() + "/" + currentUser.getUid() ,Toast.LENGTH_SHORT).show();

startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}

}
});
}

//로그아웃 안했으면, 즉 로그인 되어있으면 자동으로 메인페이지로 이동시키기
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if(currentUser != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}



}







Main.activity


package me.happygate.thanks;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {
//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;

private TextView mTextMessage;

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(currentUser.getEmail());
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(currentUser.getUid());
return true;
case R.id.navigation_notifications:
mTextMessage.setText(currentUser.getEmail());
return true;
}
return false;
}

};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mTextMessage = (TextView) findViewById(R.id.message);

BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}


//로그인 되어있으면 currentUser 변수에 유저정보 할당. 아닌경우 login 페이지로 이동!
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if(currentUser == null){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}


}










=============================================================================================================================









다음작업


1.가입할때 user name 파이어베이스 db에 push 시켜주기


2.로그아웃 기능



3.땡스피드 페이지 꾸미기 - tap layout , intent, viewpager  체크


*글쓰기 기능 - 저장 , null 체크

*조회 - 감사리스트 불러오기

*글 누르면 다른 user 프로필 페이지로 이동하기





+ Recent posts

티스토리 툴바