使用Firebase填充ListView时遇到问题。在ListView中未添加任何其他视图。打开时应用程序崩溃。在添加ListView之前,Firebase的数据存储似乎可以正常工作。

build.gradle

compileSdkVersion 24
buildToolsVersion "24.0.2"
minSdkVersion 19
targetSdkVersion 24


MainActivity.java

public class MainActivity extends AppCompatActivity {

    Firebase ref;
    ArrayAdapter<ChatMessage> adapter;
    List<ChatMessage> messages;
    ListView messagesList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonSend = (Button) findViewById(R.id.buttonSend);
        final EditText textMessage = (EditText) findViewById(R.id.etMessage);
        messagesList = (ListView) findViewById(R.id.messagesList);

        Firebase.setAndroidContext(this);
        ref = new Firebase("https://nanochat-cc415.firebaseio.com/");

        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatMessage chat = new ChatMessage("Fatima",textMessage.getText().toString());
                ref.push().setValue(chat);
                textMessage.setText("");
            }
        });

        messages = new LinkedList<>();

        adapter = new ArrayAdapter<ChatMessage>(this, android.R.layout.two_line_list_item, messages)
        {
            @Override
            public View getView(int position, View view, ViewGroup parent) {
                if(view == null) {
                    view = getLayoutInflater().inflate(android.R.layout.two_line_list_item, parent, false);
                }
                    ChatMessage chat = messages.get(position);
                    ((TextView)view.findViewById(R.id.text1)).setText(chat.getName());
                    ((TextView)view.findViewById(R.id.text2)).setText(chat.getMessage());

                return view;
            }
        };

        messagesList.setAdapter(adapter);

        ref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                ChatMessage chat = dataSnapshot.getValue(ChatMessage.class);
                messages.add(chat);
                adapter.notifyDataSetChanged();
            }

            @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(FirebaseError firebaseError) {

            }
        });

    }
}

最佳答案

尝试使用R.id.text1更改android.R.id.text1,并使用R.id.text2更改android.R.id.text2

关于android - 错误:在two_line_list_item中找不到符号变量text1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41346183/

10-09 09:33