I have a class named PageItem
, which has a constructor that takes a Context
as parameter:
PageItem(Context context)
{
super(context);
this.context = context;
}
PageItem
has these properties:
private int id;
private String Title;
private String Description;
public Newsprovider newsprovider;
public Topic topic;
Newsprovider
and Topic
are other classes of my application and have the following constructors:
Newsprovider (Context context)
{
super(context);
this.context = context;
}
Topic (Context context)
{
super(context);
this.context = context;
}
PageItem
, Newsprovider
and Topic
are subclasses of SQLiteOpenHelper
.
I want to deserialize PageItem
array with Gson, so I wrote:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PageItem.class, new PageItemInstanceCreator(context));
Gson gson = gsonBuilder.create();
Pageitem pis[] = gson.fromJson(s, PageItem[].class);
with PageItemInstanceCreator
defined as:
public class PageItemInstanceCreator implements InstanceCreator<PageItem>
{
private Context context;
public PageItemInstanceCreator(Context context)
{
this.context = context;
}
@Override
public PageItem createInstance(Type type)
{
PageItem pi = new PageItem(context);
return pi;
}
}
When debugging, a PageItem
instance has correctly "MainActivity" as context while
but its newsprovider
member variable has context = null.
Gson created PageItem
object using the right constructor but it created Newsprovider
instance using the default parameterless constructor. How can I fix this?
Just add a new InstanceCreator
derived class for NewsProvider
like this:
public class NewsProviderInstanceCreator implements InstanceCreator<NewsProvider>
{
private int context;
public NewsProviderInstanceCreator(int context)
{
this.context = context;
}
@Override
public NewsProvider createInstance(Type type)
{
NewsProvider np = new NewsProvider(context);
return np;
}
}
and register it into the GsonBuilder
like you have already done, like this:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PageItem.class, new PageItemInstanceCreator(context));
gsonBuilder.registerTypeAdapter(NewsProvider.class, new NewsProviderInstanceCreator(context));
Gson gson = gsonBuilder.create();
PageItem pis[] = gson.fromJson(s, PageItem[].class);
repeat it also for Topic
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With