Reputation: 6381
I am developing in Android. I tried sending a Bluetooth object to another Activity.
Code:
BluetoothSocket btSocket;
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra(EXTRA_BT_SOCKET,btSocket);
startActivity(i);
But it seems to be not working and it shows an error like:
Cannot resolve method 'putExtra(java.lang.String, android.bluetooth.BluetoothSocket)
How to send the Bluetooth object via intent to another Activity in Android?
Thanks in advance.
Upvotes: 1
Views: 4935
Reputation: 1643
Hey @Wun I know it is too late but I found a simple way to do that, in your first activity just start the activity and send your object:
Intent intent = new Intent(this, Second.class);
intent.putExtra("rideId", yourObject);
startActivity(intent);
And in the Second Activity:
String id = extras.getString("rideId");
try {
JSONObject mJsonObject = new JSONObject(id);
} catch (JSONException e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 95568
You can't put a BluetoothSocket
instance in a Bundle
or pass it as an Intent
"extra" like that. This would require serializing and deserializing the object, which would make a copy of the object. You can't copy a socket like that. What you want to do is just share the object between multiple activities. The easiest way to do that is to put a reference to the object in a public static
variable somewhere and just use it from all activities that need access.
Upvotes: 2
Reputation: 346
you can pass it as a bundle through the intent
Bundle bundle = new Bundle();
bundle.putParcelable("yourObject key name", YOUR_OBJECT); //make YOUR_OBJECT implement parcelable
Intent intents = new Intent(ActivityA.this, ActivityB.class);
intents.putExtra(Constants.BUNDLE_DATA, bundle);
startActivity(intents);
At recieving end (ActivityB.class)
if (intent != null && intent.hasExtra(Constants.BUNDLE_DATA)) {
Bundle bundle = intent.getBundleExtra(Constants.BUNDLE_DATA);
if (bundle != null && bundle.containsKey(yourObject key name)) {
Object yourObject = bundle.getParcelable(yourObject keyname);
}
Upvotes: -1
Reputation: 639
Use a helper class
public class BluetoothSocketHelper implements Serializable {
public BluetoothSocket btSocket;
//Constructor + getter/setters
}
Sending from ActivityA:
BluetoothSocketHelper bluetoothSocketHelper;
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra(DeviceListActivity.EXTRA_ADDRESS, address);
i.putExtra(EXTRA_BT_SOCKET, bluetoothSocketHelper);
startActivity(i);
Then in ActivityB:
private BluetoothSocket btSocket;
if(getIntent().getExtras()!=null){
bluetoothSocketHelper = (BluetoothSocketHelper) getIntent().getSerializableExtra(EXTRA_BT_SOCKET);
btSocket = (BluetoothSocket) bluetoothSocketHelper.getBluetoothSocket();
}
Upvotes: 0
Reputation: 89
Use the following to send and retrieve objects:
//To pass: intent.putExtra("MyClass", obj);
// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
Upvotes: 1