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

时间:2017-03-19 02:06:40

标签: android listview firebase firebase-realtime-database chatroom

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

https://gist.github.com/puf/f49a1b07e92952b44f2dc36d9af04e3c

我的应用流程:

登录 - > MainActivity - >从列表视图中选择一个团队加入聊天 - > ChatRoomActivity

我的问题是当我点击列表视图中的某个团队时,它会崩溃。我的聊天室代码与链接完全相同,除了我将MainActivity更改为ChatRoomActivity并删除了登录弹出窗口。其余的保持不变。有人帮我纠正或找出原因吗?

MainActivity:

$(document).ready(function() {


  $( ".player" ).animate({ "down": "-=50px" }, "slow" );
  $( ".player" ).animate({ "left": "-=80px" }, "slow" );
  $( ".player" ).animate({ "down": "-=50px" }, "slow" );
  $( ".player" ).animate({ "right": "-=30px" }, "slow" );
  $( ".player" ).animate({ "down": "-=50px" }, "slow" );

logcat的:

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:

layout_chat_room:

03-19 01:40:25.709 2995-2995/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.example.user.stfv2, PID: 2995
                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.stfv2/com.example.user.stfv2.ChatRoomActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                 at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:148)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                 at com.example.user.stfv2.ChatRoomActivity.setUsername(ChatRoomActivity.java:58)
                                                 at com.example.user.stfv2.ChatRoomActivity.onCreate(ChatRoomActivity.java:73)
                                                 at android.app.Activity.performCreate(Activity.java:6237)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                 at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                 at android.os.Looper.loop(Looper.java:148) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

ChatRoomActivity:

<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>

1 个答案:

答案 0 :(得分:1)

您的问题是您正在定义错误的XML文件。当您使用ChatroomActivity中的代码时,您忘记更改XML文件。它目前设置为setContentView(R.layout.activity_main),但应为setContentView(R.layout.layout_chat_room)