How to store the Local image path in sqlite or xml database in Xamrin.Forms - xamarin

I have given task to store the image path in database either xml schema or sqlite database.I am working on Xamarin.Forms PCL project. I am very confused with how to store image path in database.because in android image should be placed in Ressource/drawble,ios image placed in Resources folder. I read this xamarin.forms documentaion. But not getting how to get path and store in database. Please anyone provide any resources or example.

Hope you have gone through this documentation and to distinguish between iOS and Android is also Given here in this documentation .
if (Device.OS == TargetPlatform.iOS) {
// Save in sqlite with iOS path
}if (Device.OS == TargetPlatform.Android) {
// Save in sqlite with Android path
}
Hope it helps.

Related

Flutter Workflow for saving & retrieving images

I am trying to build an app where the user can add images from Image Picker, then save it in a Provider as well as in Firebase. For retrieving it should be the other way around: Get it from Firebase and then store it in my Provider.
(ignore the Firebase part, for now I only want to store the images in a Provider, but it should be correctly set up, so I can add the Firebase support later)
The problem is that I am quite new to Flutter and I am not how to start here, because there are so many ways to load images in Flutter. From the ImagePicker I retrieve a File. What is the correct way to store this in a Provider so I can load it in another screen?
I know this is quite a genreal question but I hope some one can shed some light in the dark for me here :D Let me know if you need any more info.
I already setup a ChangeNotifier:
class MemoryImageProvider extends ChangeNotifier {
String path = '';
setImage(String path) {
path = path;
notifyListeners();
}
}

Adding dynamic assets to Flutter app in runtime

I have Flutter app which needs to load dynamic assets and content which I want to save for later use. I know about Assets I can have in build time at the folder "assets/" inside the app.
I want to download content using ZIP files and unzip them to app local folder so they won't delete in the next app update.
what are the folders Flutter allows me to add assets to at runtime?
You cannot dynamically add assets to Flutter app at runtime and that is why Shared_Preferences package was developed by the official Flutter_Dev Team.
https://pub.dev/packages/shared_preferences
If you want to store a File instead of bits of information then refer to the below example code (For a Image File):
Future getImage(ImageSource imageSource) async {
// using your method of getting an image
final File image = await ImagePicker.pickImage(source: imageSource);
// getting a directory path for saving
final String path = await getApplicationDocumentsDirectory().path;
// copy the file to a new path
final File newImage = await image.copy('$path/image1.png');
setState(() {
_image = newImage;
});}
If your still want to somehow add/delete files dynamically then the answer is that it is practically not possible because assets weren't designed to dynamically store files.
One should only use assets to store files which shall remain common for all users.

Xamarin can not read the file

