Я пытаюсь создать Android-мессенджер с помощью Android Studio, и я использую незамутненный метод. Я набрал код для трансляции сообщения в сети и получил ошибку «Несовместимые типы».

открытый класс MessengerActivity расширяет Activity {
// Unclouded event loop
private Unclouded unclouded;
// Flag to indicate whether device is connected to the network or not
private boolean isOnline;
// Name that is entered in the splash activity
private String myName;
// Adapter to update the list view with string messages
private ArrayAdapter<String> conversationArrayAdapter;
// List of remote references to other devices in the network
private ArrayList buddyList;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messenger);
buddyList = new ArrayList<>();
isOnline = false;
Intent intent = getIntent();
myName = intent.getStringExtra("NAME");
ListView conversationView = (ListView) findViewById(R.id.conversation_view);
Button sendButton = (Button) findViewById(R.id.send_button);
conversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
conversationView.setAdapter(conversationArrayAdapter);
// Make listView to scroll down automatically
conversationView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
// When entering a messenger, clear the field and broadcast the messenger
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
EditText msgField = (EditText) findViewById(R.id.msg_field);
String msg = msgField.getText().toString();
msgField.setText("");
broadcastMessage(msg);
}
});
// Obtain Unclouded event loop
unclouded = Unclouded.getInstance();
// Go online and connected to the network
com.unclouded.android.Network network = unclouded.goOnline();
// Monitor the network connection to update the isOnline flag
network.whenever(new NetworkListener() {
public void isOnline(InetAddress ip) {
isOnline = true;
}
public void isOffline(InetAddress ip) {
isOnline = false;
buddyList.clear();
}
});
// MESSENGER type tag to associate with the messenger service
TypeTag MESSENGER_TYPETAG = new TypeTag("MESSENGER");
// New instance of the Messenger class.
Messenger myMessenger = new Messenger();
// myMessenger is broadcasted by reference (because Messenger implements UObject)
// This makes a remote reference to this object to be spread across the network
unclouded.broadcast(MESSENGER_TYPETAG, myMessenger);
// Listen for remote reference associated with the MESSENGER_TYPETAG type tag
unclouded.whenever(MESSENGER_TYPETAG, new ServiceListener<RemoteReference>() {
String buddyName;
@Override
public void isDiscovered(RemoteReference remoteReference) {
// When discovering a buddy, register the remote reference to its Messenger object
buddyList.add(remoteReference);
// Asynchronously ask for his name
Promise promise = remoteReference.asyncInvoke("getName");
// Listen for the name to be returned
promise.when(new PromiseListener<String>() {
@Override
public void isResolved(String name) {
// When name is returned, store it and print messenger on the screen
buddyName = name;
printBuddyJoinedMessage(name);
}
});
}
@Override
public void isDisconnected(RemoteReference remoteReference) {
// When disconnected, remove buddy from list
buddyList.remove(remoteReference);
// If name is already resolved, print disconnection messenger on the screen
if (buddyName != null) { // Null in case disconnection occurs before name is resolved
printBuddyDisconnectedMessage(buddyName);
}
}
@Override
public void isReconnected(RemoteReference remoteReference) {
// When reconnecting, check whether name has been resolved before
if (buddyName == null) {
// If not, treat like a new connection
isDiscovered(remoteReference);
} else {
// Otherwise, add reference to list and print messenger on the screen
buddyList.add(remoteReference);
printBuddyJoinedMessage(buddyName);
}
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.messenger, menu);
return true;
}
@Override
// Dynamically change menu depending on network status
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.messenger, menu);
MenuItem item = menu.findItem(R.id.action_change_network_status);
if (isOnline) {
// If connected to the network, show `go offline' action
item.setTitle(R.string.action_go_offline);
} else {
// If disconnected from the network, show `go online' action
item.setTitle(R.string.action_go_online);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_change_network_status:
if (isOnline) {
// When clicked and network is online, go offline
unclouded.goOffline();
} else {
// When clicked and network is offline, go online
unclouded.goOnline();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Broadcast a messenger in the network
private void broadcastMessage(String msg) {
// Loop over all discovered buddies...
// ... and asynchronously invoke their receiveMsg method;
// Здесь не нужно ждать возврата значения для (Ссылка RemoteReference: buddyList) reference.asyncInvoke ("receiveMsg", myName, msg); // Выводим сообщение на экран printMessage (myName, сообщение); }
private void printMessage(final String name, final String msg) {
addToAdapter(name + ": " + msg);
}
private void printBuddyJoinedMessage(final String name) {
addToAdapter(name + " has joined the conversation.");
}
private void printBuddyDisconnectedMessage(final String name) {
addToAdapter(name + " has left the conversation.");
}
// Main method to print something on the screen
private void addToAdapter(final String msg) {
// Necessary because most invocations are initiated by the Unclouded event loop
runOnUiThread(new Runnable() {
public void run() {
conversationArrayAdapter.add(msg);
}
});
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Messenger Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
// ------------------------------------------
// Instances of the Messenger class are spread across the network
// and allow other devices to share messages
protected class Messenger implements UObject {
public String getName() {
return myName;
}
public void receiveMsg(String name, String msg) {
printMessage(name, msg);
}
}
}
А была и ошибка в for (RemoteReference reference : buddyList)
говоря, что есть «несовместимые типы». Ожидается: объект Найдено: RemoteReference
Как я могу исправить проблему?
Пожалуйста, как я могу это решить?
Можем ли мы увидеть весь класс, чтобы сделать реализацию buddyList видимой?
Я добавил весь класс к вопросу




Вы указали, что buddylist имеет тип ArrayList. Если вы хотите использовать это так:
for (RemoteReference reference : buddyList) { ... }
тогда вам нужно объявить buddyList как:
List<RemoteReference> buddyList;
Другой подход:
for (Object obj : buddyList) {
RemoteReference reference = (RemoteReference) obj;
...
}
Это базовое недоразумение / ошибка программирования Java, и оно указывает на то, что вы не до конца понимаете, как работают дженерики.
Я настоятельно рекомендую вам найти время, чтобы прочитать (или перечитать) поток Oracle Java Tutorial на дженерики.
Вероятное объяснение состоит в том, что тип
buddyListне поддерживаетIterable<RemoteReference>.