Storing and getting data in windows phone app - windows-phone-8

I have created a Windows phone app based on a quiz game. I want that when the user give the correct answer for some question then a small tick mark will be permanently on in the tab of the question.
I want to store score for every question so that i can display that in a place name as 'your score'. And that score will not be reset even if the app is closed.

you could use app IsolatedStorage for saving the file.
reference
#region Save and Load Parameters from the Application Storage
void saveToAppStorage(String ParameterName, String ParameterValue)
{
// use mySettings to access the Apps Storage
IsolatedStorageSettings mySettings = IsolatedStorageSettings.ApplicationSettings;
// check if the paramter is already stored
if (mySettings.Contains(ParameterName))
{
// if parameter exists write the new value
mySettings[ParameterName] = ParameterValue;
}
else
{
// if parameter does not exist create it
mySettings.Add(ParameterName, ParameterValue);
}
}
String loadFromAppStorage(String ParameterName)
{
String returnValue = "_notSet_";
// use mySettings to access the Apps Storage
IsolatedStorageSettings mySettings = IsolatedStorageSettings.ApplicationSettings;
// check if the paramter exists
if (mySettings.Contains(ParameterName))
{
// if parameter exists write the new value
mySettings.TryGetValue<String>(ParameterName, out returnValue);
// alternatively the following statement can be used:
// returnValue = (String)mySettings[ParameterName];
}
return returnValue;
}
#endregion

Related

Static member fields in GAS (google apps script) classes

