Ormlite ForeignCollection with Gson - android

Been struggling with this all day. I feel like I am one annotation away from the right solution.
I am getting an JSON from an API, and parsing it using Gson inside Volley request into a object.
Then I want to store the object in DB, using ORMLite.
The problem is that my JSON has lists of other objects. So I have decided that ForeignCollection are required.
Here is simplified version of what I am getting as JSON:
{
"b": [
{"title"="abc","id="24sfs"},
{"title"="def", "id="532df"}
],
"c": [
{"description"="abc","id="34325"},
{"description"="def", "id="34321"}
],
"id"="ejsa"
}
Lets call this whole object class A. The objects inside "b", are B, inside "c", class C.
B and C are the similar. This leads to the following class definitions:
class A {
#DatabaseField(index = true, unique = true, id = true)
private String id;
#ForeignCollectionField(eager = true)
public Collection<B> bCollection;
public ArrayList<B> b;
#ForeignCollectionField(eager = true)
public Collection<C> cCollection;
public ArrayList<C> c;
}
class B {
#DatabaseField(foreign=true)
public A a;
#DatabaseField(id = true, index = true, unique = true)
public String id;
#DatabaseField
public String title;
}
The reason we need the ArrayList b and c, is so that gson can parse it correctly. So once I have class A in memory, here is what I do to store it
private void storeA(A a) {
if (a.b != null) {
getHelper().getDao(B.class).callBatchTasks(new Callable<Void>() {
#Override
public Void call() throws Exception {
for (B b : a.b) {
b.a = a;
try {
getHelper().getDao(B.class).createOrUpdate(b);
} catch (Exception e) {
}
}
return null;
}
});
}
/*
Here we start running into problems. I need to move the data from the ArrayList to the Collection
*/
a.bCollection = a.b; // but this seems to work, since bCollection is a Collection
a.cCollection = a.c;
getHelper().getDao(A.class).createOrUpdate(a);
}
So it seems to store correctly, no errors as far as I can tell. But when I try to retrieve as follows, I can't retrieve anything out of bCollection:
private void load() {
try {
List<A> as = getHelper().getDao(A.class).queryForEq("id", "ejsa");
if (as != null && as.size() > 0) {
A a = as.get(0);
CloseableWrappedIterable<B> cwi = a.bCollection.getWrappedIterable();
try {
for (B b : cwi) {
Log.e(b.title);
}
} finally {
cwi.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
What am I doing wrong? Do I need to specify foreignColumnName for some of these things? I can't tell if the things are not being stored correctly or if I am just failing to retrieve them correctly?

I would try removing the following two lines:
a.bCollection = a.b;
a.cCollection = a.c;
A's ForeignCollection's should be auto-magically populated for you by ORMLite when you query for A, you do not need to set them yourself.

Related

How to serialize the response to object by using Gson?

I make request directly to VK api with token
Like this: https://api.vk.com/method/groups.get?fields=photo_50&access_token=MY_TOKEN&filter=admin%2C%20editor%2C%20moder&extended=1
Here is spec about api
But I can't serialize the response to object by using Gson, because is response array there is int value:
{
"response": [
2,
{
"gid": 59295,
"name": "Создание",
"screen_name": "book",
"is_closed": 0,
"type": "group",
"photo_50": "https://pp.userapi.com/qwvD6SPkYzo.jpg"
},
{
"gid": 57150,
"name": "Массаж",
"screen_name": "club10450",
"is_closed": 2,
"type": "group",
"photo_50": "https://pp.userapi.com/ZKnmRkS1izs.jpg"
}
]
}
How can I make serialize it to object by using Gson?
Despite you've already resolved the issue by changing the API version via the GET URL parameters, here is a method of dealing with "non-standard" JSONs you might face in the future. I'm assuming you have correct mappings, but the array length (presumably) is put as the very first array element. Gson cannot handle such a special case itself (at least if it expects {...} objects), probably giving you something like this:
Expected BEGIN_OBJECT but was NUMBER at line 3 column 10 path $.response[0]
Assuming you have mappings similar to the next two:
final class ElementsResponse {
#SerializedName("response")
final List<Element> response = null;
}
final class Element {
#SerializedName("gid")
final int gid = Integer.valueOf(0);
#SerializedName("name")
final String name = null;
#SerializedName("screen_name")
final String screenName = null;
#SerializedName("is_closed")
final int isClosed = Integer.valueOf(0);
#SerializedName("type")
final String type = "";
#SerializedName("photo_50")
final URL photo50 = null;
}
You can easily create your type adapter with a special type adapter factory in order to deal with the given JSON:
final class LengthArrayTypeAdapterFactory
implements TypeAdapterFactory {
// The instance holds no state and can be created as a singleton
private static final TypeAdapterFactory lengthArrayTypeAdapterFactory = new LengthArrayTypeAdapterFactory();
private LengthArrayTypeAdapterFactory() {
}
// However, the factory method does not let a caller to create an instance itself, and _may_ create it itself if necessary (encapsulation)
static TypeAdapterFactory getLengthArrayTypeAdapterFactory() {
return lengthArrayTypeAdapterFactory;
}
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
// Are we dealing with a java.util.List instance?
if ( List.class.isAssignableFrom(typeToken.getRawType()) ) {
// Resolve the list element type if possible
final Type elementType = getElementType(typeToken.getType());
// And request Gson for the element type adapter
final TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
// Some Java boilerplate regarding generics in order not letting the #SuppressWarnings annotation cover too much
#SuppressWarnings("unchecked")
final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) new LengthArrayTypeAdapter<>(elementTypeAdapter);
return castTypeAdapter;
}
// Or let Gson pick the next downstream type adapter itself
return null;
}
private static Type getElementType(final Type listType) {
// The given type is not parameterized?
if ( !(listType instanceof ParameterizedType) ) {
// Probably the (de)serialized list is raw being not parameterized
return Object.class;
}
final ParameterizedType parameterizedType = (ParameterizedType) listType;
// Or just take the first type parameter (java.util.List has one type parameter only)
return parameterizedType.getActualTypeArguments()[0];
}
private static final class LengthArrayTypeAdapter<E>
extends TypeAdapter<List<E>> {
// This type adapter is designed to read and write a single element only
// We'll take care of all elements array ourselves
private final TypeAdapter<E> elementTypeAdapter;
private LengthArrayTypeAdapter(final TypeAdapter<E> elementTypeAdapter) {
this.elementTypeAdapter = elementTypeAdapter;
}
#Override
public List<E> read(final JsonReader in)
throws IOException {
// Gson type adapters are supposed to be null-friendly
if ( in.peek() == NULL ) {
return null;
}
// Consume the array begin token `[`
in.beginArray();
// The next value is most likely the array length?
final int arrayLength = in.nextInt();
final List<E> list = new ArrayList<>();
// Read until the array has more elements
while ( in.hasNext() ) {
// And let the element type adapter read the array element so push the value to the list
list.add(elementTypeAdapter.read(in));
}
// Consume the array end token `]`
in.endArray();
assert arrayLength == list.size();
return list;
}
#Override
#SuppressWarnings("resource")
public void write(final JsonWriter out, final List<E> list)
throws IOException {
if ( list == null ) {
// Must be null-friendly always
out.nullValue();
} else {
// Writing the `[` token
out.beginArray();
// Writing the list size/length
out.value(list.size());
for ( final E element : list ) {
// And just write each array element
elementTypeAdapter.write(out, element);
}
// Finalizing the writing with `]`
out.endArray();
}
}
}
}
So all you had to do could be just adding the type adapter factory to the Gson configuration creating your special arrays-aware Gson:
final Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(getLengthArrayTypeAdapterFactory())
.create();
final ElementsResponse elementsResponse = gson.fromJson(JSON, ElementsResponse.class);
elementsResponse.response.forEach(e -> System.out.println(e.name));
System.out.println(gson.toJson(elementsResponse));
Output:
Создание
Массаж
{"response":[2,{"gid":59295,"name":"Создание","screen_name":"book","is_closed":0,"type":"group","photo_50":"https://pp.userapi.com/qwvD6SPkYzo.jpg"},{"gid":57150,"name":"Массаж","screen_name":"club10450","is_closed":2,"type":"group","photo_50":"https://pp.userapi.com/ZKnmRkS1izs.jpg"}]}
Note that this type adapter factory always assumes that the first array element is a number, and you might need to analyze the elementType if necessary (for example, if it's a java.lang.Number or its subclass).
Resolved, Added param to url v=5.61 version number
{
"response": {
"count": 190,
"items": [{
"id": 28261334,
"name": "TJ",
"screen_name": "tj",
"is_closed": 0,
"type": "page",
"is_admin": 0,
"is_member": 1,
"photo_50": "https://pp.vk.me/...f2c/06crfCSL1KY.jpg"
}]
}
}

Deserialize json with same key but different type in android using Jackson

I am calling web-services which can have 2 types of json object in response. Now sometimes i get key profile with type String and sometimes it may have same key with type 'ProfileSubObject'. So how to manage this case? Below are my two types of object. I am using Jackson library to parse json.
1.)
{
"data": [
{
"profession": "iOS Developer",
"thanks": {
"count": 5
},
"profile": "test"
}
]
}
2.)
{
"data": [
{
"profession": "iOS Developer",
"thanks": {
"count": 5
},
"profile": {
"val1":"test1",
"val2":"test2"
}
}
]
}
Key profile have 2 different type of object based on web-service call.
Following is my data class structure.
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class DataObject {
#JsonProperty("profession")
private String profession;
#JsonProperty("profile")
private ProfileObject profile;
#JsonProperty("thanks")
private ThanksObject thanks;
public String getProfession() {
return profession;
}
public ThanksObject getThanks() {
return thanks;
}
public ProfileObject getProfile() {
return profile;
}
}
And Profile class is as per below.
public class ProfileObject {
ProfileObject(){
}
ProfileObject(ProfileSubObject profileSubObject){
this.profileSubObject= profileSubObject;
}
ProfileObject(String profile){
this.profile= profile;
}
private ProfileSubObject profileSubObject;
private String profile;
public ProfileSubObject getProfileSubObject() {
return profileSubObject;
}
}
Now when i parse my object, ProfileObject is always null. I want it to get parsed based on proifle key data type.
Anyone could help me with parsing?
In constructing the solution, I faced two problems:
the Json structure does not match a single DataObject
the original problem of deserializing same property into differnt types of Java objects.
The first problem I solved by constructing JavaType objects which tell Jackson the generic type of the collections involved. There are two such collections: a Map, consisting of a single entry with key "data" and value of List of DataObjects
The second problem, I solved with the Jackson feature of #JsonAnySetter which directs Jackson to call a single method for all properties it doesn't recognize. For this purpose, I added #JsonIgnore to the profile variable to make sure that Jackson indeed doesn't recognize it. Now Jackson calls the same method for the two input jsons
This is the new DataObject class:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class DataObject
{
#JsonProperty("profession")
public String profession;
#JsonIgnore // forcing jackson to not recognize this property
public ProfileObject profile;
#JsonProperty("thanks")
public ThanksObject thanks;
public String getProfession() { return profession; }
public void setProfession(String p) { profession = p; }
public ThanksObject getThanks() { return thanks; }
public void setThanks(ThanksObject t) { thanks = t; }
public ProfileObject getProfile() { return profile; }
public void setProfile(ProfileObject p) { profile = p; }
#JsonAnySetter
public void setProfileFromJson(String name, Object value)
{
// if value is single String, call appropriate ctor
if (value instanceof String) {
profile = new ProfileObject((String)value);
}
// if value is map, it must contain 'val1', 'val2' entries
if (value instanceof Map) {
ProfileSubObject profileSubObject =
new ProfileSubObject(((Map<String, String>)value).get("val1"), ((Map<String, String>)value).get("val2"));
profile = new ProfileObject(profileSubObject);
}
// error?
}
}
Here is my test method, which includes the java type construction I mentioned:
public static void main(String[] args)
{
try (Reader reader = new FileReader("C://Temp/xx2.json")) {
ObjectMapper mapper = new ObjectMapper();
// type of key of map is String
JavaType stringType = TypeFactory.defaultInstance().constructType(String.class);
// type of value of map is list of DataObjects
JavaType listOfDataObject = TypeFactory.defaultInstance().constructCollectionType(List.class, DataObject.class);
// finally, construct map type with key and value types
JavaType rootMap = TypeFactory.defaultInstance().constructMapType(HashMap.class, stringType, listOfDataObject);
Map<String ,List<DataObject>> m = mapper.readValue(reader, rootMap);
DataObject do1 = m.values()
// get first (only?) value in map (it is list)
.stream().findFirst().orElse(Collections.emptyList())
// get first (only?) item in list - it is the DataObject
.stream().findFirst().orElse(null);
System.out.println(do1.profile);
System.out.println(do1.profile.profile);
System.out.println(do1.profile.profileSubObject.val1 + " " + do1.profile.profileSubObject.val2);
} catch (Exception e) {
e.printStackTrace();
}
}
This may be of help in regards to parsing JSON, use a JsonReader. It does assume you are using RESTful webservice and have already gotten a HttpURLConnection and an InputStream from the connection.
https://developer.android.com/reference/android/util/JsonReader.html

How to save retrofit array to sqlite database?

here is my jsonString:
{
"status":1,
"data":[
{
"id":"39",
"friendsInfo":{
"email":"test#gmail.com",
"phone":null,
"language":"en"
}
},
{
"id":"39",
"friendsInfo":{
"email":"test#gmail.com",
"phone":null,
"language":"en"
}
}
],
"message":""
}
here is my receivingClass:
public class mAnswer{
#SerializedName("status")
public int mEnterStatus;
#SerializedName("data")
public List<Data> dataList;
public class Data {
#SerializedName("id")
public int mUserId;
#SerializedName("friendsInfo")
public GetUserDetails getUserDetails;
public class GetUserDetails{
#SerializedName("email")
public int email;
#SerializedName("phone")
public String phone;
#SerializedName("language")
public String language;
}
}
}
and here is my code for successful receiving answer where I am trying to save this data to SQLite db:
private void saveList(){
Vector<ContentValues> cVVector = new Vector<ContentValues>();
int arraySize = mAnswer.dataList.size();
for (int i = 0; i < arraySize; i++){
// **HERE IS PROBLEM**
cVVector.add(friendsValue);
}
if (arraySize > 0 ){
ContentValues[] cvArray = new ContentValues[arraySize];
cVVector.toArray(cvArray);
mContext.getContentResolver().
bulkInsert(J4D_DB_Contract.UserFriendsEntry.CONTENT_URI, cvArray);
}
}
So here is my problem:
how to correct call #SerializedName elements when i am trying to save List data to db?
any ideas?
Will be glad any help! Thanks!
mAnswer.dataList.get(0);
gives back the
"id":"39",
"friendsInfo":{
"email":"test#gmail.com",
"phone":null,
"language":"en"
}
this is what you should say in the loop:
mAnswer.dataList.get(0).getFriendsObject().getEmail();
mAnswer.dataList.get(0).getFriendsObject().getPhone();
I would use this site to generate my POJO, beucase it`s more cleaner I think.
http://www.jsonschema2pojo.org/
This site gives back well defined POJO architecture, what is ready for use.
Just set that you are working with JSON instead of JSON Scheme and using GSON (if you are using retrofit).
After you can copy your java files to your workplace.
You don't need the #SerializedName("jsonName") if the variable has the same name private String jsonName;

Gson Parse Json with array with different object types

How can I parse this JSON using Gson?
I have an array with multiple object types and I don't know what kind of object I need to create to save this structure. I cannot change the json message (I don't control the server).
The only class that function (sort of) was this
public class Response {
private List<Object> tr;
private int results;
(...)
}
JSON Message (Note the array with multiple object types.)
{
"tr":
[
{
"a":
{
"userId": "112"
}
},
{
"b":
{
"userId": "123",
"address":"street dummy"
}
},
{
"a":
{
"userId": "154"
}
}
],
"results":3
}
The Gson User's Guide explicitly covers this:
https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types
You have an object with a field tr that is an array containing arbitrary types.
The users guide explains that you can't directly deserialize such a structure, and recomends:
Use Gson's parser API (low-level streaming parser or the DOM parser
JsonParser) to parse the array elements and then use Gson.fromJson()
on each of the array elements. This is the preferred approach.
In your case ... it would really depend on what objects were possible in that array. If they are all going to have that same inner object you'd want to do something like...
List<MyUserPojo> list = new ArrayList<MyUserPojo>();
JsonArray array = parser.parse(json).getAsJsonObject().getAsJsonArray("tr");
for (JsonElement je : array)
{
Set<Map.Entry<String,JsonElement>> set = je.getAsObject().entrySet();
JsonElement je2 = set.iterator().next().getValue();
MyUserPojo mup = new Gson().fromJson(je2, MyUserPojo.class);
list.add(mup);
}
And of course, this would need to be inside a custom deserializer for your actual object that would have the tr and results fields.
class MyPojo
{
List<MyUserPojo> userList;
int results;
}
class MyUserPojo
{
String userId;
String address;
}
class MyDeserializer implements JsonDeserializer<MyPojo>
{
#Override
public MyPojo deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
List<MyUserPojo> list = new ArrayList<MyUserPojo>();
JsonArray array = je.getAsJsonObject().getAsJsonArray("tr");
for (JsonElement je2 : array)
{
Set<Map.Entry<String,JsonElement>> set = je2.getAsObject().entrySet();
JsonElement je3 = set.iterator().next().getValue();
MyUserPojo mup = new Gson().fromJson(je3, MyUserPojo.class);
list.add(mup);
}
MyPojo mp = new MyPojo();
mp.tr = list;
mp.results = je.getAsObject().getAsJsonPrimitive("results").getAsInt();
return mp;
}
}
Now you're all set - you can use that deserializer and create your object:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyPojo.class, new MyDeserializer())
.build();
MyPojo mp = gson.fromJson(json, MyPojo.class);
If the a, b etc are important ... well, you'll have to figure that out. But the above should get you well on your way to understanding what's going to be needed to deal with your JSON structure.
For completeness sake, the only "hacky" way around this is if there is a fairly limited number of those types and the inner object also is fairly limited in terms of its fields. You could create a POJO that encompasses all the possibilities:
class MyPojo
{
MySecondPojo a;
MySecondPojo b;
...
MySecondPojo f;
}
class MySecondPojo
{
String userId;
String address;
...
String someOtherField;
}
When Gson deserializes JSON it will set any missing fields in your POJO(s) to null. You could now have tr be a List or array of these in your POJO. Again and to emphasize, this is really quite hacky and the wrong way to do it, but I thought I'd explain what would be required to directly parse that array.
I pick something from each answer and did it this way:
Response Object
public class Response {
private List<Users> tr;
private int results;
(...)
}
Generic User
public class User {
public static final int TYPE_USER_A =0;
public static final int TYPE_USER_B =1;
private String userId;
private int type;
(...)
}
A
public class a extends User {
private String location;
(...)
}
B
public class b extends User {
private String adress;
(...)
}
Parsing Method
private Response buildResponseObject(String response) {
Response tls = new Response();
List<Users> users = new ArrayList<users>();
User u;
try {
JSONObject object = new JSONObject(response);
tls.setResults(object.getInt("results"));
JSONArray array = object.getJSONArray("tr");
for (int i = 0; i < array.length(); i++) {
JSONObject trs = array.getJSONObject(i);
if (trs.has("a")) {
String json = trns.getString("a");
A a = new Gson().fromJson(json,A.class);
a.setType(User.TYPE_USER_A);
users.add(a);
} else if (trs.has("b")) {
String json = trs.getString("b");
B b= new Gson().fromJson(json,B.class);
B.setType(User.TYPE_USER_B);
users.add(b);
}
}
tls.setUsers(users);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tls;
}
This is not as elegant as I wanted and mix native JsonObjects with Gson methods but works for me.
Try this code here:
public class Address {
public String userId;
public String address;
// ...
}
public class Response {
private HashMap<String, Address> tr;
private int results;
// ...
}
Usage:
String json = "{\n \"tr\":\n {\n \"a\": {\n \"userId\": \"112\"\n },\n \"b\": {\n \"userId\": \"123\",\n \"address\":\"street dummy\"\n },\n \"c\": {\n \"userId\": \"154\"\n }\n },\n \"results\":3\n}";
Response users = new Gson().fromJson(json, Response.class);
As you may see I needed to modify the structure:
{
"tr":
{
"a": {
"userId": "112"
},
"b": {
"userId": "123",
"address":"street dummy"
},
"c": {
"userId": "154"
}
},
"results":3
}
But unfortunately I don't get it managed to allow multiple keys. Right now I have no idea how to fix this.
I think this link might help you:
https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples
Basically, create a class for your "object" (kind of user I guess), and then use the deserialization code of Gson, like this:
Type collectionType = new TypeToken<Collection<User>>(){}.getType();
Collection<User> users= gson.fromJson(json, collectionType);
You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-
Gson gson = new GsonBuilder().create();
Response r = gson.fromJson(jsonString, Response.class);
Here is an example- http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

Android, Null Pointer Exception to Data that isn't null

I'm writing an app for android that needs to parse data from an XML file. I've never come across an error like this that is so impossibly hard to track down. Or maybe my brain just stopped working. That happens. XML file is of the form:
<?xml version="1.0" encoding="iso-8859-1"?>
<memberRoster>
<agent>
<agentInfo1>...</agentInfo1>
<agentInfo2>...</agentInfo2>
...
</agent>
<agent>
...
</agent>
...
</memberRoster>
So far it's working well, except for some random bits of fun!
Every now and then it will throw a NullPointerException. I did some more digging and found out that there are THREE "agents" (out of 800) with "supposedly" null data. I checked the XML file and the data is there, there are no illegal characters, etc. It is the same three "agents" every time. The program parses other entries before and after these "null" "agents". Also of note is that not all "agentInfo" fields in the ArrayList come up null; example, one of the entries has 7 of the 8 entries as null, with the 8th one non-null, another has only one null with the last 7 non-null.
I'm parsing the data in to an ArrayList from the XML file, and like I mentioned before, it works flawlessly until it comes to those three specific entries in the XML file.
I'm sorry I can't give much more info than that, the data is sensitive to our members.
EDIT:
Sorry! I knew I was forgetting something! :)
Some code from my XMLHandler.java class:
public void characters(char[] ch, int start, int length)
if(this.in_mr_agentNrdsId) {
agent[0] = ch.toString();
}
else if(this.in_mr_agentFirstName) {
agent[1] = ch.toString();
}
else if(this.in_mr_agentLastName) {
agent[2] = ch.toString();
}
else if(this.in_mr_agentPhone) {
agent[3] = ch.toString();
}
else if(this.in_mr_agentEmail) {
agent[4] = ch.toString();
}
else if(this.in_mr_agentOfficeName) {
agent[5] = ch.toString();
}
else if(this.in_mr_agentOfficePhone) {
agent[6] = ch.toString();
}
else if(this.in_mr_agentType) {
agent[7] = ch.toString();
pds.setMemberRoster(agent);
agent = new String[8];
}
PDS is an object of type ParsedDataSet, which is just a simple class containing the ArrayList objects and a few getter and setter methods:
public class ParsedDataSet {
private ArrayList agentOpenHouses = new ArrayList();
private ArrayList calendarOfEvents = new ArrayList();
private ArrayList latestStatistics = new ArrayList();
private ArrayList memberRoster = new ArrayList();
public ArrayList<String[]> getAgentOpenHouses() {
return agentOpenHouses;
}
public ArrayList<String[]> getCalendarOfEvents() {
return calendarOfEvents;
}
public ArrayList<String[]> getLatestStatistics() {
return latestStatistics;
}
public ArrayList<String[]> getMemberRoster() {
return memberRoster;
}
public void setAgentOpenHouses(String[] agentOpenHousesItem) {
this.agentOpenHouses.add(agentOpenHousesItem);
}
public void setCalendarOfEvents(String[] calendarOfEventsItem) {
this.calendarOfEvents.add(calendarOfEventsItem);
}
public void setLatestStatistics(String[] latestStatisticsItem) {
this.latestStatistics.add(latestStatisticsItem);
}
public void setMemberRoster(String[] memberRosterItem) {
this.memberRoster.add(memberRosterItem);
}
} // end class ParsedDataSet
You could throw an if statement into your assignements and reassign any caught 'NULL' or empty strings into a zero value or just reassign as variable = "" in your code.
For example:
if (agentInfo1 == NULL) {
agentInfo1 = "" || agentInfo1 = 0; //Depending on what your variables are
}
Try putting try catch loop in code to find where the error is happening, then, pinpoint the exact part of code that is giving this error, there do null checks before proceeding. This is based on best practices of software development, rather than a fix for you.
Alternatively, you can makes sure on server side that there are no "null" values, maybe by giving dummy value like "EMPTY_STRING". This is especially relevant if your app is already shipped and you cant make any client code changes.

Categories

Resources