I'm trying to read a Json file for my mobile app in Xamarin Studio, but it throws me an error
can not find the file
While I try the same in Console Application every thing is all right.
I'm trying reading the file this way:
string Jason = File.ReadAllText(#"C:\Folder\file.txt")
This information is taken from Xam160 Class from Xamarin University. Within mobile application the platform generates a isolated folder area specifically for your App. These are the preferred locations to store files specific to your App with AppHome representing the Root of your sandboxed area.
Android - AppHome/files
iOS - AppHome/Lirbrary/[subdirectory]
Windows Phone - AppHome\Local
To Access these paths you can work with the Environment.SpecialFolder Enumeration to access these locations with the Environment.GetFolder() Method.
//Android
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
//iOS
string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libFolder = System.IO.Path.Combine(docFolder,"..","Library");
// Windows has different implementation. GetFolder Path with throw exception on windows.
string path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
Each of these will get you access to the path you need to be able to read and write files locally on which platform you are on.

How can I save some user data locally on my Xamarin Forms app?

I have a simple Xamarin Forms app. I've now got a simple POCO object (eg. User instance or an list of the most recent tweets or orders or whatever).
How can I store this object locally to the device? Lets imagine I serialize it as JSON.
Also, how secure is this data? Is it part of Keychains, etc? Auto backed up?
cheers!
You have a couple options.
SQLite. This option is cross-platform and works well if you have a lot of data. You get the added bonus of transaction support and async support as well. EDIT: In the past I suggested using SQLite.Net-PCL. Due to issues involving Android 7.0 support (and an apparent sunsetting of support) I now recommend making use of the project that was originally forked from: sqlite-net
Local storage. There's a great nuget that supports cross-platform storage. For more information see PCLStorage
There's also Application.Current.Properties implemented in Xamarin.Forms that allow simple Key-Value pairs of data.
I think you'll have to investigate and find out which route serves your needs best.
As far as security, that depends on where you put your data on each device. Android stores app data in a secure app folder by default (not all that secure if you're rooted). iOS has several different folders for data storage based on different needs. Read more here: iOS Data Storage
Another option is the Xamarin Forms settings plugin.
E.g. If you need to store a user instance, just serialize it to json when storing and deserialize it when reading.
Uses the native settings management
Android: SharedPreferences
iOS: NSUserDefaults
Windows Phone: IsolatedStorageSettings
Windows RT / UWP: ApplicationDataContainer
public User CurrentUser
{
get
{
User user = null;
var serializedUser = CrossSettings.Current.GetValueOrDefault<string>(UserKey);
if (serializedUser != null)
{
user = JsonConvert.DeserializeObject<User>(serializedUser);
}
return user;
}
set
{
CrossSettings.Current.AddOrUpdateValue(UserKey, JsonConvert.SerializeObject(value));
}
}
EDIT:
There is a new solution for this. Just use Xamarin.Essentials.
Preferences.Set(UserKey, JsonConvert.SerializeObject(value));
var user= JsonConvert.DeserializeObject<User>(Preferences.Get(UserKey, "default_value");
Please use Xamarin.Essentials
The Preferences class helps to store application preferences in a key/value store.
To save a value:
Preferences.Set("my_key", "my_value");
To get a value:
var myValue = Preferences.Get("my_key", "default_value");
If you want to store a simple value, such as a string, follow this Example code.
setting the value of the "totalSeats.Text" to the "SeatNumbers" key from page1
Application.Current.Properties["SeatNumbers"] = totalSeats.Text;
await Application.Current.SavePropertiesAsync();
then, you can simply get the value from any other page (page2)
var value = Application.Current.Properties["SeatNumbers"].ToString();
Additionally, you can set that value to another Label or Entry etc.
SeatNumbersEntry.Text = value;
If it's Key value(one value) data storage, follow below code
Application.Current.Properties["AppNumber"] = "123"
await Application.Current.SavePropertiesAsync();
Getting the same value
var value = Application.Current.Properties["AppNumber"];

How to decode a bitmap from a local file deployed with Android application

I am going through http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/
and trying to get the Local Images working with Android however I am experiencing some issues when attempting to do something in normal monodroid just as a further test. I'm using a SharedProject, just for reference.
I have added the test image at Resources/drawable (test1.png), and also setting the Build Action as AndroidResource as it describes, and if I do the following in Xamarin.Forms it works:-
Xamarin.Forms.Image myimage = new Image();
myimage.Source = ImageSource.FromFile("test1.png");
However, if I try and retrieve the same file via the following it comes back as null.
Android.Graphics.Bitmap objBitmapImage = Android.Graphics.BitmapFactory.DecodeFile("test1.png")
Does anyone know why this is null and how to correct?
The Xamarin.Forms FileImageSource has a fallback mode as it covers two different scenarios.
First it will check whether the file exists in the file system via the BitmapFactory.DecodeFile.
Should the file not exist as specified in the File property, then it will use BitmapFactory.DecodeResource to try and load the resource content as a secondary alternative.
FileImageSource for Android therefore isn't only just for files that exist in the file system but also for retrieving named resources also.
This link indicates that Android Resources are compiled into the application and therefore wouldn't be part of the file system as physical files.
Since test1.png is a Drawable you should use BitmapFactory.DecodeResource ()
string scr = "#drawable/test1.png";
ImageView iv = new ImageView(context);
Bitmap bm = BitmapFactory.DecodeFile(src);
if (bm != null)
iv.SetImageBitmap(bm);

Resources