Android 当点击进入聊天室时,应用程序崩溃

Android 当点击进入聊天室时,应用程序崩溃,android,listview,firebase,firebase-realtime-database,chatroom,Android,Listview,Firebase,Firebase Realtime Database,Chatroom,我在应用程序中使用此链接的聊天室 我的应用程序流: 登录->主要活动->从列表视图中选择一个团队加入聊天->聊天室活动 我的问题是,当我单击listview中的一个团队时,它崩溃了。我的聊天室代码与链接完全相同,只是我将MainActivity更改为ChatRoomActivity并删除了登录弹出窗口。其余的都一样。有人能帮我纠正它或找出原因吗 主要活动: public class MainActivity extends AppCompatActivity { public static f

我在应用程序中使用此链接的聊天室

我的应用程序流:

登录->主要活动->从列表视图中选择一个团队加入聊天->聊天室活动

我的问题是,当我单击listview中的一个团队时,它崩溃了。我的聊天室代码与链接完全相同,只是我将MainActivity更改为ChatRoomActivity并删除了登录弹出窗口。其余的都一样。有人能帮我纠正它或找出原因吗

主要活动:

public class MainActivity extends AppCompatActivity {
public static final String TEAM_NAME = "com.example.user.stfv2.teamname";
public static final String TEAM_ID = "com.example.user.stfv2.teamid";

private FirebaseAuth firebaseAuth;

EditText editTextName;
EditText textDate;
EditText textTime;
Spinner spinnerSport;
Button buttonAddTeam;
ListView listViewTeams;
DatePickerDialog datePickerDialog;

List<Team> teams;

DatabaseReference databaseTeams;

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

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() == null){

        finish();

        startActivity(new Intent(this, SignInActivity.class));
    }

    FirebaseUser user = firebaseAuth.getCurrentUser();

    databaseTeams = FirebaseDatabase.getInstance().getReference("teams");

    editTextName = (EditText) findViewById(R.id.editTextName);
    spinnerSport = (Spinner) findViewById(R.id.spinnerSports);
    listViewTeams = (ListView) findViewById(R.id.listViewTeams);
    textDate = (EditText) findViewById(R.id.textDate);
    textTime = (EditText) findViewById(R.id.textTime);


    buttonAddTeam = (Button) findViewById(R.id.buttonAddTeam);

    teams = new ArrayList<>();

    buttonAddTeam.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent myIntent = new Intent(MainActivity.this,
                    AddActivity.class);
            startActivity(myIntent);
        }
    });


    listViewTeams.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            Team team = teams.get(i);


            Intent intent = new Intent(getApplicationContext(), ChatRoomActivity.class);

            intent.putExtra(TEAM_ID, team.getTeamId());
            intent.putExtra(TEAM_NAME, team.getTeamName());

            startActivity(intent);
        }
    });

    listViewTeams.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            Team team = teams.get(i);
            showUpdateDeleteDialog(team.getTeamId(), team.getTeamName());
            return true;
        }
    });

}

private void showUpdateDeleteDialog(final String teamId, String teamName) {

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.update_dialog, null);
    dialogBuilder.setView(dialogView);

    final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);
    final Spinner spinnerSport = (Spinner) dialogView.findViewById(R.id.spinnerSports);
    final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateTeam);
    final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteTeam);
    final EditText textDate = (EditText) dialogView.findViewById(R.id.textDate);
    final EditText textTime = (EditText) dialogView.findViewById(R.id.textTime);

    dialogBuilder.setTitle(teamName);
    final AlertDialog b = dialogBuilder.create();
    b.show();

    textDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final Calendar c = Calendar.getInstance();
            int mYear = c.get(Calendar.YEAR); 
            int mMonth = c.get(Calendar.MONTH); 
            int mDay = c.get(Calendar.DAY_OF_MONTH); 

            datePickerDialog = new DatePickerDialog(MainActivity.this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {

                            textDate.setText(dayOfMonth + "/"
                                    + (monthOfYear + 1) + "/" + year);

                        }
                    }, mYear, mMonth, mDay);
            datePickerDialog.show();
        }
    });

    textTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    textTime.setText(selectedHour + ":" + selectedMinute);
                }
            }, hour, minute, true);
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();

        }
    });


    buttonUpdate.setOnClickListener(new View.OnClickListener() {

        FirebaseUser user = firebaseAuth.getCurrentUser();

        @Override
        public void onClick(View view) {
            String name = editTextName.getText().toString().trim();
            String sport = spinnerSport.getSelectedItem().toString();
            String owner = user.getUid();
            String date = textDate.getText().toString();
            String time = textTime.getText().toString();
            if (!TextUtils.isEmpty(name)) {
                updateTeam(teamId, name, sport, owner, date, time);
                b.dismiss();
            }
        }
    });


    buttonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            deleteTeam(teamId);
            b.dismiss();
        }
    });
}

