我在Main Activity之外创建了一个java类,但我无法访问它以在我的Main Activity中使用getter

时间:2018-03-27 16:35:03

标签: java android

我无法获得我的Message课程,我在其中将我的getter和setter设置为在Main Activity中使用。我的编码在getContent() void onStart()中显示错误。以下是主要活动的代码:

package com.example.tejindersingh.chatapplication;

public class MainActivity extends AppCompatActivity {

private EditText editMessage;
private DatabaseReference mDatabase;
private RecyclerView mMessageList;

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

    editMessage = (EditText) findViewById(R.id.editMessageE);
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Messages");
    mMessageList = (RecyclerView) findViewById(R.id.messageRec);
    mMessageList.setHasFixedSize(true);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setStackFromEnd(true);
    mMessageList.setLayoutManager(linearLayoutManager);
    MainActivity mActivity= new MainActivity();


}

public void sendButtonClicked(View view){
    final String messageValue = editMessage.getText().toString().trim();
    if(!TextUtils.isEmpty(messageValue)){
        final DatabaseReference newPost = mDatabase.push();
        newPost.child("Content").setValue(messageValue);
    }
}

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

    FirebaseRecyclerAdapter <Message,MessageViewHolder> FBRA = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(
            Message.class,
            R.layout.singlemessagelayout,
            MessageViewHolder.class,
            mDatabase
    ) {
        @Override
        protected void populateViewHolder(MessageViewHolder viewHolder, Message model, int position) {

            viewHolder.setContent(model.getContent()); //Problem here

        }
    };
    mMessageList.setAdapter(FBRA);
}

public static class MessageViewHolder extends RecyclerView.ViewHolder{

    View mView;
    public MessageViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }


    public void setContent(String content){
        TextView message_content = (TextView) mView.findViewById(R.id.messageText);
        message_content.setText(content);

    }
}

}

这显示了我在其中设置getter和setter的外部Message类的代码。

1 个答案:

答案 0 :(得分:0)

当您调用populateViewHolder方法时。 Message model参数的String content为空。要更改它,您需要使用setContent方法。

尝试这样做:

  @Override
    protected void populateViewHolder(MessageViewHolder viewHolder, Message model, int position) {

        model.setContent("Write Here Your Content"); //new line of code
        viewHolder.setContent(model.getContent()); 

    }