Xamarin Android : Retain data on activity change and come back - xamarin

I'm developing an app in Xamarin.android where in I want to retain the data of Edit Text, spinners etc. whenever i revisit to that activity. E.g.
Activity A contains Edit Text, Spinners.
I navigate to Activity B from Activity A, and whenever I come back to Activity A from B I want to retain those values of Edit Text and Spinners.
I tried using Put Extra and Get Extra, but as there are multiple values this approach seems to be wrong.
var activity2 = new Intent (this, typeof(Activity2));
activity2.PutExtra ("MyData", "Data from Activity1");
StartActivity (activity2);
Also OnSaveInstanceState and OnRestoreInstanceState is not working out for me as I'm using Fragments in my Activity A
Please Guide

Can't your fragments save their own data using Fragment.onSaveInstanceState ?

in your case you need to save this temp data in Shared Preference
here is example
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutInt(("number_of_times_accessed", accessCount++);
editor.PutString("date_last_accessed", DateTime.Now.ToString("yyyy-MMM-dd"));
editor.Apply();
save what ever you want int or string
and when you load you activity retrieve this data and set it to your views
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
string passedString = prefs.GetString(key, defValue);
// here set retured data to your view
// Ex : YourEditText.Text = passedString
hope this help

Related

Duplicated display of NSUserActivity in Spotlight

I know there are several posts on this topic out there but they differed to much from my problem.
I am trying to display my NSUserActivity in Spotlight Search. For my NSUserActivity I am using three APIs: .isEligibleForHandoff, .isEligibleForSearch and .isEligibleForPrediction.
My problem is that my activity is being displayed twice in the Spotlight Search and that one of the results delivers an empty userInfo and the other one doesn't. However the Apple Programming Guide suggests:
Use the following strategies to avoid creating duplicate
representations of a single item:
If you’re using both NSUserActivity and Core Spotlight APIs to index
an item, use the same value for relatedUniqueIdentifier and
uniqueIdentifier to link the representations of the item.
But I don't think this is even my problem since I am not using any Core Spotlight APIs.
Thats my code inside my UIResponder class:
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String)
attributeSet.title = "Place Order Search"
attributeSet.contentDescription = "Get Your Avocado Toast Now"
attributeSet.relatedUniqueIdentifier = ActivityType.placeOrder.rawValue
let avocadoToastDictionary = AvocadoToastManger.dictionary(from: avocadoToastOrder)
let jsonAvocadoToastData = json(from: avocadoToastDictionary)
let activity = NSUserActivity(activityType: ActivityType.placeOrder.rawValue)
activity.title = "Place Order"
activity.userInfo = ["PlaceOrder.avocadoToast": jsonAvocadoToastData]
activity.requiredUserInfoKeys = ["PlaceOrder.avocadoToast"]
activity.suggestedInvocationPhrase = "Order an Avocado Toast"
activity.keywords = ["Order", "Avocado Toast"]
activity.isEligibleForHandoff = true
activity.isEligibleForSearch = true
activity.isEligibleForPrediction = true
activity.contentAttributeSet = attributeSet
self.userActivity = activity
activity.becomeCurrent()
Note: The updateUserActivityState(activity:) method is getting called twice in a row.
So how can I void getting multiple search results in the Spotlight Search and make sure the one which has the userInfo property set stays.

How to get the location/filepath of a file opened in Windows programmatically?

