Troubles with binding drawable icons in dropdown in MVVMCross Xamarin.Android - xamarin.android

I need to add pictures to dropdown items.
In the dropdown I need to see the icon first and the text below. But for some reason, I can't see images, though I see the empty place instead.
My project is Xamarin.Android with MVVMCross. I'm missing something, maybe I need some plugins?
I have MypageView.axml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="#layout/toolbar" />
<TextView
android:id="#+id/city"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:textSize="12sp"
android:layout_below="#id/toolbar"
local:MvxBind="Text Strings[CityTextView]" />
<MvxSpinner
android:id="#+id/select_city"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="24dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:spinnerMode="dropdown"
android:layout_below="#id/city"
local:MvxItemTemplate="#layout/item_city"
local:MvxDropDownItemTemplate="#layout/item_city"
local:MvxBind="ItemsSource Cities; SelectedItem SelectedCity" />
And item_city.axml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<ImageView
android:id="#+id/cityImage"
android:layout_width="35dp"
android:layout_height="20dp"
android:layout_marginLeft="16dp"
android:scaleType="fitXY"
local:MvxBind="DrawableName Name, Converter=IconsConverter" /> />
<TextView
android:id="#+id/cityName"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="8dp"
android:layout_toRightOf="#id/cityImage"
android:textSize="16sp"
local:MvxBind="Text Name" />
</RelativeLayout>
In the Core, I have City.cs:
namespace My.cities.Core.Models
{
public class City
{
public City(string Id, string Name, string Flag)
{
this.Id = Id;
this.Name = Name;
this.Flag = Flag;
}
public string Id { get; set; }
public string Name { get; set; }
public string Flag { get; set; }
}
}
And MypageViewModel.cs:
using MvvmCross.Core.ViewModels;
using System.Collections.Generic;
using My.cities.Core.Models;
namespace My.cities.Core.ViewModels
{
public class MypageViewModel : BaseViewModel
{
private City _selectedCity;
private List<City> _cities = new List<City>()
{
new City("1", "London", "England")
new City("2", "Paris", "France")
};
public List<City> Cities
{
get { return _cities; }
}
public City SelectedCity
{
get
{
return _selectedCity;
}
set
{
_selectedCity = value;
RaisePropertyChanged(() => SelectedCity);
}
}
}
}
So I add the converter to MypageView.cs:
using Android.App;
using MvvmCross.Platform.Converters;
using System;
using System.Globalization;
namespace My.cities.Droid.Views
{ [Activity]
class MypageView : BaseView
{
protected override int LayoutResource => Resource.Layout.MypageView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
}
public static class CrossDeviceInfoHelper
{
public static string GetLocalImageUrlByPlatform(string name)
{
return CrossDeviceInfo.Current.Platform == Platform.Android ? $"#drawable/{name}" : name;
}
}
public class IconsConverter : MvxValueConverter<string, string>
{
protected override string Convert(string value, Type targetType, object parameter, CultureInfo culture)
{
if (value == "London")
return CrossDeviceInfoHelper.GetLocalImageUrlByPlatform("england");
if (value == "Paris")
return CrossDeviceInfoHelper.GetLocalImageUrlByPlatform("france");
}
}
Images England.png and France.png live here: My.sities.Droid\Resources\drawable-hdpi, My.sities.Droid\Resources\drawable-mdpi, and etc.
The build is successful, but I can't see my images, only empty rectangles. Why?
UPD.
I installed Xam.Plugin.DeviceInfo and changed my code. But I still can't see icons.
In debug it says:
[0:] MvxBind:Warning: 36,05 Value '' could not be parsed as a valid string identifier
[0:] MvxBind:Warning: 36,06 Value '' could not be parsed as a valid string identifier
[0:] MvxBind:Warning: 36,06 Value 'London' was not a known drawable name
[0:] MvxBind:Warning: 36,08 Value 'Paris' was not a known drawable name
UPD2.
Also, I tried to do it this way:
public class IconsConverter : MvxValueConverter<string, int>
{
protected override int Convert(string value, Type targetType,
object parameter, CultureInfo culture)
{
switch (value)
{
case "London":
return Resource.Mipmap.England;
case "Paris":
return Resource.Mipmap.France;
}
}
}
But the error is the same:
[0:] MvxBind:Warning: 9,54 Value '' could not be parsed as a valid string identifier
[0:] MvxBind:Warning: 9,63 Value '' could not be parsed as a valid string identifier
[0:] MvxBind:Warning: 9,64 Value 'London' was not a known drawable name
[0:] MvxBind:Warning: 9,65 Value 'Paris' was not a known drawable name

I think you are lacking the android:scaleType in your ImageView. Try using android:scaleType="fitXY".
If it is not that, try using the DrawableName binding instead of DrawableId and it's better because you can use a converter in your PCL making it cross-platform with Xam.Plugin.DeviceInfo and a helper method like this one:
public static class CrossDeviceInfoHelper
{
public static string GetLocalImageUrlByPlatform(string name)
{
// Assuming we are working with Android and iOS
return CrossDeviceInfo.Current.Platform == Platform.Android ? $"#drawable/{name}" : name;
}
}
So you'll endup with a Converter like this one:
public class StringToIntValueConverter : MvxValueConverter<string, string>
{
protected override string Convert(string value, Type targetType, object parameter, CultureInfo culture)
{
if (value == "London")
return CrossDeviceInfoHelper.GetLocalImageUrlByPlatform("england");
if (value == "Paris")
return CrossDeviceInfoHelper.GetLocalImageUrlByPlatform("france");
}
}
Also if I were you I'll add an enum or something that tells you the country in your City class so that you don't have to compare strings in the converter and you could also have a Dictionary in your converter that has which city goes with which country image so that you can just call CrossDeviceInfoHelper.GetLocalImageUrlByPlatform(myDictionary[value]); and therefore not using ifs

The binding expression DrawableName Name Converter=IconsConverter is wrong. You are missing a comma:
DrawableName Name, Converter=IconsConverter
Alternatively you can write it like:
DrawableName Icons(Name)

Related

mvxlistview click on item

I'm currently creating an app for Android using MvvmCross. Part of that app requires a MvxListView, where each item has 2 TextViews. One of these TextViews are hidden by default. I'm looking to implement an accordion like functionality, where clicking on the first TextView will show/hide the other TextView.
I've currently gotten most of this to work with the MvvmCross Visibility Plugin, but the click event is bound to the MvxListView instead of the TextView inside it. What I've currently gotten to work looks like this:
FirstViewModel:
public class FirstViewModel
: MvxViewModel
{
public FirstViewModel(IListService listService)
{
Interests = new ObservableCollection<Interest>();
List<Interest> tempInterests = listService.GetInterestFeeds("");
foreach (var interest in tempInterests)
{
interest._parent = this;
Interests.Add(interest);
}
var pluginLoader = new PluginLoader();
pluginLoader.EnsureLoaded();
}
private ObservableCollection<Interest> _interests;
public ObservableCollection<Interest> Interests
{
get { return _interests; }
set { _interests = value; RaisePropertyChanged(() => Interests); }
}
public ICommand ItemVisibleCommand
{
get
{
return new MvxCommand<Interest>(item => item.IsVisible = !item.IsVisible);
}
}
}
FirstView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
...>
<Mvx.MvxListView
...
local:MvxBind="ItemsSource Interests"
local:MvxItemTemplate="#layout/item_interests" />
</LinearLayout>
item_interests:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
local:MvxBind="Text InterestName" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
local:MvxBind="Text InterestDescription; Visibility IsVisible, Converter=Visibility" />
</LinearLayout>
In order to bind it to the TextView inside the MvxListView, I've been trying to modify my code to something similar to How to bind ItemClick in MvxListView in MvxListView as per the anwser by Stuart, resulting in the following code:
item_interest:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
local:MvxBind="Text InterestName; Click ItemVisibleCommand" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
local:MvxBind="Text InterestDescription; Visibility IsVisible, Converter=Visibility" />
</LinearLayout>
FirstViewModel:
public class FirstViewModel
: MvxViewModel
{
public FirstViewModel(IListService listService)
{
Interests = new ObservableCollection<Interest>();
List<Interest> tempInterests = listService.GetInterestFeeds("");
foreach (var interest in tempInterests)
{
interest._parent = this;
Interests.Add(interest);
}
var pluginLoader = new PluginLoader();
pluginLoader.EnsureLoaded();
}
private ObservableCollection<Interest> _interests;
public ObservableCollection<Interest> Interests
{
get { return _interests; }
set { _interests = value; RaisePropertyChanged(() => Interests); }
}
public void MakeItemVisible(bool isVisible)
{
isVisible = !isVisible;
}
Interest:
public class Interest : INotifyPropertyChanged
{
public string InterestId { get; set; }
public string InterestName { get; set; }
public string InterestDescription { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public FirstViewModel _parent { get; set; }
private bool _isVisible;
public bool IsVisible
{
get { return _isVisible; }
set
{
_isVisible = value;
onPropertyChanged(this, "IsVisible");
}
}
private void onPropertyChanged(object sender, string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
public Interest(string id, string name, string description)
{
//Initialisers
}
private MvxCommand<bool> _itemVisible;
public ICommand ItemVisibleCommand
{
get
{
_itemVisible = _itemVisible ?? new MvxCommand<bool>(IsVisible => _parent.MakeItemVisible(IsVisible));
return _itemVisible;
}
}
}
resulting in the following exception:
04-04 15:05:40.575 I/MonoDroid(18011): UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
04-04 15:05:40.575 I/MonoDroid(18011): at Cirrious.MvvmCross.ViewModels.MvxCommand`1<bool>.Execute (object) <IL 0x00010, 0x00088>
04-04 15:05:40.575 I/MonoDroid(18011): at Cirrious.MvvmCross.Binding.Droid.Target.MvxViewClickBinding.ViewOnClick (object,System.EventArgs) <IL 0x0001f, 0x000fb>
04-04 15:05:40.575 I/MonoDroid(18011): at Android.Views.View/IOnClickListenerImplementor.OnClick (Android.Views.View) [0x0000d] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.12-series/a1e3982a/source/monodroid/src/Mono.Android/platforms/android-15/src/generated/Android.Views.View.cs:1615
04-04 15:05:40.575 I/MonoDroid(18011): at Android.Views.View/IOnClickListenerInvoker.n_OnClick_Landroid_view_View_ (intptr,intptr,intptr) [0x00011] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.12-series/a1e3982a/source/monodroid/src/Mono.Android/platforms/android-15/src/generated/Android.Views.View.cs:1582
04-04 15:05:40.575 I/MonoDroid(18011): at (wrapper dynamic-method) object.a963c1ac-b573-4022-b41d-f0f002438c84 (intptr,intptr,intptr) <IL 0x00017, 0x00043>
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
Thanks in advance to anyone who's taken the time to read all that :)
UPDATE - I tried to do as Stuart suggested, and got the following solution:
First off, to preserve the original Interest entity, it got wrapped in an InterestWrapper.
public class InterestWrapper : INotifyPropertyChanged
{
private Interest _interest;
private InterestAndroidViewModel _parent; //TO-DO
public Interest Item { get { return _interest; } }
public event PropertyChangedEventHandler PropertyChanged;
private bool _isVisible;
public bool IsVisible
{
get { return _isVisible; }
set
{
_isVisible = value;
onPropertyChanged(this, "IsVisible");
}
}
private void onPropertyChanged(object sender, string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
public InterestWrapper(Interest interest, InterestAndroidViewModel parent)
{
IsVisible = false;
_interest = interest;
_parent = parent;
}
public IMvxCommand ItemVisibleCommand
{
get
{
return new MvxCommand(() => _parent.MakeItemVisible(_interest));
}
}
}
FirstViewModel
public class FirstViewModel
: MvxViewModel
{
public FirstViewModel(IListService listService)
{
Interests = new ObservableCollection<InterestWrapper>();
List<Interest> tempInterests = listService.GetInterestFeeds("");
foreach (var interest in tempInterests)
{
InterestWrapper wrapper = new InterestWrapper(interest, this);
Interests.Add(wrapper);
}
}
private ObservableCollection<InterestWrapper> _interests;
public ObservableCollection<InterestWrapper> Interests
{
get { return _interests; }
set { _interests = value; RaisePropertyChanged(() => Interests); }
}
public void MakeItemVisible(Interest interest)
{
if (interest.IsVisible)
{
interest.IsVisible = !interest.IsVisible;
}
else
{
foreach (var _interest in _interests)
{
_interest.Item.IsVisible = false;
}
interest.IsVisible = !interest.IsVisible;
}
}
}
item_interest:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
...
<RelativeLayout
...
<TextView
...
local:MvxBind="Text Item.InterestName; Click ItemVisibleCommand" />
<Mvx.MvxImageView
...
local:MvxBind="Visibility Item.IsVisible, Converter=InvertedVisibility; Click ShowEducationsCommand" />
</RelativeLayout>
</RelativeLayout>
The local:MvxBind="Text InterestName; Click ItemVisibleCommand" can only really call a non-parameterized MvxCommand - it can't call MvxCommand<bool> as it doesn't know what the bool value is.
If you wanted to, you could use the CommandParameter converter to pass in the value - e.g. local:MvxBind="Text InterestName; Click CommandParameter(ItemVisibleCommand, IsVisible)"
But overall, in this case I'd probably recommend rewriting ItemVisibleCommand as just a "toggle visible" command instead
Look through this question it's the as your one and has the solution suggested by Stuart, so think it's what you are looking for.
Binding button click in ListView template MvvMCross

Mvvmcross inconsistent binding within viewmodel

I'm experiencing strange behaviour in binding of simple EditText controls within one viewmodel. For some of the properties, the binding works, for others it does not while i cannot discover any difference in the way the code is written (both in cs and axml files). What could cause such baheviour ? How can one debug binding triggering problems ? Code snippets of two properties below. The first one works, the second doesn't...
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value; RaisePropertyChanged(() => FirstName);
}
}
private string _installer;
public string Installer
{
get { return _installer; }
set
{
_installer = value; RaisePropertyChanged(() => Installer);
}
}
axml :
<EditText
android:id="#+id/firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textSize="20sp"
android:hint="First Name"
local:MvxBind="Text FirstName" />
<EditText
android:id="#+id/installer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:hint="Installer"
Mvx.MvxBind="Text Installer"
android:layout_weight="1"/>

How to bind ItemClick in MvxListView in MvxListView

In my example below I want to bind an ItemClick Command to the Item in the MvxListView.
Here I have in my ViewModel a List of Person that contains a List of Dog.
The ItemsSource HasDogs binding works fine.
When MvvmCross is trying to bind ItemClick SelectDogCommand to the ICommand in the Viewmodel I get this Exception.
[0:]
MvxBind:Warning: 11,30 Unable to bind: source property source not found Property:SelectDogCommand on Person
[0:] MvxBind:Warning: 11,30 Unable to bind: source property source not found Property:SelectDogCommand on Person
12-04 15:05:03.062 I/mono-stdout(16338): MvxBind:Warning: 11,30 Unable to bind: source property source not found Property:SelectDogCommand on Person
Hope you can Help.
Here is my example:
public class FirstViewModel:MvxViewModel
{
private List<Person> _persons;
public List<Person> Persons
{
get { return _persons; }
set { _persons = value; }
}
private Cirrious.MvvmCross.ViewModels.MvxCommand<Dog> _selectDog;
public System.Windows.Input.ICommand SelectDogCommand
{
get
{
_selectDog = _selectDog ?? new Cirrious.MvvmCross.ViewModels.MvxCommand<Dog>(SelectDog);
return _selectDog;
}
}
private void SelectDog(Dog item)
{
ShowViewModel<DetailViewModel>(new DetailViewModel.Parameters{dog = item});
}
}
public class Person
{
private string _name;
private List<Dog> _hasDogs;
public List<Dog> HasDogs
{
get { return _hasDogs; }
set { _hasDogs = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}
public class Dog{...}
The Android View Xml:
FirstView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
...>
<TextView ...
local:MvxBind="Text Persons"
<Mvx.MvxListView
...
local:MvxBind="ItemsSource Persons"
local:MvxItemTemplate="#layout/item_person" />
</LinearLayout>
item_person:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
...
android:layout_height="200dp">
<TextView
...
local:MvxBind="Text Name" />
<Mvx.MvxListView
...
local:MvxBind="ItemsSource HasDogs; ItemClick SelectDogCommand"
local:MvxItemTemplate="#layout/item_dog" />
</LinearLayout>
The DataContext for your person list item is a Person - so your SelectDogCommand needs to be part of the Person class - e.g. something like:
public class Person
{
private string _name;
private List<Dog> _hasDogs;
public List<Dog> HasDogs
{
get { return _hasDogs; }
set { _hasDogs = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
private Cirrious.MvvmCross.ViewModels.MvxCommand<Dog> _selectDog;
public System.Windows.Input.ICommand SelectDogCommand
{
get
{
_selectDog = _selectDog ?? new Cirrious.MvvmCross.ViewModels.MvxCommand<Dog>(dog => _parent.SelectDog(dog));
return _selectDog;
}
}
private FirstViewModel _parent;
public Person(FirstViewModel parent)
{
_parent = parent;
}
}
or alternatively you could get Person to inherit from MvxNavigatingObject (or MvxPropertyChanged or MvxViewModel) - in which case the ShowViewModel methods will be available there too.

Spinner Control in Monodroid - Get ID and Text on Selection

I have started exploring the Spinner control just now. I have pretty much achieved what I wanted but only the last step is missing. Here is what I have done so far.
I have a very simple class for this example:
[Serializable]
public class Merchant
{
public Int64 MerchantId { get; set; }
public String ShopName { get; set; }
public override string ToString()
{
return ShopName;
}
}
Here is the axml where I placed the Spinner:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="1280dip"
android:layout_height="800dip">
<TextView
android:text="Select a merchant:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/lblSelect"
android:layout_marginLeft="30dip"
android:layout_marginTop="30dip"
android:textSize="42dip" />
<Spinner
android:id="#+id/spinMerchant"
android:layout_width="1000dip"
android:layout_height="wrap_content"
android:layout_below="#id/lblSelect"
android:prompt="#string/spinner_prompt"
android:layout_centerHorizontal="true"
android:minHeight="20dip" />
</RelativeLayout>
And my code is:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create your application here
this.SetContentView(Resource.Layout.MerchantSelect);
List<Merchant> lstMerchant = new List<Merchant> ();
lstMerchant.Add (new Merchant() { ShopName = "First Shop", MerchantId = 11 });
lstMerchant.Add (new Merchant() { ShopName = "Second Shop", MerchantId = 12 });
Spinner spinner = this.FindViewById<Spinner>(Resource.Id.spinMerchant);
ArrayAdapter adapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleSpinnerItem, lstMerchant);
spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (spinner_ItemSelected);
spinner.Adapter = adapter;
}
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
//Merchant merch = (Merchant)spinner.SelectedItem;
string toast = string.Format ("Selected text is {0}", spinner.GetItemAtPosition (e.Position));
Toast.MakeText (this, toast, ToastLength.Long).Show ();
}
I want to get the selected text as well as the ID behind it as soon as the selection is made. I get the text by spinner.GetItemAtPosition (e.Position) but I can't seem to find anything that can give me the ID. If I try to do Merchant merch = (Merchant)spinner.SelectedItem; I get an exception: Cannot convert type 'Java.Lang.Object' to 'Merchant'.
Please let me know how it can be achieved.
Thanks.
The spinner only knows about the text because that's what you have in your ToString() method it. The adapter that's providing the spinner data has no idea it is dealing with Merchant objects.
To get to the actual Merchant object, youll have to make your List<Merchant> lstMerchant a member of your class.
Then change your selection handler:
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
// Get the ID from your model.
Merchant merch = this.lstMerchant[e.Position];
var id = merch.MerchantId;
string toast = string.Format ("Selected text is {0}", spinner.GetItemAtPosition (e.Position));
Toast.MakeText (this, toast, ToastLength.Long).Show ();
}

Dozer initialize property with empty string

I need to initialize with Dozer a String property on destination obect with empty string.
Imagine these objects:
SRC
public class Container {
private String animalName;
....
DEST
public class Animal {
private String name;
private String type;
I need to initialize from Container to Animal and to set type property to "" and not null:
The only way I found is to write a Custom Converter as follows:
public class InitializeStringConverter extends DozerConverter<Container, String>{
public InitializeStringConverter() {
super(Container.class, String.class);
}
#Override
public Container convertFrom(String arg0, Container arg1) {
return null;
}
#Override
public String convertTo(Container arg0, String arg1) {
return "";
}
}
and having this mapping:
<mapping>
<class-a>it.alten.sample.mapping.Container</class-a>
<class-b>it.alten.sample.mapping.Animal</class-b>
<field custom-converter="it.alten.sample.mapping.converter.InitializeStringConverter">
<a>this</a>
<b>type</b>
</field>
<!--
<field>
<a>animalName</a>
<b>name</b>
</field>
-->
<field>
<a>animalType</a>
<b>type</b>
</field>
</mapping>
Is there a more concise way to accomplish this task?
Kind regards
Massimo
Dozer copies and converts values, it should not init fields in custom way as I think.
My solution for your problem:
Enable null mapping for class or field - docs
Create setter, which init field with empty value instead of null, like:
void setType(String type) {this.type = (type != null ? type : "");}
I think, it more clear solution for your problem, because null control is functionality of setter and it's right.

Resources