我正在尝试使用Android Studio制作Android Messenger,我正在使用unclouded方法。我键入了一个代码来在网络中广播消息,我得到了一个"不兼容的类型"错误。
公共类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;
//这里不需要等待返回值 for(RemoteReference reference:buddyList) reference.asyncInvoke(&#34; receiveMsg&#34;,myName,msg); //将messenge打印到屏幕上 printMessage(myName,msg); }
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)
说有&#34;不兼容的类型&#34;。 预计:对象 发现:RemoteReference
我该如何解决问题?
答案 0 :(得分:0)
您已将buddylist
声明为ArrayList
类型。如果你想这样使用它:
for (RemoteReference reference : buddyList) { ... }
然后您需要将buddyList
声明为:
List<RemoteReference> buddyList;
另一种方法是:
for (Object obj : buddyList) {
RemoteReference reference = (RemoteReference) obj;
...
}
这是Java编程的基本误解/错误,它表明您并不完全了解泛型如何工作。
我强烈建议您在generics上花时间阅读(或重读)Oracle Java Tutorial流。