I am trying to save a string to SharedPerferences like this:
Write
var prefs = Application.Context.GetSharedPreferences ("Janssen", FileCreationMode.WorldReadable);
var prefEditor = prefs.Edit ();
prefEditor.PutString ("SecurityToken", SecurityCode.Text);
prefEditor.Commit ();
Read
var prefs = Application.Context.GetSharedPreferences ("Janssen", FileCreationMode.WorldReadable);
var SecurityToken = prefs.GetString ("SecurityToken", null);
I am new to Android coming from iOS. I am trying to emulate NSUserDefaults in iOS. I am reading the SharedPreferences in a new activity, maybe that is what causes the problem? I am not sure. I also have no idea what to set as default value.
Are you re-deploying between writing your SharedPreferences and reading them? This often wipes the SharedPreferences.
I have just tested them and they work fine between two Activities:
WritePrefsAcitivity.cs
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
namespace Derrrp
{
[Activity (Label = "Derrrp", MainLauncher = true)]
public class WritePrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Write);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
var prefsEditor = prefs.Edit();
var ed = FindViewById<EditText>(Resource.Id.editText1);
ed.AfterTextChanged += (sender, e) => {
prefsEditor.PutString("MyPref", e.Editable.ToString());
prefsEditor.Commit();
};
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
var intent = new Intent(this, typeof(ReadPrefsActivity));
StartActivity(intent);
};
}
}
}
ReadPrefsActivity.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
namespace Derrrp
{
[Activity (Label = "ReadPrefsActivity")]
public class ReadPrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.Read);
var tv = FindViewById<TextView>(Resource.Id.myTextView);
var button = FindViewById<Button>(Resource.Id.myButton);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
button.Click += (sender, e) => {
tv.Text = prefs.GetString("MyPref", "");
};
}
}
}
The defValue can be set to anything you want. This is the value that will be chosen if the preference you are trying to get is empty.
NOTE: If you are using it to store some secret information it is advised to use FileCreationMode.Private and even use something that makes it only readable by the application, such as encryption.
I am not sure what is the error you have, but below is an example i used before for saving a string using shared preferences.
I used to set default value to "", so that while reading, if the value was not saved before, it will set the variable to empty string. You can read the shared preferences in any new activity , shared preferences is per application not activity ..
example:
writing string:
String pass = "abcdefg";
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("savedPass", pass);
editor.commit();
reading string:
SharedPreferences preferences = getSharedPreferences("pref", 0);
String mypassword = preferences.getString("savedPass", "");
Related
I am new on xamarin and i am trying to save my checkbox state even if the app is closed because when i close it the checkbox reset to uncheck state...
also.. the image that was changed resets.. is there any way to preserve both?
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout1);
var seletor = FindViewById<CheckBox>(Resource.Id.checkBox1);
var imagem = FindViewById<ImageView>(Resource.Id.imageView1);
seletor.Click += (o, e) => {
if (seletor.Checked)
imagem.SetImageResource(Resource.Drawable.estado1);
else
imagem.SetImageResource(Resource.Drawable.estado2);
};
}
Have you tried to use the Preferences?
Check the following: How to save user settings
Store the option selected onclose or suspend.. and retrieve onResume / OnLoad
Something like:
// Function called from OnDestroy
protected void saveset(){
//store
var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
var prefEditor = prefs.Edit();
prefEditor.PutString("PrefName", "Some value");
prefEditor.Commit();
}
// Function called from OnCreate
protected void retrieveset()
{
//retreive
var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
var somePref = prefs.GetString("PrefName", null);
//Show a toast
RunOnUiThread(() => Toast.MakeText(this, somePref, ToastLength.Long).Show());
}
as in the link provided.
Of course you'll need to adapt to your needs and get / populate the value of the checkbox.
If you want, you can also implement some kind of db and use the same mechanism to persist and retrieve settings.
This is usually what I use to store settings and persist values that I need to "remember"
This is an example of how I'm using the same behavior in one app.. not for a checkbox.. but you can see how it works. I removed some code, but I think should be a good example.
[Activity(Label = "#string/ApplicationName",
Icon = "#drawable/Icon")]
public class PersonalDetailsActivity : Activity
{
...
private ISharedPreferencesEditor prefEditor;
private ISharedPreferences preferences;
...
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.PersonalDetailView);
preferences = Application.Context.GetSharedPreferences("AppName", FileCreationMode.Private);
PopulatePersistedData();
}
private void PopulatePersistedData()
{
myId = preferences.GetInt(nameof(myData.Id), 0);
name.Text = preferences.GetString(nameof(myData.Name), null);
address.Text = preferences.GetString(nameof(myData.Address), null);
city.Text = preferences.GetString(nameof(myData.City), null);
county.Text = preferences.GetString(nameof(myData.County), null);
emailAddress.Text = preferences.GetString(nameof(myData.Email), null);
phoneNumber.Text = preferences.GetString(nameof(myData.PhoneNumber), null);
bio.Text = preferences.GetString(nameof(myData.Bio), null);
rating.Rating = 5;
}
private void SaveButton_Click(object sender, EventArgs e)
{
prefEditor = preferences.Edit();
myData = new Citizen();
myData.Name = name.Text;
myData.Address = address.Text;
myData.City = city.Text;
myData.County = county.Text;
myData.Email = emailAddress.Text;
myData.PhoneNumber = phoneNumber.Text;
myData.Bio = bio.Text;
prefEditor.PutInt(nameof(myData.Id), myId);
prefEditor.PutString(nameof(myData.Name), myData.Name);
prefEditor.PutString(nameof(myData.Address), myData.Address);
prefEditor.PutString(nameof(myData.City), myData.City);
prefEditor.PutString(nameof(myData.County), myData.County);
prefEditor.PutString(nameof(myData.Email), myData.Email);
prefEditor.PutString(nameof(myData.PhoneNumber), myData.PhoneNumber);
prefEditor.PutString(nameof(myData.Bio), myData.Bio);
prefEditor.Apply();
prefEditor.Commit();
var intent = new Intent();
intent.PutExtra("CitizenName", name.Text);
SetResult(Result.Ok, intent);
this.Finish();
}
}
I'm building a xamarin app where I'm using a Preprocessed Razor Template as a webview. I used this guide to set it up: https://developer.xamarin.com/guides/cross-platform/advanced/razor_html_templates/
It's working great and all but every time I do some css changes I have to restart the app to see the css changes. Is there another way to do this so I don't have to restart the app every time?
I tried adding a button which reloads the webView but that did not work. This is my activity:
public class ItemWebViewActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var itemId = Intent.GetIntExtra("itemId", 0);
SetContentView(Resource.Layout.ItemWebView);
webView = FindViewById<WebView>(Resource.Id.webView);
var dataService = new AzureDataService();
var item = dataService.GetItem(itemId);
Button refreshButton = (Button)FindViewById(Resource.Id.refreshButton);
refreshButton.Click += ReloadPage;
var decodedDesc = WebUtility.HtmlDecode(item.Description);
var vm = new Item()
{
Artist = item.Artist,
Title = item.Title,
Picture = item.Picture,
Description = decodedDesc
};
var template = new ItemWebView() { Model = vm };
var page = template.GenerateString();
webView.LoadDataWithBaseURL("file:///android_asset/",page, "text/html", "charset=UTF-8",null);
}
private void ReloadPage(object sender, EventArgs e)
{
webView.Reload();
}
}
Would appreciate any help :)
So I'm working in Xamarin to make a C# android app for school and at some point the user needs to type in an IBAN number.
I want to check if the input equals 4 times 4 numbers with a dash between them (e.g. 1234-1234-1234-1234),
sadly I have no idea how to do this and I haven't found anything that could help me, so far.
This is my activity where I need to check if the input of "mTxtIBAN" equals the IBAN number.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace LoginSystem
{
[Activity (Label = "SubDetailsBankActivity")]
public class SubDetailsBankActivity : Activity
{
private Button mBtnContinue;
private EditText mTxtIBAN;
private EditText mTxtBIC;
private TextView mIBANWarning;
private TextView mBICWarning;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.SubBankDetails);
// Create your application here
string email = Intent.GetStringExtra ("Email") ?? "Data not available";
string firstName = Intent.GetStringExtra ("FirstName") ?? "Data not available";
string lastName = Intent.GetStringExtra ("LastName") ?? "Data not available";
string streetNumber = Intent.GetStringExtra ("StreetNumber") ?? "Data not available";
string cityCode = Intent.GetStringExtra ("CityCode") ?? "Data not available";
string country = Intent.GetStringExtra ("Country") ?? "Data not available";
mBtnContinue = FindViewById<Button> (Resource.Id.btnContinue);
mTxtIBAN = FindViewById<EditText> (Resource.Id.IBAN);
mTxtBIC = FindViewById<EditText> (Resource.Id.BIC);
mIBANWarning = FindViewById<TextView> (Resource.Id.IBANtext);
mBICWarning = FindViewById<TextView> (Resource.Id.BICtext);
mBtnContinue.Click += (object sender, System.EventArgs e) =>
{
if (mTxtIBAN.Text.Length != 0 && mTxtBIC.Text.Length != 0) {
var newSub = new Intent(this, typeof(SubDetailsComplete));
newSub.PutExtra ("Email", email);
newSub.PutExtra ("FirstName", firstName);
newSub.PutExtra ("LastName", lastName);
newSub.PutExtra ("StreetNumber", streetNumber);
newSub.PutExtra ("CityCode",cityCode);
newSub.PutExtra ("Country", country);
newSub.PutExtra ("IBAN", mTxtIBAN.Text);
newSub.PutExtra ("BIC", mTxtBIC.Text);
StartActivity (newSub);
}
if (mTxtIBAN.Text.Length == 0){
mIBANWarning.Text = "Fill in your IBAN number!";
}
if (mTxtBIC.Text.Length == 0){
mBICWarning.Text = "Fill in your BIC number!";
}
};
}
}
}
Any help would be much appreciated.
Thank you in advance and have a nice day.
You can check it this way:
Regex rgx = new Regex(#"^\d{4}?-\d{4}?-\d{4}?-\d{4}?$");
if (rgx.IsMatch(mTxtIBAN.Text))
{
// valid IBAN
}
I am building an app where user can select which Language he wants to set when the app starts. A pop up will show "Select your Language" with two buttons one for Arabic and the other one for English.
The problem is that when I change the locale and execute this line
SetContentView (Resource.Layout.Main);
the app broke. there is no error or any exception but all controls stop capturing the events. I tried to declare an Intent using this and this.Class and when I call StartActivity it is like restarting the whole app and the pop comes again to select the language. I am new to android development as I spent my last two years working on SAP Abap so I might ask a stupid question :D
here is my code
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Khums
{
[Activity (Label = "Khums", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
int r = Resource.Layout.Main;
SetContentView (Resource.Layout.Main);
var languageIso = "ar-SA";
AlertDialog.Builder alert = new AlertDialog.Builder (this);
//alert.SetTitle ("Selected Language");
AlertDialog alertDiaog = alert.Create ();
alertDiaog.SetTitle ("Select Language:");
alertDiaog.SetButton ("العربية", (s, EventArgs) => {
languageIso = "ar-SA";
var locale = new Java.Util.Locale(languageIso);
Java.Util.Locale.Default = locale;
var config = new Android.Content.Res.Configuration{Locale = locale };
BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
//base.SetContentView(r);
//Intent intent = new Intent(this, this.Class);
//StartActivity(intent);
SetContentView (Resource.Layout.Main);
});
alertDiaog.SetButton2 ("English", (s, EventArgs) => {
languageIso = "en-US";
var locale = new Java.Util.Locale(languageIso);
Java.Util.Locale.Default = locale;
var config = new Android.Content.Res.Configuration{Locale = locale };
BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
SetContentView (Resource.Layout.Main);
});
alertDiaog.Show();
Button button = FindViewById<Button> (Resource.Id.myButton);
RadioButton rb_FirstTime = FindViewById<RadioButton> (Resource.Id.radioButton1);
RadioButton rb_Regular = FindViewById<RadioButton> (Resource.Id.radioButton2);
EditText ti_lyearBalance = FindViewById<EditText> (Resource.Id.ti_lastBalance);
EditText ti_Balance = FindViewById<EditText> (Resource.Id.ti_Balance);
EditText ti_Clothes = FindViewById<EditText> (Resource.Id.ti_Clothes);
EditText ti_Food = FindViewById<EditText> (Resource.Id.ti_Food);
EditText ti_Perfumes = FindViewById<EditText> (Resource.Id.ti_Perfumes);
EditText ti_Subscriptions = FindViewById<EditText> (Resource.Id.ti_Subscriptions);
EditText ti_Others = FindViewById<EditText> (Resource.Id.ti_Others);
TextView lbl_lyearBalance = FindViewById<TextView> (Resource.Id.lbl_lastBalance);
rb_FirstTime.Click += RadioButtonHandler;
rb_Regular.Click += RadioButtonHandler;
button.Click += MyButtoHandler;
}
private void RadioButtonHandler(object sender, EventArgs e)
{
}
private void MyButtoHandler(object sender, EventArgs e)
{
}
private double calculateKhumus (double[] amounts, Boolean isRegular)
{
}
private void LangSwitchHndler(Object sender, EventArgs e)
{
}
}
}
can you please show me what I'm doing wrong here. I tried to use togglebutton instead of alert and also standard button but ends up with the same issue. Thank you.
It is solved after trying for two days. All I did is to create a menu and change the target framework to Android 3.1 Honeycomb. Then I just start the activity and everything is working fine.
So the issue was only target framework!
This is a xamarin application for android to compress or extract a given file entered by user in the textbox. I placed the sample file in the assets folder. The function zip on button click is supposed to compress the file On entering the filename and clicking the button it is throwing a filenotfound exception even after providing path of the file located.
namespace zipfile
{
[Activity (Label = "zipfile", MainLauncher = true)]
public class MainActivity : Activity
{
string t;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button> (Resource.Id.button1);
button1.Click += delegate {
EditText text = FindViewById<EditText>
(Resource.Id.editText2);
if (null == text)
return;
t="\\zip\\zipfile\\Assets\\"+ text.Text;
//Toast.MakeText(this,"file
zipped",ToastLength.Long).Show();
ZipOutputStream.Zip(t, t, 128);
};
Button button2 = FindViewById<Button> (Resource.Id.button2);
button2.Click += delegate {
//Toast.MakeText(this,"file
unzipped",ToastLength.Long).Show();
ZipInputStream.UnZip (t, t, 128);
};
}
}
}
I am new To Xamarin Please suggest me way to handle this exception.
You can't write to paths inside of the APK.
A simple file IO example:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(path, "file.txt");
using (var file = File.Open(filePath, FileMode.Create, FileAccess.Write))
using (var strm = new StreamWriter(file))
{
strm.Write(data);
}