java.lang.NumberFormatException: Invalid int while storing a string - android

I'm getting the weirdest error. Im attempting to store a String to Azure Mobile Service Table and I'm getting this exception. ( Being thrown for a GCM ID I'm generating"
java.lang.NumberFormatException: Invalid int: "C3960965-ECE0-4533-B99D-84DB3881A50F"
public class User
{
private int id;
private String gcmChannel;
public User()
{
}
/**
* Getters and setters
*
*/
public String getRegistrationId() {
return gcmChannel;
}
public final void setRegistrationId(String registrationId) {
gcmChannel = registrationId;
}

There was a change in the tables created in Azure Mobile Services - the tables by default now have ids of type string (instead of integer, as before). If you change your type definition to the following:
public class User
{
private String id;
private String gcmChannel;
// ... rest the same
}
It should work fine. Notice that you'll also need the latest Azure Mobile Services SDK for Android (version 1.1.0) which has support for types with string ids - you can find that SDK at http://www.windowsazure.com/en-us/downloads/?sdk=mobile.
You can find the announcement of this change in the MSDN Forums, or more information about it in this blog post.

Related

Xamarin + sqlite: Trouble reading database

I am opening a database file, and running select * query and no objects are found. I have:
Created a DB in DB Browser for SQLite, stored the db file in common project, as well as assets/resources for Droid/iOS with proper Build Action (AndroidAsset/BundleResource)
Created interface in common code and DatabaseService in Droid:
public SQLiteConnection CreateConnection()
{
var sqliteFilename = "StepsDatabase.db";
string documentsDirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsDirectoryPath, sqliteFilename);
var conn = new SQLite.SQLiteConnection(path);
//conn.CreateTable<Step>();
//conn.CreateTable<SuperStep>();
return conn;
}
(I have tried with and without the .CreateTable as I saw that was a possible solution from another question)
Created C# mdoels for both tables in my database
namespace StepsDB
{
[Table("Step")]
public class Step
{
[PrimaryKey, AutoIncrement, Unique, Column("stepID")]
public int stepID
{
get;
set;
}
[NotNull, Column("name")]
public string name
{
get;
set;
}
[NotNull, Column("superStep")]
public int superStep
{
get;
set;
}
[Column("videoLocation")]
public string videoLocation
{
get;
set;
}
[Column("uploader")]
public string uploader
{
get;
set;
}
[Column("uploaderIG")]
public string uploaderIG
{
get;
set;
}
}
}
Created a DatabaseManager that calls CreateConnection() and then a select * query from both tables and empty Lists are created.
Even when I debug and check the "conn" variable, it has TableMappings Count = 0.
PS using sqlite-net-pcl NuGet installed in all projects.
I have been stuck on this for a LONG time and have scoured the internet but no solution that worked for others have worked for me. Please help!
Also this is my first question so if I have done anything wrong please let me know.
I was never properly opening my database asset, only creating an empty file. I now use
var binaryReader = new BinaryReader(Android.App.Application.Context.Assets.Open(sqliteFilename))
to open the asset and write it to the file location I was trying to open originally. Once I create the connection it properly maps to my objects and I have a list to use! :) :)
You can use EF Core to access Sqlite databases easily.
use this command to install EFCore Sqlite package:
Install-Package Microsoft.EntityFrameworkCore.Sqlite
Then you can use EFCore standard functions to create databases at runtime.

Firebase data insert issue. Data is not inserted properly

I am trying to insert a POJO to Firebase. However, some of the fields don't seem to be parsed into Firebase, but there is no warning or error.
I have this POJO:
public class Group {
public String name;
public String admin;
public List<String> addedUsers;
public List<String> invitedUsers;
public Group(String name, String admin, ArrayList<String> addedUsers, ArrayList<String> invitedUsers) {
this.name = name;
this.admin = admin;
this.addedUsers = addedUsers;
this.invitedUsers = invitedUsers;
}
public Group() {
// Default constructor required because we have a non-default constructor as well.
}
}
I upload to Firebase by doing so:
DatabaseReference groupRef = ref.child("Groups");
ArrayList<String> addedUsers = new ArrayList<String>();
addedUsers.add("email1#gmail.com");
addedUsers.add("email2#gmail.com");
ArrayList<String> invitedUsers = new ArrayList<String>();
Group newGroup = new Group("GroupName",
"email1#gmail.com", addedUsers, invitedUsers
);
groupRef.push().setValue(newGroup);
I end up with this object in Firebase:
I have a secondary issue now, I manually inserted the data into Firebase, but now I cannot map the Lists onto my Java Object, and are mapped as null, I know I am able to download the data fine;
I'm not sure what you mean that lists are not supported, as it seems that they are supported.
Basic write operations
For basic write operations, you can use setValue() to save data to a
specified reference, replacing any existing data at that path. You can
use this method to:
Pass types that correspond to the available JSON types as follows:
String
Long
Double
Boolean
Map<String, Object>
List<Object>
Pass a custom Java object, if the class that defines it has a default
constructor that takes no arguments and has public getters for the
properties to be assigned.
Firebase supports key value mapping. So lists are not supported. Change it to Map type, keep email addresses as key and assign a boolean value true or false.

Why does Google Cloud Endpoints reverse the order of my parameters?