I run the following in the Chrome console without problem:
// Usage:
// console.log([...scope]); // => ['user','script','document']
// console.log(`${scope.user`}); // => 'user'
// console.log(scope.user.properties); // 'user.properties' (not real code)
class scope {
static user = new scope();
static script = new scope();
static document = new scope();
constructor(propertyーscope) {
if(propertyーscope in scope) return scope[propertyーscope];
}
get properties() {
return `${this.toString()}.properties`; // just for the example
// in reality, I'd return:
// PropertiesService[`get${this.toString().toSentenceCase()}Properties`]();
}
static *[Symbol.iterator]() { for (const key of Object.keys(scope)) yield key; }
toString() { return Object.entries(scope).filter(([key, value])=>value===this)[0][0]; }
};
However, Google Apps script refuses to save this code snippet and complains about the static declarations (= sign after static user.
Isn't GAS supposed to support static fields?
More importantly, how can I achieve the same?
(note: the dash in propertyーscope is not a dash but a unicode letter looking like it; I use that as a more readable alternative to underscores).
There's a way to simulate static fields in Apps Script. It involves using properties instead of a field. We can create a lazily initiated property that replaces itself with the following code:
class MyClass {
static get c() {
// Delete this property. We have to delete it first otherwise we cannot set it (due to it being a get-only property)
delete MyClass.c;
// Replace it with a static value.
return MyClass.c = new StaticObject();
}
}
To confirm this works, we can use the following:
SpreadsheetApp.getUi().alert(MyClass.c === MyClass.c)
This will only evaluate to true if the object was generated once and stored. If the field remains a property, it will return false.

Read username from GoogleSignInAccount ( Google Fit Android API)

I'm using the Google Fit Android API to retrieve fitness data and it all works like a charm. I want to also access the name of the currently logged in user , which should be accessible by GoogleSignInAccount .getDisplayName();
I already asked this question but unfortunately didn't get any replies, and I cant figure it out with the documentation.
Example code:
//Create a FitnessOptions instance, declaring the data types and access type (read and/or write) your app needs:
FitnessOptions fitnessOptions = FitnessOptions.builder()
.addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.addDataType(DataType.TYPE_SLEEP_SEGMENT, FitnessOptions.ACCESS_READ)
.addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ)
.addDataType(DataType.AGGREGATE_HEART_RATE_SUMMARY, FitnessOptions.ACCESS_READ)
.build();
//Get an instance of the Account object to use with the API:
GoogleSignInAccount account = GoogleSignIn.getAccountForExtension(this, fitnessOptions);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
loggedInUser = account.getDisplayName();
}
The problem is acct.getDisplayname().getGrantedScopes works like a charm, and I see the granted scope. When I try to read .getDisplayName I always get NULL.
I decided to use another way of logging in...
I now use this to configure sign in options and access :
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Then we start the sign in intent:
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 000000);
And now we handle the result:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == 000000) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
updateUI(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
Tips: Make sure to use ApiException.class from Google and not AWS

Google Drive Android API onChildrenRetrievedCallback

I'm building an app and trying to view a PDF stored in a shared Google Drive folder in-app. I've already connected to the Drive and I have a GoogleApiClient already set up. Right now I'm querying the database and trying to handle the results, but I'm having trouble with this code:
Query query = new Query.Builder().addFilter(Filters.and(
Filters.eq(SearchableField.TITLE, "sample_pdf.pdf"),
Filters.eq(SearchableField.MIME_TYPE, "application/vnd.google-apps.file")))
.build();
Drive.DriveApi.query(googleApiClient, query)
.setResultCallback(new OnChildrenRetrievedCallback() {
#Override
public void onChildrenRetrieved(MetadataBufferResult result) {
// Iterate over the matching Metadata instances in mdResultSet
}
});
Android Studio is not able to resolve the class OnChildrenRetrievedCallback. I have imported the com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks package but I'm not sure what else to do here. Any help?
Try this:
/********************************************************************
* find file/folder in GOODrive
* #param prnId parent ID (optional), null searches full drive, "root" searches Drive root
* this is a String representation of DriveId (DriveId.encodeToString()
* #param titl file/folder name (optional)
* #param mime file/folder mime type (optional)
* #return void (arraylist of found objects in callback)
*/
static void find(String prnId, String titl, String mime) {
// add query conditions, build query
ArrayList<Filter> fltrs = new ArrayList<>();
if (prnId != null){
fltrs.add(Filters.in(SearchableField.PARENTS,
prnId.equalsIgnoreCase("root") ?
Drive.DriveApi.getRootFolder(mGAC).getDriveId() : DriveId.decodeFromString(prnId)));
}
if (titl != null) fltrs.add(Filters.eq(SearchableField.TITLE, titl));
if (mime != null) fltrs.add(Filters.eq(SearchableField.MIME_TYPE, mime));
Query qry = new Query.Builder().addFilter(Filters.and(fltrs)).build();
// fire the query
Drive.DriveApi.query(mGAC, qry).setResultCallback(new ResultCallback<MetadataBufferResult>() {
#Override
public void onResult(MetadataBufferResult rslt) {
if (rslt.getStatus().isSuccess()) {
MetadataBuffer mdb = null;
try {
mdb = rslt.getMetadataBuffer();
for (Metadata md : mdb) {
if (md == null || !md.isDataValid() || md.isTrashed()) continue;
// collect files
DriveId driveId = md.getDriveId();
String dId = driveId.encodeToString();
String mime = md.getMimeType();
//.....
}
} finally { if (mdb != null) mdb.close(); } // don't know if necessary
}
}
});
}
Your mimeType filter doesn't look right, either. I suggest skipping the mimeType filter, search by name(title) only and double-check the mime type you're getting (the md.getMimeType() in the code above).
BEWARE! File name/title IS NOT UNIQUE IDENTIFIER in the GooDrive universe
ONE MORE BEWARE! You will not see the file if t was not created by your Android App (see GDAA supported SCOPES).
Good Luck

declaring key in IsolatedStorageSettings

my goal is retrieve value of counter which was stored last time when application closed.
i.e. i am storing the counter value in isolated storage. if counter has value 5 and application is closed and again started i should be able to retrieve 5.
for this purpose i have written following code but i cannot make out of it.
IsolatedStorageSettings isoStoreSettings = IsolatedStorageSettings.ApplicationSettings;
int count=0;
isoStoreSettings["flag"];
if (isoStoreSettings["flag"]!="set")
{
isoStoreSettings["count"] = count;
isoStoreSettings["flag"] = "set";
}
count = isoStorageSettings["count"]; //using the value of count stored previously
//some code which updates the count variable
isoStorageSettings["count"]=count;
the problem with this code is that declaration of key in isolatedstorage is now allowed, we must assign some value to that key
but if i assign value to that key, it will reinitialize the key each time application is started.
so, if anyone can solve this, please help
even there is any other alternative to isolatedstorage for my goal then also please share.
If you want to load your count every time the App is Launched then put your code in Application_Launching event in App.xaml.cs:
// declare static variable which you will be able to access from anywhere
public static int count;
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("count")) count = (int)settings["count"];
else count = 0;
}
On Clising event - save your variable:
private void Application_Closing(object sender, ClosingEventArgs e)
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("count")) settings["count"] = count;
else settings.Add("count", count);
settings.Save();
}
From anywhere in your code, you should be able to access your variable like this:
int myVariable = App.count;
App.count++;
// and so on
Note that you may also think about Activated and Deactivated events - for more information read MSDN.
I also don't know what flag suppose to do, but code above should save your variable just fine.
Use updated count value in Add method like below:
IsolatedStorageSettings isolatedStorageSettingsCount = IsolatedStorageSettings.ApplicationSettings;
if (isolatedStorageSettingsCount.Contains("count"))
{
isolatedStorageSettingsCount.Remove("count");
isolatedStorageSettingsCount.Add("count",5);
IsolatedStorageSettings.ApplicationSettings.Save();
}
else
{
isolatedStorageSettingsCount.Add("count",5);
IsolatedStorageSettings.ApplicationSettings.Save();
}
To retrive your count value use below code:
IsolatedStorageSettings isolatedStorageSettingsCount = IsolatedStorageSettings.ApplicationSettings;
string strCount = (string)isolatedStorageSettingsCount["count"];
int count=Convert.ToInt32(strCount);

I want to store json values in my android device

I want to store json values in my device. Because everytime application takes time to load json values. Instead of doing number of times to load, just want to load entire json values once. and without internet I can work with that. Once internet get connected, the application automatically load json values. How can I do this ?
You Can use Database for that.
This way also you can store it.
Arraylist<ClassName> jsondata=new ArrayList<ClassName>
Here's an example:
public Class ClassName
{
string fname;
string lname;
public void setfname(String fname)
{
this.fname=fname;
}
public void setlname(String lname)
{
this.lname=lname;
}
public String getlname(String lname)
{
return lname;
}
public String getfname(String fname)
{
return fname;
}
You can use SharedPreferences to save the json in application's storage space.
code
/* save */
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
Editor editor = pref.edit();
editor.put("myjson", json.toString());
editor.commit();
/* restore */
JSONObject ret = null;
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
String jsonStr = pref.getString("myjson", null);
if (!TextUtil.isEmpty(jsonStr)) {
ret = new JSONObject(jsonStr); // need try-catch
}
======
Do the restore every time the app is launching.
For the second part "Once internet get connected, the application automatically load json values."
You need to listen the network state change broadcast. When you get broadcast said the network (or wifi) is connected, grab the newest json from server, replace the json in the memory and save it to SharedPreferences