private boolean updateTeam(String id, String name, String sport, String owner, String date, String time) {

    DatabaseReference dR = FirebaseDatabase.getInstance().getReference("teams").child(id);

    Team team = new Team(id, name, sport, owner, date, time);
    dR.setValue(team);
    Toast.makeText(getApplicationContext(), "Team Updated", Toast.LENGTH_LONG).show();
    return true;
}

private boolean deleteTeam(String id) {

    DatabaseReference dR = FirebaseDatabase.getInstance().getReference("teams").child(id);


    dR.removeValue();


    DatabaseReference drTracks = FirebaseDatabase.getInstance().getReference("tracks").child(id);

    drTracks.removeValue();
    Toast.makeText(getApplicationContext(), "Team Deleted", Toast.LENGTH_LONG).show();

    return true;
}

@Override
protected void onStart() {
    super.onStart();

    databaseTeams.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


            teams.clear();


            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                Team team = postSnapshot.getValue(Team.class);

                teams.add(team);
            }

            TeamList teamAdapter = new TeamList(MainActivity.this, teams);

            listViewTeams.setAdapter(teamAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_logout:

            firebaseAuth.signOut();

            finish();

            startActivity(new Intent(this, SignInActivity.class));
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
}
编辑1:

聊天室布局图:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.user.stfv2.MainActivity">

<RelativeLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/header"
    android:gravity="end">

    <ImageView
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:id="@+id/userIcon"
        android:foregroundGravity="center"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true" />

    <TextView
        android:layout_width="141dp"
        android:layout_height="wrap_content"
        android:id="@+id/usernameTxt"
        android:layout_toRightOf="@+id/userIcon"
        android:layout_alignTop="@+id/userIcon"
        android:layout_alignBottom="@+id/userIcon"
        android:gravity="center_vertical"
        tools:text="Username"
        android:layout_weight="0" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sign in"
        android:id="@+id/loginBtn"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sign out"
        android:id="@+id/logoutBtn"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true" />
</RelativeLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/messagesList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    tools:listitem="@android:layout/two_line_list_item"
    android:layout_above="@+id/footer"
    android:layout_below="@+id/header" />

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/footer">

    <ImageButton
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:id="@+id/imageBtn"
        android:background="@android:drawable/ic_menu_gallery" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/messageTxt"
        android:layout_gravity="bottom"
        android:layout_weight="1"
        android:inputType="textShortMessage|textAutoCorrect" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/sendBtn"
        android:layout_gravity="bottom" />
</LinearLayout>
</RelativeLayout>

聊天室活动:

public class ChatRoomActivity extends AppCompatActivity {
private static final String TAG = "ChatRoomActivity";

static final int RC_PHOTO_PICKER = 1;

private Button sendBtn;
private EditText messageTxt;
private RecyclerView messagesList;
private ChatMessageAdapter adapter;
private ImageButton imageBtn;
private TextView usernameTxt;
private View loginBtn;
private View logoutBtn;

private FirebaseApp app;
private FirebaseDatabase database;
private FirebaseAuth auth;
private FirebaseStorage storage;

private DatabaseReference databaseRef;
private StorageReference storageRef;

private String username;

private void setUsername(String username) {
    Log.d(TAG, "setUsername("+String.valueOf(username)+")");
    if (username == null) {
        username = "Android";
    }
    boolean isLoggedIn = !username.equals("Android");
    this.username = username;
    this.usernameTxt.setText(username);
    this.logoutBtn.setVisibility(isLoggedIn ? View.VISIBLE : View.GONE);
    this.loginBtn .setVisibility(isLoggedIn ? View.GONE    : View.VISIBLE);
}

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