I am working on a project that needs to extract the location of a file opened in Windows.For example if a Word document is opened, I need to programmatically determine the location of the file which was opened.
I have tried using GetWindowModuleFileName() but that only provides the location where Word is installed.
The other approaches I have already tried out are:
Using Microsoft.Office.Interop to get the path using word.ActiveDocument.FullName, but it supports only Office files and that too upto Office 2013.
Handle utility which provides all the window handles referencing a given process(PID). I need to parse the output provided by this in order to isolate the file path which could be any one handle in the list and it's a difficult task.
I was wondering if there is any alternate approach/es more direct than those which I have mentioned here.
Thank you for your time.
Edit: My program uses Java Native Access(JNA) currently to get the active windows.
Here is my code:
public synchronized Map<String, Object> getWindowDetails() {
Map<String, Object> titleProcessIdMap = new LinkedHashMap<>();
char[] buffer = new char[Constants.MAX_TITLE_LENGTH * 2];
//get active window
WinDef.HWND hwnd = User32.INSTANCE.GetForegroundWindow();
//get rectangle structure of active window
WinDef.RECT rect = new WinDef.RECT();
User32.INSTANCE.GetWindowRect(hwnd, rect);
//get active window title
User32.INSTANCE.GetWindowText(hwnd, buffer, Constants.MAX_TITLE_LENGTH);
String windowTitle = Native.toString(buffer).replaceAll("\'", "\\\'");
//get process Id of active window
IntByReference pointer = new IntByReference();
User32.INSTANCE.GetWindowThreadProcessId(hwnd, pointer);
//add data to map
titleProcessIdMap.put("title", windowTitle);
titleProcessIdMap.put("pid", String.valueOf(pointer.getValue()));
titleProcessIdMap.put("rect", rect);
return titleProcessIdMap;
}
Suppose the "active window" is a Word Document, I need a way of identifying that it is a Word document and getting the filepath/location of the opened Word document in the system.

Check programmatically if a value is compliant with a datavalidation rule

I am using data validation rules on a Google Spreadsheet.
In my scenario, I need users to entry only valid values. I use the 'Reject input' to force them to write only validated content.
However, the 'Reject input' option works for manually entried data only, but it does not work if the user pastes content into the cell from a different source (e.g. a MS Excel document). In that case, a warning is still shown but the invalid value is written.
In other words, I need the 'Reject input' option to work also with pasted content.
OR... another approach would be to programmatically check the validity of the value according the Datavalidation rule for that cell.
Any ideas?
Thank you in advance.
I had a little play with this.
I had inconsistent behavior from google.
On occasion when I ctrl-c and ctrl-p, the target cell lost its data validation!
To do this programmatically
Write myfunction(e)
Set it to run when the spreadsheet is edited, do this by Resources>Current Project's Triggers
Query e to see what has happened.
Use the following to gather parameters
var sheet = e.source.getActiveSheet();
var sheetname = sheet.getSheetName();
var a_range = sheet.getActiveRange();
var activecell = e.source.getActiveCell();
var col = activecell.getColumn();
var row = activecell.getRow();
You may wish to check a_range to make sure they have not copied and pasted multiple cells.
Find out if the edit happened in an area that you have data validated;
if (sheetname == "mySheet") {
// checking they have not just cleared the cell
if (col == # && activecell.getValue() != "") {
THIS IS WHERE YOU CHECK THE activecell.getValue() AGAINST YOUR DATA VALIDATION
AND USE
activecell.setValue("") ;
to clear the cell if you want to reject the value
}
}
The obvious problem with this is that it is essentially repeating programmatically what the data validation should already be doing.
So you have to keep two sets of validation rules synchronized. You could just delete the in sheet data validation but I find that useful for providing the user feedback. Also is the data validation you are using provides content it is practical to leave it in place.
It would be great if there was a way of detecting that ctrl-p had been used or one of the paste-special options and only run the script in those cases. I would really like to know the answer to that. Can't find anything to help you there.
Note also that if someone inserts a row, this will not trigger any data validation and the onEdit() trigger will not detect it. It only works when the sheet is edited and by this I think it means there is a content change.
onChange() should detect insertion, it is described as;
Specifies a trigger that will fire when the spreadsheet's content or
structure is changed.
I am posting another answer because this is a programmatic solution.
It has a lot of problems and is pretty slow but I am demonstrating the process not the efficiency of the code.
It is slow. It will be possible to make this run faster.
It assumes that a single cell is pasted.
It does not cater for inserting of rows or columns.
This is what I noticed
The onEdit(event) has certain properties that are accessible. I could not be sure I got a full listing and one would be appreciated. Look at the Spreadsheet Edit Events section here.
The property of interest is "e.value".
I noticed that if you typed into a cell e.value = "value types" but if you pasted or Paste->special then e.value = undefined. This is also true for if you delete a cell content, I am not sure of other cases.
This is a solution
Here is a spreadsheet and script that detects if the user has typed, pasted or deleted into a specific cell. It also detects a user select from Data validation.
Type, paste or delete into the gold cell C3 or select the dropdown green cell C4.
You will need to request access, if you can't wait just copy & paste the code, set a trigger and play with it.
Example
Code
Set the trigger onEdit() to call this or rename it to onEdit(event)
You can attach it to a blank sheet and it will write to cells(5,3) and (6,3).
function detectPaste(event) {
var sheet = event.source.getActiveSheet();
var input_type =" ";
if (event.value == undefined) { // paste has occured
var activecell = event.source.getActiveCell();
if (activecell.getValue() == "") { // either delete or paste of empty cell
sheet.getRange(5,3).setValue("What a good User you are!");
sheet.getRange(6,3).setValue(event.value);
input_type = "delete"
}
else {
activecell.setValue("");
sheet.getRange(5,3).setValue("You pasted so I removed it");
sheet.getRange(6,3).setValue(event.value);
input_type = "paste";
}
}
else { // valid input
sheet.getRange(5,3).setValue("What a good User you are!");
sheet.getRange(6,3).setValue(event.value);
input_type = "type or select";
}
SpreadsheetApp.getActiveSpreadsheet().toast('Input type = ' + input_type, 'User Input detected ', 3);
}