I have the following endpoint method:
public class PlayerEndpoint {
private static final String PLAYER_NAME = "player_name";
private static final String PLAYER_UUID = "player_uuid";
#ApiMethod(name = "register", httpMethod = ApiMethod.HttpMethod.POST, path="register")
public Player register(#Named(PLAYER_UUID) String uuid,
#Named(PLAYER_NAME) String playerName) {
log.info(String.format("Registering user uuid: %s name: %s", uuid, playerName));
...
}
}
When I call this from my Android client:
String uuid = "test_uuid";
String name = "test_name";
playerEndpoint.register(uuid, name).execute();
The backend logs:
Registering user uuid: test_name name: test_uuid
What is going on here?
I figured it out. Apparently Endpoints sorts your methods alphabetically.
Method parameters in the generated client library are in alphabetical order, regardless of the original order in the backend method. As a result, you should be careful when editing your methods, especially if there are several parameters of the same type. The compiler will not be able to catch parameter-ordering errors for you.
https://cloud.google.com/developers/articles/google-cloud-endpoints-for-android/

Sugar ORM is not saving data into the database

I am currently using Sugar ORM and Android Async Http Client for my Android application.
I read through the documentation of Sugar ORM and did exactly what is written there.
My HttpClient is using the singleton pattern and provides methods for calling some APIs.
Now comes the bad part about it. I am not able to save the data persistently into my database which is created by Sugar ORM.
Here is the method, that is calling an API:
public void getAvailableMarkets(final Context context, final MarketAdapter adapter) {
String url = BASE_URL.concat("/markets.json");
client.addHeader("Content-Type", "application/json");
client.addHeader("Accept", "application/json");
client.get(context, url, null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.i(TAG, "Fetched available markets from server: " + response.toString());
Result<Markets> productResult = new Result<Markets>();
productResult.setResults(new Gson().<ArrayList<Markets>>fromJson(response.toString(),
new TypeToken<ArrayList<Markets>>() {
}.getType()));
ArrayList<Markets> marketsArrayList = productResult.getResults();
// This lines tells me that there are no entries in the database
List<Markets> marketsInDb = Markets.listAll(Markets.class);
if(marketsInDb.size() < marketsArrayList.size() ||
marketsInDb.size() > marketsArrayList.size()) {
Markets.deleteAll(Markets.class);
for(Markets m : marketsArrayList) {
Markets market = new Markets(m.getId(), m.getName(), m.getChainId(), m.getLat(),
m.getLng(), m.getBusinessHourId(), m.getCountry(), m.getZip(), m.getCity(),
m.getStreet(), m.getPhoto(), m.getIcon(), m.getUrl());
market.save();
adapter.add(market);
}
adapter.notifyDataSetChanged();
}
List<Markets> market = Markets.listAll(Markets.class);
// This lines proves that Sugar ORM is not saving the entries
Log.i(TAG, "The market database list has the size of:" + market.size());
}
});
}
This is what Logcat is printing:
D/Sugar: Fetching properties
I/Sugar: Markets saved : 3
I/Sugar: Markets saved : 5
I/RestClient: The market database list has the size of:0
Also I took a look at the Sugar ORM tag here at stackoverflow, but no answers or questions could give me a hint on how to solve that problem.
I am a newbie to the android ecosystem and would love any help of you guys to solve this problem.
Thanks in advance
I just solve it the same problem as you have.
It was a pain in the neck but after few hours I find out what caused this problem.
Using Sugar ORM you must not set id property as it's belongs to SugarRecord class,
otherwise ORM will try to update objects instead of insert them.
As I need to have field with my object id, I used json annotation to assign it to another field.
Last step was configure GSON to exclude fields without Expose annotation.
So my class looks like one below now:
public class MyClass
{
#Expose
#SerializedName("id")
private long myId;
#Expose
private String field1;
#Expose
private String field2;
#Expose
private byte[] field3;
#Expose
private double field4;
public MyClass() { }
// parametrized constructor and more logic
}
Cheers!

ORMLite foreign field null on create, not null on query

When writing an instance of my data class to the database via ORMLite, and one of the child members (a foreign field) is null, I get back a non null child member.
Data classes as follows:
public class Site {
// snip
#DatabaseField(foreign = true, canBeNull = true)
private InstallationType installationType;
}
public class InstallationType {
#DatabaseField(generatedId = true)
private int id;
#DatabaseField
private String name;
}
When I read my instance of the Site class again via
getSiteDao().queryForId(id);
the installationType member is non null, but with a non-existent id. The only way the rest of our application can now work with this object, is if I manually do a lookup through the InstallationTypeDAO and set what I get back on the site. Query will sometimes return null as per the documentation.
Is there a way of getting ORMLite to set this member to null?
This was a bug in ORMLite that was fixed in version 4.15 (3/7/2011). Here's the change log file. What version are you using? Have you tried to update? Here's the bug report page:
Currently the following test passes so I think we have good coverage on that bug.
#Test
public void testForeignNull() throws Exception {
Dao<Foreign, Integer> dao = createDao(Foreign.class, true);
Foreign foreign = new Foreign();
foreign.foo = null;
assertEquals(1, dao.create(foreign));
Foreign foreign2 = dao.queryForId(foreign.id);
assertNotNull(foreign2);
assertNull(foreign2.foo);
}
With Foreign having the following fields:
#DatabaseField(generatedId = true)
public int id;
#DatabaseField(foreign = true)
public Foo foo;
If you are up to date in versions, please let me know if you can change the test to get it to fail.

Categories

Resources