    sendBtn = (Button) findViewById(R.id.sendBtn);
    messageTxt = (EditText) findViewById(R.id.messageTxt);
    messagesList = (RecyclerView) findViewById(R.id.messagesList);
    imageBtn = (ImageButton) findViewById(R.id.imageBtn);
    loginBtn = findViewById(R.id.loginBtn);
    logoutBtn = findViewById(R.id.logoutBtn);
    usernameTxt = (TextView) findViewById(R.id.usernameTxt);
    setUsername("Android");

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    messagesList.setHasFixedSize(false);
    messagesList.setLayoutManager(layoutManager);

    // Show an image picker when the user wants to upload an imasge
    imageBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
        }
    });
    // Show a popup when the user asks to sign in
    loginBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            LoginDialog.showLoginPrompt(ChatRoomActivity.this, app);
        }
    });
    // Allow the user to sign out
    logoutBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            auth.signOut();
        }
    });

    adapter = new ChatMessageAdapter(this);
    messagesList.setAdapter(adapter);
    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        public void onItemRangeInserted(int positionStart, int itemCount) {
            messagesList.smoothScrollToPosition(adapter.getItemCount());
        }
    });

    // Get the Firebase app and all primitives we'll use
    app = FirebaseApp.getInstance();
    database = FirebaseDatabase.getInstance(app);
    auth = FirebaseAuth.getInstance(app);
    storage = FirebaseStorage.getInstance(app);

    // Get a reference to our chat "room" in the database
    databaseRef = database.getReference("chat");

    sendBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ChatMessage chat = new ChatMessage(username, messageTxt.getText().toString());
            // Push the chat message to the database
            databaseRef.push().setValue(chat);
            messageTxt.setText("");
        }
    });
    // Listen for when child nodes get added to the collection
    databaseRef.addChildEventListener(new ChildEventListener() {
        public void onChildAdded(DataSnapshot snapshot, String s) {
            // Get the chat message from the snapshot and add it to the UI
            ChatMessage chat = snapshot.getValue(ChatMessage.class);
            adapter.addMessage(chat);
        }

        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
        public void onChildRemoved(DataSnapshot dataSnapshot) { }
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
        public void onCancelled(DatabaseError databaseError) { }
    });

    // When the user has entered credentials in the login dialog
    LoginDialog.onCredentials(new OnSuccessListener<LoginDialog.EmailPasswordResult>() {
        public void onSuccess(LoginDialog.EmailPasswordResult result) {
            // Sign the user in with the email address and password they entered
            auth.signInWithEmailAndPassword(result.email, result.password);
        }
    });

    // When the user signs in or out, update the username we keep for them
    auth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
        public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() != null) {
                // User signed in, set their email address as the user name
                setUsername(firebaseAuth.getCurrentUser().getEmail());
            }
            else {
                // User signed out, set a default username
                setUsername("Android");
            }
        }
    });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();

        // Get a reference to the location where we'll store our photos
        storageRef = storage.getReference("chat_photos");
        // Get a reference to store file at chat_photos/<FILENAME>
        final StorageReference photoRef = storageRef.child(selectedImageUri.getLastPathSegment());

        // Upload file to Firebase Storage
        photoRef.putFile(selectedImageUri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // When the image has successfully uploaded, we get its download URL
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        // Set the download URL to the message box, so that the user can send it to the database
                        messageTxt.setText(downloadUrl.toString());
                    }
                });
    }
}
}
公共类聊天室活动扩展了AppCompatActivity{
私有静态最终字符串标记=“聊天室活动”;
静态最终整数RC_PHOTO_PICKER=1;
私人按钮发送;
私有EditText-messageTxt;
私有RecyclerView消息列表;
专用聊天信息适配器;
专用图像按钮图像BTN;
私有文本视图usernameTxt;
私有视图登录;
私用视图logoutBtn;
私有FirebaseApp;
私有FirebaseDatabase数据库;
私有FirebaseAuth-auth;
私有火基存储;
私有数据库参考数据库参考;
私有存储引用storageRef;
私有字符串用户名;
私有void setUsername(字符串用户名){
Log.d(标记“setUsername”(+String.valueOf(username)+”);
如果(用户名==null){
用户名=“安卓”;
}
布尔值isLoggedIn=!username.equals(“Android”);
this.username=用户名;
this.usernameTxt.setText(用户名);
this.logoutBtn.setVisibility(isLoggedIn?View.VISIBLE:View.GONE);
this.loginBtn.setVisibility(isLoggedIn?View.go:View.VISIBLE);
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn=(按钮)findviewbyd(R.id.sendBtn);
messageTxt=(EditText)findViewById(R.id.messageTxt);
messagesList=(RecyclerView)findViewById(R.id.messagesList);
imageBtn=(ImageButton)findViewById(R.id.imageBtn);
loginBtn=findviewbyd(R.id.loginBtn);
logoutBtn=findviewbyd(R.id.logoutBtn);
usernameTxt=(TextView)findViewById(R.id.usernameTxt);
setUsername(“安卓”);
LinearLayoutManager layoutManager=新的LinearLayoutManager(此);
messagesList.setHasFixedSize(false);
messagesList.setLayoutManager(layoutManager);
//当用户想要上传图像时显示图像选择器
imageBtn.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
意向意向=新意向(意向.行动\u获取\u内容);
intent.setType(“图像/jpeg”);
intent.putExtra(仅intent.EXTRA_本地_,true);
startActivityForResult(Intent.createChooser(Intent,“使用完成操作”),RC\u PHOTO\u PICKER;
}
});
//当用户要求登录时显示弹出窗口
loginBtn.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
LoginDialog.showLoginPrompt(聊天室活动.this,应用程序);
}
});
//允许用户注销
logoutBtn.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
auth.signOut();
}
});
适配器=新的ChatMessageAdapter(此);
messagesList.setAdapter(适配器);
registerAdapterDataObserver(新的RecyclerView.AdapterDataObserver(){
已插入的公用项目(int positionStart、int itemCount){
messagesList.smoothScrollToPosition(adapter.getItemCount());
}
});
//获取Firebase应用程序和我们将使用的所有原语
app=FirebaseApp.getInstance();
database=FirebaseDatabase.getInstance(应用程序);
auth=FirebaseAuth.getInstance(应用程序);
存储=FirebaseStorage.getInstance(应用程序);
//在数据库中获取对聊天室的引用
databaseRef=database.getReference(“chat”);
sendBtn.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
ChatMessage chat=新的ChatMessage(用户名,messageTxt.getText().toString());
//将聊天信息推送到数据库
databaseRef.push().setValue(聊天);
messageTxt.setText(“”);
}
});
//侦听何时将子节点添加到集合中
databaseRef.addChildEventListener(新的ChildEventListener(){
公共void onchildaded(DataSnapshot快照,字符串s){
//从快照中获取聊天信息并将其添加到UI
ChatMessage chat=snapshot.getValue(ChatMessage.class);
adapter.addMessage(聊天);
}
public void onChildChanged(DataSnapshot DataSnapshot,字符串s){}
公共void onChildRemoved(DataSnapshot DataSnapshot){}
public void onChildMoved(DataSnapshot DataSnapshot,字符串s){}
已取消的公共void(DatabaseError DatabaseError){}
});
//当用户在登录对话框中输入凭据时
LoginDialog.onCredentials(新的OnSuccessListener(){
成功时公共无效(LoginDialog.EmailPasswordResult){
//使用用户输入的电子邮件地址和密码登录
使用email和password(result.email、result.password)进行身份验证登录;
}
});
//当用户登录或注销时,更新我们为他们保留的用户名
auth.addAuthStateListener(新的FirebaseAuth.AuthStateListener(){
AuthStateChanged上的公共无效(FirebaseAuth FirebaseAuth){
如果(firebaseAuth.getCurrentUser()!=null){
//用户登录后,将其电子邮件地址设置为用户名
setUsername(firebaseAuth.getCurrentUser().getEmail());
}
否则{
//用户已注销,请设置默认用户名
setUsername(“安卓”);
}
}
});
}
activityresult(int请求代码、int结果)上的公共无效
public class ChatRoomActivity extends AppCompatActivity {
private static final String TAG = "ChatRoomActivity";

static final int RC_PHOTO_PICKER = 1;

private Button sendBtn;
private EditText messageTxt;
private RecyclerView messagesList;
private ChatMessageAdapter adapter;
private ImageButton imageBtn;
private TextView usernameTxt;
private View loginBtn;
private View logoutBtn;

private FirebaseApp app;
private FirebaseDatabase database;
private FirebaseAuth auth;
private FirebaseStorage storage;

private DatabaseReference databaseRef;
private StorageReference storageRef;

private String username;

private void setUsername(String username) {
    Log.d(TAG, "setUsername("+String.valueOf(username)+")");
    if (username == null) {
        username = "Android";
    }
    boolean isLoggedIn = !username.equals("Android");
    this.username = username;
    this.usernameTxt.setText(username);
    this.logoutBtn.setVisibility(isLoggedIn ? View.VISIBLE : View.GONE);
    this.loginBtn .setVisibility(isLoggedIn ? View.GONE    : View.VISIBLE);
}

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