Saving settings on Phonegap/Javascript app

I have an Android Phonegap app made with HTML5/Javascript/CSS. I'd like to suggest the users to choose between light and dark themes at the very first start of the app. When the user once chooses one of them this chose should be saved and relevant theme should be set as default at evry further start of the app. I have read some posts on this theme and am not sure which solution to take: Cache, cookies or HTML5 local storage (I am not familiar with any of them). Which one fits better to my app?
Thank you all!
localStorage wins, simply for persistence and ease-of-use:
// set the selected theme
localStorage.setItem("appTheme") = "dark";
...
var lsTheme = localStorage.getItem("appTheme"),
theme = (typeof lsTheme !== "undefined" ? lsTheme : "bright");
// do something with the selected theme; "bright" is default if no preference stored.
localStorage is the simplest and most effective solution like Kerri Shotts said however the setItem methods syntax is different to that displayed in her answer. As it takes to parameters one being the keyName the other being the keyValue like so: storage.setItem(keyName, keyValue); This then retrieved using the getItem method like so: var aValue = storage.getItem(keyName);.
e.g.
localStorage.setItem('bgcolor', 'red');
localStorage.setItem('font', 'Helvetica');
localStorage.setItem('image', 'myCat.png');
var currentColor = localStorage.getItem('bgcolor');
var currentFont = localStorage.getItem('font');
var currentImage = localStorage.getItem('image');

Programmatically select and clear selection on an ADF DVT piegraph

I am using a pieGraph and doing some page interactions based on clicking on the pie-graph. These work just fine.
<dvt:pieGraph id="graph1" tabularData="#{dc.bean.tabularData}" dataSelection="single"
selectionListener="#{dc.bean.transfersGraphSelectionListener}"/>
However I am not able to support the following use cases
Clicking outside the graph(or clicking a selected data set again) should cause the pie-graph to lose its selection.
Having a clear button on the page which forces the graph to lose its current selection.
Programmatically select one of the data sets in the graph
I checked the UIGraph API but couldn't find much information.
Any hints would be really helpful.
please add the right code to your original post. this is what your code look like
transfersGraphSelectionListener(SelectionEvent selectionEvent){
Set<GraphSelection> selectionSet = selectionEvent.getGraphSelection();
for (GraphSelection selection : selectionSet) {
if (selection instanceof DataSelection) {
DataSelection ds = (DataSelection) selection;
Set seriesKeySet = ds.getSeriesKey().keySet();
for (Object key : seriesKeySet) {
Object selectedKey = ds.getSeriesKey().get((String) key))
}
Looks like something is missing!

Resources