I want to save and retrieve the image from local database. I insert image as blob in db but I am usable to retrieve image.
Please help me.
Thanks
Monali
What error are you getting? Using LINQ to SQL, the following code creates an HttpHandler and grabs a BLOB from a database...
public class GetFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Document document = new GigzDataContext().Documents.SingleOrDefault(p => p.Id == new Guid(context.Request.QueryString["Id"].ToString()));
context.Response.ContentType = document.ContentType;
context.Response.BinaryWrite(document.Blob.ToArray());
}
public bool IsReusable
{
get
{
return false;
}
}
}
See this link to have a concept on how to retrieve blob data from a database table as bytes, and after you have them in bytes, you should be able to save them into proper format to form your final image.
Related
I want to save an image inside the sqflite database and the later on, I want to display it in a SliverAppBar as a background. Till now I am able to save the image(not sure if it is right, but throws no error XD):
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path;
File newImage = await _image.copy('$path/${recipeName.text}.png'); //_image already taken with image_picker plugin
String base64Encoded = base64Encode(newImage.readAsBytesSync());
And this String I am saving inside the database. But I also want to display. And as far I know, I have to get the String, but from now I on, I do not know anything how to get further. I have written a function to get the String, but do not know what I should do with this String. The function looks like this:
Future fetchRecipe(String name) async{
var dbHelper = new DBHelper();
Future<List<Recipes>> recipes = dbHelper.getSpecRecipe(name);
return recipes;
}
The getSpecRecipe(name) points to this function:
Future<List<Recipes>> getSpecRecipe(String recipeName) async{
List<Map> list = await _db.rawQuery("SELECT * FROM recipes WHERE name = ?", [recipeName]);
List<Recipes> recipes = new List();
for(int i =0; i < list.length; i++){
recipes.add(new Recipes(list[i]["id"], list[i]["name"], list[i]["definition"], list[i]["duration"], list[i]["favorite"], list[i]["timestamp"], list[i]["image"], list[i]["backgroundColor"]));
}
return recipes;
}
It would be awesome, if somebody would be able to solve my problem. Thanks in advanceXD
From the snippets provided, it seems that you're trying to save the image as a base64 on your database. And as mentioned by #Nordeast in the comments, it's better to save the image on the device's storage and store the file path instead. Also, given the snippets provided, it's difficult to replicate the behavior locally.
I am making Android app for practicing driving licence theory tests. I will have about 3000 questions. Question object would have several atributes (text, category, subcategory, answers, group). I will create them and put in app, so data won't ever change. When user chooses category, app would go througt data, look which question meets requirements (that user selected) and put it in list for displaying. What should I use to store data/questions, XML or SQLite? Thanks in advance.
Edit:
I forgot to mentiont that app won't use internet connection. Also, I planned to make simple java app for entering data. I would copy text from government's website (I don't have access to their database and I have to create mine), so I thought to just put question's image url to java program and it would download it and name it automaticaly. Also, when entering new question's text it would tell me if that question already exist before I enter other data. That would save me time, I wouldn't have to save every picture and name it my self. That is what I thought if using XML. Can I do this for JSON or SQLite?
If you do not have to perform complex queries, I would recommend to store your datas in json since very well integrated in android apps using a lib such as GSON or Jackson.
If you don't want to rebuild your app / redeploy on every question changes. You can imagine to have a small webserver (apache, nginx, tomcat) that serves the json file that you will request on loading of the app. So that you will download the questions when your app is online or use the cached one.
XML is a verbose format for such an usage, and does not bring much functions....
To respond to your last question, you can organise your code like that :
/**
* SOF POST http://stackoverflow.com/posts/37078005
* #author Jean-Emmanuel
* #company RIZZE
*/
public class SOF_37078005 {
#Test
public void test() {
QuestionsBean questions = new QuestionsBean();
//fill you questions
QuestionBean b=buildQuestionExemple();
questions.add(b); // success
questions.add(b); //skipped
System.out.println(questions.toJson()); //toJson
}
private QuestionBean buildQuestionExemple() {
QuestionBean b= new QuestionBean();
b.title="What is the size of your boat?";
b.pictures.add("/res/images/boatSize.jpg");
b.order= 1;
return b;
}
public class QuestionsBean{
private List<QuestionBean> list = new ArrayList<QuestionBean>();
public QuestionsBean add(QuestionBean b ){
if(b!=null && b.title!=null){
for(QuestionBean i : list){
if(i.title.compareToIgnoreCase(b.title)==0){
System.out.println("Question "+b.title+" already exists - skipped & not added");
return this;
}
}
System.out.println("Question "+b.title+" added");
list.add(b);
}
else{
System.out.println("Question was null / not added");
}
return this;
}
public String toJson() {
ObjectMapper m = new ObjectMapper();
m.configure(Feature.ALLOW_SINGLE_QUOTES, true);
String j = null;
try {
j= m.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
System.out.println("JSON Format error:"+ e.getMessage());
}
return j;
}
}
public class QuestionBean{
private int order;
private String title;
private List<String> pictures= new ArrayList<String>(); //path to picture
private List<String> responseChoice = new ArrayList<String>(); //list of possible choices
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getPictures() {
return pictures;
}
public void setPictures(List<String> pictures) {
this.pictures = pictures;
}
public List<String> getResponseChoice() {
return responseChoice;
}
public void setResponseChoice(List<String> responseChoice) {
this.responseChoice = responseChoice;
}
}
}
CONSOLE OUTPUT
Question What is the size of your boat? added
Question What is the size of your boat? already exists - skipped & not added
[{"order":1,"title":"What is the size of your boat?","pictures":["/res/images/boatSize.jpg"],"responseChoice":[]}]
GIST :
provides you the complete working code I've made for you
https://gist.github.com/jeorfevre/5d8cbf352784042c7a7b4975fc321466
To conclude, what is a good practice to work with JSON is :
1) create a bean in order to build your json (see my example here)
2) build your json and store it in a file for example
3) Using android load your json from the file to the bean (you have it in andrdoid)
4) use the bean to build your form...etc (and not the json text file) :D
I would recommend a database (SQLite) as it provides superior filtering functionality over xml.
Create the db using DB Browser for SQLite
And then use the library SQLiteAssetHelper in the link-
https://github.com/jgilfelt/android-sqlite-asset-helper
Tutorial on how to use -
http://www.javahelps.com/2015/04/import-and-use-external-database-in.html
You can use Paper https://github.com/pilgr/Paper its a fast NoSQL data storage for Android.
SQLite is the best for your system. because you will have to maintain (text, category, subcategory, answers, group) etc. So if you create db and create table for them. That will be easy to manage and you can relationship with each other which is not possible to XML.
I'm developing an android app that uses SQLite as the local database. The app syncs data obtained from a web api and stores it in the local database. All the model classes have their ID property set as Primary key and Auto incremented so I can manually enter data without having to specify the ID. The issue is when I insert the data from the API into the SQlite, the ID of the object is ignored and Sqlite gives the object a new ID. I want the data stored with the same ID as the object being stored.
The web api returns the object lists that have their ID type long however the SQLite objects have their primary keys as int. Is this the reason why the ID values is not getting stored because their data types don't match? I can't change the datatype in my SQL database where the data comes from as there are hundreds of tables in it. Is there a way around it?
This is the Code to inserts or updates data in my local DB:
}
public async Task<string> insertUpdateVideoData(Video_Struct data)
{
try
{
var db = new SQLiteAsyncConnection(dbPath);
var m = GetVideos();
if (await db.FindAsync<Video_Struct>(f => f.VideoID == data.VideoID) != null)
{
await db.UpdateAsync(data);
}
else
{
if (await db.InsertAsync(data) != 0)
{
await db.UpdateAsync(data);
}
}
return "Single data file inserted or updated";
}
catch (SQLiteException ex)
{
return ex.Message;
}
}
This is the code to get data objects from the API:
public async Task<List<Video_Struct>> GetVideoData()
{
List<Video_Struct> vids = new List<Video_Struct>();
WebClient mClient = new WebClient();
var output = await mClient.DownloadDataTaskAsync(new Uri(GlobalVariables.host + "/api/media/getmedia"));
var json = Encoding.UTF8.GetString(output);
vids = JsonConvert.DeserializeObject<List<Video_Struct>>(json);
return vids;
}
If your local DB is a cache for web data and external DB gives you unique IDs, don't use auto increment in scheme, just re-use external IDs.
Actually, you can have a complex (compound) primary key, it depends on data unique properties.
If you do not work with your data as structured set you can try gson+SharedPreferences. Just don't forget to override equals and hashcode for your data models.
Datatype in not an issue, because sqlite uses INTEGER type.
so for my android application i can insert an image to sqlite as a string. But im not sure exactly how i can retrieve this image from the database and convert it to a Image from string and display it in my app. Stuck for weeks, help appreciated! :(
Button Click saves image to sqlite
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Student student = new Student(profadmin.getText().toString());
student.setImageUri(ImageUri);
stud.updateImage(student);
Toast passes = Toast.makeText(ProfileActivity.this, "Profile Picture has been updated", Toast.LENGTH_SHORT);
passes.show();
}
});
Database Handler:
public int updateImage(Student student) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STUDENT_IMAGEURI, student.getImageUri().toString());
int rowsAffected = db.update(STUDENT_TABLE, values, STUDENT_ADMINNO + "=?", new String[]{String.valueOf(student.getAdminNo())});
db.close();
return rowsAffected;
}
Edit: Uploaded the image by clicking the empty ImageView (profileIV) , opening the android emulator gallery, choose image and then image will be displayed on the app. Then i click the 'Upload' button and it sends it to the database and uploads
public void onActivityResult(int reqCode,int resCode,Intent data){
if(resCode==RESULT_OK){
if(reqCode==1){
ImageUri = data.getData();
profileIV.setImageURI(data.getData());
}
}
What you can do is storing your pictures in your drawable folder.
Then you will just have to store the name in your database and retrieve the corresponding image thanks to this one. It will also allow you to avoid a heavy DB file.
Why you need to store image into database? it's not a good choice.
If you have to store image into database, you can encode you image with Base64,and store the result string into database. so you can decode the string to image. But this way will cause problems with large images.
I suggest you to store images with disk cache.
I am writing a Xamarin Android application using SQLite and am not sure how to add an object to a table where the object has a list.
Here is my model class:
public class TestObject
{
[PrimaryKey]
public int Id { get; set; }
public string name { get; set; }
public DateTime lastUpdate { get; set; }
public List<TestItem> items { get; set; }
}
Here is my code to add an object to a table:
public void InsertObjectToDatabase<T>(string databasePath, T objType)
{
var db = new SQLiteConnection (databasePath);
db.CreateTable(typeof (T));
db.InsertOrReplace (objType);
}
Here is my code to add a TestObject to a table:
TestObject testObject = new TestObject ();
testObject.Id = 1;
testObject.name = "Test Object 1";
testObject.lastUpdate = DateTime.Now;
sQLiteService.InsertObjectToDatabase<TestObject> (filename, testObject);
This is the error that I am getting:
System.NotSupportedException: Don't know about System.Collections.Generic.List`1[LearningSQLite.TestItem]
Is it possible add a list to a SQLite table?
Thanks in advance
Create another table and refer to the parent table with a foreign key. Once you insert the row in parent, insert all the items from the list in the child. Read more here http://www.sqlite.org/foreignkeys.html
If you are using SQLite.Net-PCL you can use the IBlobSerializer interface to store complex types to a BLOB (byte array). Here is a unit test class that provides more info:
https://github.com/oysteinkrog/SQLite.Net-PCL/blob/master/tests/BlobSerializationTest.cs
For the serializer you can either implement your own or use something like JSON serializers to store the data as JSON.
I am using the BLOB interface to use SQLite as key-value pair caching mechanism:
https://github.com/XForms/Xamarin-Forms-Labs/blob/master/src/Xamarin.Forms.Labs/Plugins/Caching/Xamarin.Forms.Labs.Caching.SQLiteNet/SQLiteSimpleCache.cs