I am trying to do a "ToDoListApp" and my problem is that when I add some tasks to do and then close the app everything is deleted and the app starts anew.
I saw some other similar questions and it seems the solution is OnSaveInstanceState(Bundle outState) but I have a generic list with a class that I made List<MyClass>. My Problem is that when I write outstate.Put… there is no option for my array I can only choose between int, string, charsequence and parcelable. So my question is how can I save the state of my app?
What you are trying to do here is a thing you should be doing using an SQLite mobile database instead, Can be done like so :
Download the NuGet package sqlite-net-pcl by Frank A. Krueger
Using SQLite, Create a SQLite connection object
var db = new SQLiteConnection (dbPath);
After you have established a connection create your table something like this :
db.CreateTable<MyClass>();
Then insert the data that you want to insert into to the table something like this:
db.Insert(_yourClassObject);
Retrieve Data something like this;
var stock = db.Get<MyClass>(**yourPrimaryId**); //single object based on condition
var stockList = db.Table<MyClass>(); //The list of all data in this table.
For a better understanding of how it works refer this
Update
If you want to do it using shared preferences the way to do it would be converting it to JSON and then storing it to preferences as a string something like this:
Using Newtonsoft JSON package:
List<MyClass> your_Object;
your_Object=FooValueAssigned;// Assumed assignment
string yourString=JsonConvert.SerializeObject(your_Object); //It accepts any object in your case give your list here
Now Save it in shared preferences like this:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutString("your_list", yourString);
// editor.Commit(); // applies changes synchronously on older APIs
editor.Apply(); // applies changes asynchronously on newer APIs
Retrieve from shared preferences something like this:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
string mString = prefs.GetString ("your_list", <default value>);
Convert it back to your object type something like this:
var yourObjectFromPref= JsonConvert.DeserializeObject<List<MyClass>>(mString);
Related
I am using Google.Cloud library for c#, and I want to get data from my Firestore database.
I want to use JSON key, but I dont want to put it to GOOGLE_APPLICATION_CREDENTIALS variable.
my json Key is stored in C# variable
string jsonKey = ...;
project id is stored in other variable:
string projectId = ...;
How to do it.
If you've got the full service account credential JSON in jsonKey, then you just need:
var firestoreDb = new FirestoreDbBuilder
{
ProjectId = projectId,
JsonCredentials = jsonKey
}.Build();
Basically each "client" type (in this case FirestoreDb) provides a corresponding builder class which is intended to make it easy to provide everything you need. (In the next major version, to be released fairly soon, this will also provide integration with Microsoft.Extensions.DependencyInjection.)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was wondering... What's the best way to save data in Unity games. JSONs? If so, how? Thanks
Here are some of the different Ways and Methods to Save data for Unity Projects:
Platform-Independent: One way of saving data in Unity3D in a Platform-independent way is to use the PlayerPrefs class. PlayerPrefs is a static class and it is very easy to use but not reliable.
PERSISTENCE - SAVING AND LOADING DATA using DontDestroyOnLoad, PlayerPrefs, and data serialization Video Tutorial by unity.
Server Side: You can also use a Server for saving data (like a combination of PHP and MySQL Database). You can use it to save Score Data, user profiles, inventory, etc., Learn More From Unity Wiki. You can also use third-party solutions like firebase etc.
For saving the in-game data to a Hard drive in a format that can be understood and loaded later on, use a .NET/Mono feature known as Serialization. Learn More
Simple JSON guide about Unity is available at Unity Wiki or officially you can see JSON serialization
SQLite (an embedded database for your app) is another great option for you to get the Free Package, it is simple and easy (and my favorite) if you know SQL.
Scriptable Object: it's a data container. Useful for unchanging data. Suitable for large unchanging data and amazingly reduce your project's memory.
The above is taken from my blog post on Data Saving Techniques for Unity3d Applications.
You can use many assets that are available for free and paid in asset store.
Save Game Free - XML and JSON saving and loading.
Syntax:
Saver.Save<T> (T data, string fileName);
Example:
Saver.Save<MyData> (myData, "myData"); // The .json extension will be added automatically
Save Game Pro - Binary saving and loading. fast and secure. Easy to use.
Syntax:
SaveGame.Save<T> (T data, string identifier);
Example:
SaveGame.Save<int> (score, "score");
If you want to store your data in server there is a simple way with PHP and MySQL. What you have to do is:
STEP 1:
Get what ever data you want from your server just in single string (code is below):
<?php
//SERVER CONNECTION
$server_name = "localhost";
$server_user = "Er.Ellison";
$server_pass = "supersecretPassword";
$server_db = "game_test_db";
$connection = new mysqli($server_name , $server_user , $server_pass , $server_db);
if(!$connection) {
die("Connection failed !" . mysqli_connect_error());
}
// QUERY
$query = "SELECT * FROM items";
$result = mysqli_query($connection , $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "id:" . $row['id'] . "|username:" . $row['username'] . "|type:" . $row['type'] . "|score:" . $row['score'] . ";";
}
}
?>
And note that you MUST SEPARATE ANY string you want with a ; or any thing that you are comfortable with that and remember that we going to use it in C# in Unity.
STEP 2:
Now you should get the data from your web like this (it will be a long string):
STEP 3:
Now go to the Unity and create a C# script and attached that to what ever object in your scene and open the script up, then use this kind of code to manipulate the data that you retrieved from your database:
public class DataLoader : MonoBehaviour {
public string[] items;
// Use this for initialization
IEnumerator Start () {
WWW itemsData = new WWW ("http://localhost/_game/test/itemsdata.php");
yield return itemsData;
string itemsDataStrign = itemsData.text;
print (itemsDataStrign);
items = itemsDataStrign.Split (';');
print (GetDataValue(items[0] , "cost:"));
}
string GetDataValue(string data, string index) {
string value = data.Substring (data.IndexOf(index) + index.Length);
if (value.Contains ("|")) {
value = value.Remove (value.IndexOf("|"));
}
return value;
}
}
STEP 4:
You just NOW retrieved data from database, check the image from unity console:
I made this for who that may be, like me, stuck in database problems!
Xamarin.Forms Droid project: How to store some data on OnHandleIntent event. I'm trying save data in Application.Current.Properties. When application active/open there is no problem, but when application closed data not saved. Any help would be appreciated. Below code example:
[Service]
public class GCMIntentService : IntentService
{
//other methods
protected async override void OnHandleIntent(Intent intent)
{
//Some code for push notification
Application.Current.Properties.Add("key", "value");
Application.Current.SavePropertiesAsync();
}
}
Xamarin.Forms Android: Save/Store some data on OnHandleIntent event
The Application.Current.Properties is just a dictionary of objects you can stick anything you want in there, including your own classes which will get serialized, and the properties collection is read from a file and this is done automatically.
However, the entire dictionary is serialized together in a file, an exception during reading or deserialization of that file will be catched and just leave you with an empty Properties collection.
Solution :
You could use SharedPreferences to Save/Store some data, as the document said :
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
In Xamarin.Android, You'll need to get the instance of ISharedPreferences and use that to update/change/delete preferences. As Tom Opgenorth said, there are a couple of ways to get an instance of ISharedPreferences :
Activity.GetPreferences
would get you preferences specific to that activity. Probably not what you want.
Context.GetSharedPreferences
can get you application level preferences.
PreferenceManager.DefaultSharedPreferences
will give you an ISharedPreference instance for a given context.
The actual saving is done by an instance of ISharedPreferencesEditor, which you get get by invoking the method ISharedPreferencesEditor.Apply(). Here is an example :
Save your data :
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("number", "Value");
editor.Apply();
Restore your data :
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
var a = prefs.GetString("number", "null");//"null" is the default value
I am creating a custom transformation in C# to be used in SSIS. I have already been able creating and adding the custom component and receive and alter data from a db source but I need more data to register in a log table. This data can only be passed with variables but I can't find a good explanation of how to add a readonlyvariable to my component.
I have tried to use IDTSVariable100 and VariableDispenser but I can't make sense of how to.
public override void ProvideComponentProperties()
{
base.ProvideComponentProperties();
base.RemoveAllInputsOutputsAndCustomProperties();
VariableDispenser varDispenser = this.VariableDispenser();
IDTSVariable100 vr = this.VariableDispenser.GetVariables();
IDTSInput100 input = this.ComponentMetaData.InputCollection.New();
input.Name = "Input_B";
IDTSOutput100 output=this.ComponentMetaData.OutputCollection.New();
output.Name = "Output_B";
// the output is synchronous with the input
output.SynchronousInputID = input.ID;
}
Basically i want to define readonlyvariables that I can alter the value before my custom component runs like the original "script component" has.
Well i researched a bit more and stumbled on a answer:
It seems that to access the SSIS public variables we have to get them with code on the ProcessInput Method:
var dimSrcId ="";
IDTSVariables100 variables = null;
this.VariableDispenser.LockForRead("User::dimSrcId");
this.VariableDispenser.GetVariables(out variables);
dimSrcId = variables["User::dimSrcId"].Value.ToString();
variables.Unlock();
By using the VariableDispenser.LockForRead() we're capable of searching for our variables and access there value.
I use LinqPad with the MySQL IQ driver to query data from a Magento database. I not only use this for reporting on the database but for doing updates. I can use the standard SubmitChanges() method to update data, but that often ends up with unbearably slow updates that can literally take hours - one of my tables has 35,707 records that I recreate on a regular basis.
So instead I generate SQL statements in my LinqPad queries and then execute them in a separate tab after selecting "SQL" in the language drop-down.
For example, my output might be something like this:
UPDATE catalog_category_product SET position = 6040 WHERE (category_id = 156 AND product_id = 12648);
UPDATE catalog_product_entity_media_gallery_value SET label = 'Sandy Beach' WHERE ((store_id = 0) AND (value_id = 8791));
-- Done.
I have recently found that LinqPad has a nice class called Hyperlinq that allows me to write code like this:
(new Hyperlinq(QueryLanguage.SQL, myGeneratedSqlText, "Run Query")).Dump();
The result is that a hyperlinq is put in the output window that will run the query (in my example the contents of myGeneratedSqlText) in a new tab and execute the query.
This is very convenient.
However, I now want to be able to save a log of queries that are executed. There doesn't seem to be (an easy) built-in way to manually execute a "generated" query in LinqPad. I can certainly use Util.Run to execute an existing saved query, in fact I do something like this:
Util
.OnDemand("Run Query", () =>
{
var fn = createOutputQueryFileName(); // Timestamped query name
System.IO.File.WriteAllText(fn, myGeneratedSqlText);
var run = Util.Run(fn, QueryResultFormat.Text);
var result = run.AsString();
return result.StartsWith("[]") ? "Success" : result;
})
.Dump();
The only drama with this is that I have to prefix the text in myGeneratedSqlText with the following:
var preamble = #"<Query Kind=""SQL"">
<Connection>
<ID>ec026b74-8d58-4214-b603-6d3145e03d7e</ID>
<Driver Assembly=""IQDriver"" PublicKeyToken=""5b59726538a49684"">IQDriver.IQDriver</Driver>
<Provider>Devart.Data.MySql</Provider>
<CustomCxString>[DELETED]</CustomCxString>
<Server>127.0.0.1</Server>
<Database>prod_1_8</Database>
<Password>[DELETED]</Password>
<UserName>[DELETED]</UserName>
<NoPluralization>true</NoPluralization>
<NoCapitalization>true</NoCapitalization>
<DisplayName>Production Tunnel</DisplayName>
<EncryptCustomCxString>true</EncryptCustomCxString>
<Persist>true</Persist>
<DriverData>
<StripUnderscores>false</StripUnderscores>
<QuietenAllCaps>false</QuietenAllCaps>
<Port>6606</Port>
</DriverData>
</Connection>
</Query>
";
I would really like to avoid all of this preamble stuff and include a line like this in my Util.OnDemand(...) code:
var run = Util.Run(QueryLanguage.SQL, myGeneratedSqlText, QueryResultFormat.Text);
(But this method doesn't exist.)
The key requirement here is to display a hyperlinq in the LinqPad output window that, if clicked, will save the query to disk as a log and also execute the query.
Can anyone suggest a clean way for me to do it?
I hope I've understood you correctly. When you've selected a connection in the top bar, your UserQuery becomes a datacontext. For this reason, you can use ExecuteQuery and ExecuteCommand on this within an action based Hyperlinq.
new Hyperlinq(() => {
"do log work here".Dump();
this.ExecuteQuery<string>(generatedSelect).Dump("Results");
this.ExecuteCommand(generatedCommand).Dump("Results");
}, "Run Query").Dump();
Unfortunately this outputs to the current tab, but hopefully this will at least get you most of the way to done :)
Here's an image of it at work:
As you're using MySQL, you can go via the connection property on this:
new Hyperlinq(() => {
"do log work here".Dump();
using (var command = this.Connection.CreateCommand())
{
// Usual command logic here
}
}, "Run Query").Dump();