question

HeinzWscher-4832 avatar image
0 Votes"
HeinzWscher-4832 asked JarvanZhang-MSFT commented

Pass Objects between Activities

Good morning,

I have two Activities and would like to pass an object instance between them.
The object is of type WebDavClient from a nugetpacket.

// Activity a:
Intent intent = new Intent(this, typeof(NewAcivity));
intent.PutExtra("Client", JsonConvert.SerializeObject(client));

// Activity b:
client = JsonConvert.DeserializeObject<WebDavClient>(Intent.GetStringExtra("Client"));

Am I on the wrong track in general or does it only not work with this object?
How else can objects be passed?
Via the class Intent?

Many thanks for your help.

Translated with www.DeepL.com/Translator (free version)

dotnet-xamarin
· 10
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

it should be correct

pass-data-between-two-activities-in-xamarin-android-app-using-visual-studio-2015


what do you have with

 Intent.GetStringExtra("Client")

??

An empty string?




0 Votes 0 ·

Hello alessandrocaliaro,

I get a string of length 2 containing {}.
That's all.

0 Votes 0 ·

ok, you have no data... Are you sure that you object "client" in this line has some data?

 intent.PutExtra("Client", JsonConvert.SerializeObject(client));

0 Votes 0 ·
Show more comments

Hi, HeinzWscher-4832. There is nothing wrong with the code. I created a basic demo to test the code, it works as expected. Is there any error occur? Try to create a custom object class to replace 'WebDavClient' to test the function to check if the issue is caused by the 'WebDavClient' class.

0 Votes 0 ·

Hello JarvanZhang,

I tried to convert a Bitmap- and a Stream-Object via JsonConvert.SerializeObject().
In both cases I got Errors from JsonConvert.SerializeObject().

Could it be that only simple objects are serialisable through this function?

0 Votes 0 ·

The parameter of the 'JsonConvert.SerializeObject' method is type of object, which should work for all types. What error occured in your test? Please post more details about the error. And share the related code, it'll help to reproduce the problem.

0 Votes 0 ·
Show more comments

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT commented

Hello,​

Welcome to our Microsoft Q&A platform!

1.Try using a custom object class as the tranfer parameter. Here the sample code, please check:

//Activity1
Intent intent = new Intent(this, typeof(Activity1));
TestModel model = new TestModel { Name = "test_name" };
intent.PutExtra("model", JsonConvert.SerializeObject(model));
StartActivity(intent);

//Activity2
var model = JsonConvert.DeserializeObject<TestModel>(Intent.GetStringExtra("model"));
string text = model.Name;

//the model class
public class TestModel
{
    public TestModel()
    {
    }
    public string Name { get; set; }
}

If the above code works well, the issue should be due to the 'WebDavClient'.

2.To share the client between activities, you could also create a global variable of the application. Create a custom Application class for the project and add a parameter in the custom class.

[Application]
public class CustomApplication : Application
{
    protected CustomApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }

    public static TestModel TheModel = new TestModel();
}

//set the `android:name` to the custom application class
<manifest ...>
  <application android:name=".CustomApplication" ...>
  </application>
</manifest>

//Activity1
var model = CustomApplication.TheModel;
model.Name = "testing...";
StartActivity(new Intent(this, typeof(Activity1)));

//Activity2
string text = CustomApplication.TheModel.Name;


Best Regards,

Jarvan Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Could you please insert for example a Bitmap-Object into your class and serialize it?

//the model class
public class TestModel
{
public Bitmap aBitmap = null;
public TestModel()
{
}
public string Name { get; set; }
}

And tell me your results?

Thank you.

0 Votes 0 ·

I try to add a bitmap property to the object class and encountered the 'JsonSerializationException'. To fix this, we need to create a custom 'JsonConverter' class to convert the bitmap.

//Activity1
Intent intent = new Intent(this, typeof(Activity1));
TestModel model = new TestModel { Name = "test_name", TheBitmap = bitmap };
intent.PutExtra("model", JsonConvert.SerializeObject(model, new CustomConverter()));
StartActivity(intent);

//Activity2
var model = JsonConvert.DeserializeObject<TestModel>(Intent.GetStringExtra("model"), new CustomConverter());
var bitmap = model.TheBitmap;

public class CustomConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Bitmap);
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var m = new MemoryStream(Convert.FromBase64String((string)reader.Value));
        Bitmap bp = BitmapFactory.DecodeStream(m);
        return bp;
    }

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
    {
        MemoryStream m = new MemoryStream();
        Bitmap bmp = (Bitmap)value;
        bmp.Compress(Bitmap.CompressFormat.Png, 100, m);
        writer.WriteValue(Convert.ToBase64String(m.ToArray()));
    }
}

0 Votes 0 ·

Hello.
That was the missing link.
I did not know that I have to "pre-format/convert" the Object.

Thank you very much for your effort and help.

Thank you.

0 Votes 0 ·
Show more comments