    sendBtn = (Button) findViewById(R.id.sendBtn);
    messageTxt = (EditText) findViewById(R.id.messageTxt);
    messagesList = (RecyclerView) findViewById(R.id.messagesList);
    imageBtn = (ImageButton) findViewById(R.id.imageBtn);
    loginBtn = findViewById(R.id.loginBtn);
    logoutBtn = findViewById(R.id.logoutBtn);
    usernameTxt = (TextView) findViewById(R.id.usernameTxt);
    setUsername("Android");

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    messagesList.setHasFixedSize(false);
    messagesList.setLayoutManager(layoutManager);

    // Show an image picker when the user wants to upload an imasge
    imageBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
        }
    });
    // Show a popup when the user asks to sign in
    loginBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            LoginDialog.showLoginPrompt(ChatRoomActivity.this, app);
        }
    });
    // Allow the user to sign out
    logoutBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            auth.signOut();
        }
    });

    adapter = new ChatMessageAdapter(this);
    messagesList.setAdapter(adapter);
    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        public void onItemRangeInserted(int positionStart, int itemCount) {
            messagesList.smoothScrollToPosition(adapter.getItemCount());
        }
    });

    // Get the Firebase app and all primitives we'll use
    app = FirebaseApp.getInstance();
    database = FirebaseDatabase.getInstance(app);
    auth = FirebaseAuth.getInstance(app);
    storage = FirebaseStorage.getInstance(app);

    // Get a reference to our chat "room" in the database
    databaseRef = database.getReference("chat");

    sendBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ChatMessage chat = new ChatMessage(username, messageTxt.getText().toString());
            // Push the chat message to the database
            databaseRef.push().setValue(chat);
            messageTxt.setText("");
        }
    });
    // Listen for when child nodes get added to the collection
    databaseRef.addChildEventListener(new ChildEventListener() {
        public void onChildAdded(DataSnapshot snapshot, String s) {
            // Get the chat message from the snapshot and add it to the UI
            ChatMessage chat = snapshot.getValue(ChatMessage.class);
            adapter.addMessage(chat);
        }

        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
        public void onChildRemoved(DataSnapshot dataSnapshot) { }
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
        public void onCancelled(DatabaseError databaseError) { }
    });

    // When the user has entered credentials in the login dialog
    LoginDialog.onCredentials(new OnSuccessListener<LoginDialog.EmailPasswordResult>() {
        public void onSuccess(LoginDialog.EmailPasswordResult result) {
            // Sign the user in with the email address and password they entered
            auth.signInWithEmailAndPassword(result.email, result.password);
        }
    });

    // When the user signs in or out, update the username we keep for them
    auth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
        public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() != null) {
                // User signed in, set their email address as the user name
                setUsername(firebaseAuth.getCurrentUser().getEmail());
            }
            else {
                // User signed out, set a default username
                setUsername("Android");
            }
        }
    });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();

        // Get a reference to the location where we'll store our photos
        storageRef = storage.getReference("chat_photos");
        // Get a reference to store file at chat_photos/<FILENAME>
        final StorageReference photoRef = storageRef.child(selectedImageUri.getLastPathSegment());

        // Upload file to Firebase Storage
        photoRef.putFile(selectedImageUri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // When the image has successfully uploaded, we get its download URL
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        // Set the download URL to the message box, so that the user can send it to the database
                        messageTxt.setText(downloadUrl.toString());
                    }
                });
    }
}
}