Trying to create a List of user-defined objects, getting NullPointerException - list

I'm working on an Android app. I created (in a separate .java file) an object like so:
class RRS_Location {
String tagname;
String href;
// Constructor
public RRS_Location(String tagname, String href) {
this.tagname = tagname;
this.href = href;
}
public String getTagname() {
return tagname;
}
public String getHref() {
return href;
}
}
Within an activity, I've declared a List of these items
List<RRS_Location> rrs_list;
I'm getting a NullPointerException when I try to add an RRS_Location object to the list. I'm doing so using this code
rrs_list.add(new RRS_Location(e1, e2));
I've used Toast to echo back to me that I have valid Strings e1 and e2. Any ideas on why I'm getting the exception? TIA!

Are you instantiating rrs_list before making the call to add?
List<RRS_Location> rrs_list = new ArrayList<RRS_Location>();
If not, this is why you are getting a NullPointerException, you are attempting to invoke a method on a null object.

Related

Unity3D - Integer List values don't get initialized in Constructor of Class

In my Unity3D Project I made a simple 2D Game and implemented a Data Manager to save and load Data. I created a List but get a NullReferenceException whenever I try to refer to it. I have a DataManager Class (saves & loads Data) and a UserData Class (stores the fields that are needed to be saved or loaded). In the User Data Class I declare in initialize a List of integer type. The List contains the unlocked Levels and it is initialized in the Constructor of the User Data Class.
This is the DataManager Class:
public static class DataManager
{
public static List<int> GetUnlockedLevels()
{
UserData userData = Load();
return userData.unlockedLevels; // This method returns nothing, not even null!
}
private static void Save(UserData data)
{
string path = GetDataFilePath();
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (FileStream fileStream = File.Open(path, FileMode.OpenOrCreate))
{
binaryFormatter.Serialize(fileStream, data);
}
}
private static UserData Load()
{
string path = GetDataFilePath();
if (!File.Exists(path))
{
UserData userData = new UserData();
Save(userData);
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (FileStream fileStream = File.Open(path, FileMode.Open))
{
return (UserData)binaryFormatter.Deserialize(fileStream);
}
}
And here comes the UserData Class:
[Serializable]
public class UserData
{
public int score;
public List<int> unlockedLevels;
public UserData()
{
score = 50;
unlockedLevels = new List<int>();
unlockedLevels.Add(1); //unlocked by default
unlockedLevels.Add(2); //unlocked by default
unlockedLevels.Add(3); //unlocked by default
}
}
The problem is: the first method of the DataManager "GetUnlockedLevels()" returns nothing.
The weird part: I have the exact same Data Manager in another project where it works properly. In that other project, the GetUnlockedLevels-method returns "System.Collections.Generic.List´1[System.Int32]" when I return it via "Debug.Log". But in the new project, the method returns literally nothing (not even null; the exception comes at a later point)
I am sure that I didn't make a copy-paste-mistake. What could be the root for this error?
What IDE are you using? I ask because the answer to your question is that you have a typo in your UserData constructor. Normally you would be alerted to this as soon as you built within your IDE as it would fail to compile.
[Serializable]
public class UserData
{
public int score;
public List<int> unlockedlevels; // This line
public UserData()
{
score = 50;
unlockedLevels = new List<int>(); // And this line
unlockedLevels.Add(1); // And this line
unlockedLevels.Add(2); // And this line
unlockedLevels.Add(3); // And this line
}
}
unlockedLevels
vs
unlockedlevels
Solution: the file was created but was empty. I manually deleted the saved file and from then it worked properly.

How to get and set value for a object using Shim classes in C# Microsoft fakes unit testing?

Here is my main class which I want to test. It contains one private method.
Public class MyClass
{
private bool IsWorkDone(MyItem item, string name)
{
using (MyThing thingObj = new MyThing(item.ID))
{
using (MyWork workObj = thingObj.Open())
{
try
{
return false;
}
}
}
return true;
}
}
In my test class I have written below method
public void CheckIsWorkDoneTest()
{
using (ShimsContext.Create())
{
MyItem myitem = new ShimMyItem () {
itemGet = () => new ShimMyItem () {
IDGet = () => new Guid();
}
};
ShimMyClass.AllInstances.isWorkDoneItemString = (MyClass, MyItem, MyName) => "Here I'm stuck. I need help from stackoverflow users"
PrivateObject objMyClass = new PrivateObject(typeof(MyClass));
object[] parameters = new object[2] { myItem, workName };
bool result = Convert.ToBoolean(objMyClass.Invoke("IsWorkDone", parameters));
Assert.AreEqual(result,true);
}
}
I want to set the value for oSite object from statement => "using (MyThing thingObj = new MyThing(item.ID)) " from my main MyClass Class.
while debugging this line throws Object reference not set to an instance error.
So using ShimMyClass.Allinstance how can I get or set the value for it?
You have quite a few inconsistencies, so your problem is probably just straitening them out. If you're actual code is more consistent, then update your post. The main things
You show private method IsComplete but call isWorkflowCompleted from your Invoke method
You probably end up calling your shimmed method that will pass "Here I'm stuck" and try to convert that string to a Boolean.
I fudged your skeleton and got mine to work after adjusting some of the names.

C++ Nested JSON in Unreal Engine 4

I have a JSON object that I am getting from my server that looks something like this:
{
"state":"1",
"player1": {
"alias":"Player Name",
"ready":"0"
}
}
I am able to get the JSON, parse it into a FJsonObject, and retrieve any number or string in the first level of the JSON object using this code to serialize:
TSharedPtr<FJsonObject> JsonParsed;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(json);
if (FJsonSerializer::Deserialize(JsonReader, JsonParsed))
//Use JsonParsed
And this code to read strings:
FString AJSONContainer::getStringWithKey(FString key)
{
return storedJSON->GetStringField(key);
}
Side Note:
AJSONContainer is just an Actor class that I use to call these functions from Blueprints.
That's all fine and dandy, but when I try to read things from the second level, things don't work.
I wrote this code to get the next level down:
TSharedPtr<FJsonObject> nested = storedJSON->GetObjectField(key);
But all calls to get fields of nested return nothing.
nested->GetStringField(anotherKey); //Nothing
So, for example, with the above JSON, this:
TSharedPtr<FJsonObject> nested = storedJSON->GetObjectField("player1");
FString alias = nested->GetStringField("alias");
alias has no value when I print it to the console.
Am I doing something wrong? Why isn't the second-level JSON working?
Don't know if you got it sorted out, but I found a pretty nasty function that works for nested objects and, also, for arrays altogether. And it gives you a USTRUCT, so you don't have to use the functions that get values by Keys (I don't like them since they're very error prone). Instead, you'll have type safety!
FJsonObjectConverter::JsonObjectStringToUStruct
Here are the docs and another question answered on UE4 AnswerHub
Basically, you create the target USTRUCT (or USTRUCTs for nested JSONs), mark all properties with UPROPERTY, so Unreal knows their names, and use this function. It will copy the values by matchmaking them. It copies even the arrays! =D
Example
I'll call the JSON FString to be deserialized Json and it's structure is like the one below. It contains a nested object and an array, to make things interesting.
{
"nested" : {
"id" : "654asdf",
"name" : "The Name"
},
"foo" : "foobar",
"bar_arr" : [
{ "barfoo" : "asdf" },
{ "barfoo" : "qwer" }
]
}
Before converting, we need to create the USTRUCTs from inside out (so we can reference inner on the outer). Remember to always use F for struct names.
USTRUCT()
struct FNested
{
GENERATED_USTRUCT_BODY()
UPROPERTY()
FString id;
UPROPERTY()
FString name;
};
USTRUCT()
struct FBar
{
GENERATED_USTRUCT_BODY()
UPROPERTY()
FString barfoo;
};
USTRUCT()
struct FJsonData
{
GENERATED_USTRUCT_BODY()
UPROPERTY()
FNested nested;
UPROPERTY()
FString foo;
UPROPERTY()
TArray<FBar> bar_arr;
};
The conversion will go like this:
FJsonData JsonData;
FJsonObjectConverter::JsonObjectStringToUStruct<FJsonData>(
Json,
&JsonData,
0, 0);
Now, you are able to access all the properties as in standard C++ structs. Eg., to access one of the barfoos:
FString barfoo0 = JsonData.bar_arr[0].barfoo;
I have not tested it with int and float in the JSON, but since it copies even arrays, I believe that would work also.
for (auto currJsonValue = JsonObject->Values.CreateConstIterator(); currJsonValue; ++currJsonValue)
{
// Get the key name
const FString Name = (*currJsonValue).Key;
// Get the value as a FJsonValue object
TSharedPtr< FJsonValue > Value = (*currJsonValue).Value;
TSharedPtr<FJsonObject> JsonObjectIn = Value->AsObject();
}
The Json Object nested can be accessed by GetObjectField or the code I posted.
As I commented calling GetField<EJson::Object> instead of GetObjectField is the solution.
So this code will get your nested json:
TSharedPtr<FJsonValue> nested = storedJSON->GetField<EJson::Object>("player1");
TSharedPtr<FJsonObject> nestedParsed = nested->AsObject();
FString alias = nestedParsed->GetStringField("alias"); // alias == "Player Name"

Service which provides interface-impelementation instead of data

Since a while now I'm implementing services whenever possible with ServiceStack (or WebAPI) instead of WCF.
What I want to do now is sending an interface (-name) to the server and get a class-implementation back. Maybe that's confusing, so I'll give you an example:
My service-client has multiple operations - like "check form":
The logic for checking this form is not implemented. What it has is an interface called IFormChecker with methods like NameIsValid(string firstName, string middleName, string lastName).
Instead of sending the whole form-data to the server for validation, the client will request the implementation of IFormChecker from the server.
I know that's possible with WCF, but I have no idea how to do that with ServiceStack.
If that's possible, what's the way to go? I checked the documentation, but I'm not really wiser.
It seams like there's no "magic trick" or anything.
I have to serialize/deserialize the class "old-fashion way".
If you're interested, here's the solution:
I created a "Root"-Interface, in this example it is IModule.
This IModule contains only 1 property, called Name.
It is a string and only there for convenience:
The IFormChecker from the example would be derived from this interface:
My client knows the value of this Name-property and of course the interface itself.
It will now fire the Name-value to the server, which will return the serialized class.
All I have to do is:
var module = ModuleImplementations.FirstOrDefault(x => x.Name == name);
if(module == null) throw new SomeException();
return module.Serialize();
client-wise I can deserialize it and cast it to the interface. That's it.
Here's my ModuleSerialization-Class:
public static class ModuleSerialization
{
public static string Serialize(this IModule m)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, m);
return Convert.ToBase64String(ms.ToArray());
}
}
public static T Deserialize<T>(string serialized) where T : class, IModule
{
var ba = Convert.FromBase64String(serialized);
using (var s = new MemoryStream(ba))
{
var bf = new BinaryFormatter();
return bf.Deserialize(s) as T;
}
}
}
Cheers!

Why is my IQueryable LINQtoObject being treated as LINQtoSQL and throwing no supported translation to SQL

I have a LINQ dbml class that I am wrapping in a POCO. I have built overloaded constructors that take the DBML class and init. the wrapper objects properties based on the dbml object passed in.
For example
public class MyPerson{
public MyPerson(DBMLPerson p)
{
this.ID = p.ID;
this.Name = p.Name;
}
}
if I then do something like this where I return an IQueryable
{
return from p in datacontext.DBMLPerson
select new MyPerson(p){};
}
When I try to do further queries on that Iquearble I get "System.NotSupportedException: The member 'MyPerson.ID' has no supported translation to SQL.."
However if I do this
{
return from p in datacontext.DBMLPerson
select new MyPerson(){
ID = p.ID;
Name = p.Name;
};
}
I don't get an error at all and everything works perfect. Basically I want to have my class handle the conversion from LINQ object to POCO itself.
Basically I have to use the Object Initializer or I am unable to match on that field.
Ok not sure this will actually help anyone but but myself but my whole problem is the I shouldn't be using IQuerable after a certain point(outside of my repository)
iqueryable-can-kill-your-dog-steal-your-wife-kill-your-will-to-live-etc