I am trying to access a static database that is stored in assets using this answer. I therefore set up my main() function like this:
main() async {
// Construct a file path to copy database to
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "asset_worldcities.db");
// Only copy if the database doesn't exist
if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound) {
// Load database from asset and copy
ByteData data = await rootBundle.load(join('assets', 'worldcities.db'));
List<int> bytes = data.buffer.asUint8List(
data.offsetInBytes, data.lengthInBytes);
// Save copied asset to documents
await new File(path).writeAsBytes(bytes);
}
Directory appDocDir = await getApplicationDocumentsDirectory();
String databasePath = join(appDocDir.path, 'asset_database.db');
this.db = await openDatabase(databasePath);
initialized = true;
runApp(Globeye());
}
However this seems not to be allowed as Android Studio marks this as illegal reference and also complains about that the name initialize is undefined. How can I correctly set this up?
You can copy paste run full code below
You can use DatabaseHelper to do this
code snippet
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
var databasesPath = await getDatabasesPath();
var path = join(databasesPath, "asset_database.db");
print(path);
// delete existing if any
await deleteDatabase(path);
// Make sure the parent directory exists
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
// Copy from asset
ByteData data = await rootBundle.load(join("assets", "worldcities.db"));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(path).writeAsBytes(bytes, flush: true);
// open the database
var db = await openDatabase(path);
return db;
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Database db = await DatabaseHelper().db;
print(db.path);
runApp(MyApp());
}
output
I/flutter ( 6569): /data/user/0/yourdomain.projecct/databases/asset_database.db
I/flutter ( 6569): /data/user/0/yourdomain.projecct/databases/asset_database.db
full code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
var databasesPath = await getDatabasesPath();
var path = join(databasesPath, "asset_database.db");
print(path);
// delete existing if any
await deleteDatabase(path);
// Make sure the parent directory exists
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
// Copy from asset
ByteData data = await rootBundle.load(join("assets", "worldcities.db"));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(path).writeAsBytes(bytes, flush: true);
// open the database
var db = await openDatabase(path);
return db;
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Database db = await DatabaseHelper().db;
print(db.path);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Related
I am working on quiz I have saved the question id and the option id in array now I have to post these data in http post method in json object. I don't know how to convert array into json object
here is my http.post method..
submit(testId,List<String> answer) async {
try {
Response response = await post(
Uri.parse(NetworkConstants.BASE_URL + 'get-participate-to-test/${widget.id}'),
headers: {
"Authorization": "Bearer $token"
},
body:json.encode(
{
'test_id': testId,
'question': answer,
}
));
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
// Navigator.of(context).pushAndRemoveUntil(
// MaterialPageRoute(builder: (context) => HomeScreen()),
// (Route<dynamic> route) => false);
} else {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
}
} catch (e) {
setState(() {
print(e);
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Exception:"),
content: Text(e.toString()),
actions: [
TextButton(
child: Text("Try Again"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
}
here I am sending Variable (answer) as list [{question_id: 2, option_id: 14}]
how to convert it in json encode object and post in the body of the method?
Here the answer is List of Map<String, int>. You are are already converting it to json by using json.encode in body.
submit(testId,List<Map, String> answer) async {
try {
Response response = await post(
Uri.parse(NetworkConstants.BASE_URL + 'get-participate-to-test/${widget.id}'),
headers: {
"Authorization": "Bearer $token"
},
body:json.encode(
{
'test_id': testId,
'question': answer,
}
));
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
// Navigator.of(context).pushAndRemoveUntil(
// MaterialPageRoute(builder: (context) => HomeScreen()),
// (Route<dynamic> route) => false);
} else {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
}
} catch (e) {
setState(() {
print(e);
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Exception:"),
content: Text(e.toString()),
actions: [
TextButton(
child: Text("Try Again"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
UsersController.cs
namespace testlol
{
[ApiController]
public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> _logger;
static readonly Models.IUserRepository repository = new Models.UserRepository();
public UsersController(ILogger<UsersController> logger)
{
_logger = logger; //what is this ?
}
[HttpGet]
[Route("api/users")]
public IEnumerable<Models.UserModel> GetAllUsers()
{
return repository.GetAll();
}
[HttpPost]
[Route("api/user")]
[Consumes("application/json")]
public Models.UserModel PostUser(Models.UserModel item)
{
return repository.Add(item);
}
}
}
Where I then use the service in react:
userService.js
export async function getAllUsers() {
const response = await fetch('/api/users');
return await response.json();
}
Then, I try to call it in a component:
import { getAllUsers } from "../services/userService.js"
...
useEffect(() => {
const getUserList = () => {
console.log("Getting user list ..");
getAllUsers()
.then(userList => {
console.log("User list: ")
console.log(userList)
setUsers(userList)
});
}
getUserList()
}, [])
This always yields the error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I'm not sure how the program isn't working. I saw that it could be a blank string, but I'm also currently storing some hardcoded values in another file:
public UserRepository()
{
Add(new UserModel { email = "test#mail.com", password ="password" });
Add(new UserModel { email = "admin#mail.com", password ="admin" });
}
I wanted to back up my Flutter SQFlite database to mobile.
And i need to restore the database in existing app.
I am searching on internet but did not get any proper tutorial or document.
Anyone please help!!!
Thanks in advance.
For complete details, go to link
ElevatedButton(
onPressed: () async {
final dbFolder = await getDatabasesPath();
File source1 = File('$dbFolder/doggie_database.db');
Directory copyTo =
Directory("storage/emulated/0/Sqlite Backup");
if ((await copyTo.exists())) {
// print("Path exist");
var status = await Permission.storage.status;
if (!status.isGranted) {
await Permission.storage.request();
}
} else {
print("not exist");
if (await Permission.storage.request().isGranted) {
// Either the permission was already granted before or the user just granted it.
await copyTo.create();
} else {
print('Please give permission');
}
}
String newPath = "${copyTo.path}/doggie_database.db";
await source1.copy(newPath);
setState(() {
message = 'Successfully Copied DB';
});
},
child: const Text('Copy DB'),
),
ElevatedButton(
onPressed: () async {
var databasesPath = await getDatabasesPath();
var dbPath = join(databasesPath, 'doggie_database.db');
FilePickerResult? result =
await FilePicker.platform.pickFiles();
if (result != null) {
File source = File(result.files.single.path!);
await source.copy(dbPath);
setState(() {
message = 'Successfully Restored DB';
});
} else {
// User canceled the picker
}
},
child: const Text('Restore DB'),
),
I created a flutter application with sign in and sign up screens, the sign up screens works perfectly well and saves the email and username in the firebase, but when I try to sign in this error occurs: Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0, and when I printed the size of the query snapshot it was zero.. Any help would be appreciated.
This is the code for the method that is called when I press the sign in button:
AuthMethods authMethods = new AuthMethods();
final formKey = GlobalKey<FormState>();
TextEditingController emailTextEditingController = new TextEditingController();
TextEditingController passwordTextEditingController = new TextEditingController();
QuerySnapshot snapshotUserInfo;
bool isLoading = false;
signMeIn() {
if (formKey.currentState.validate()) {
HelperFunctions.saveUserEmailSharedPrefrence(emailTextEditingController.text);
databaseMethods.getUserByUserEmail(emailTextEditingController.text).toString();
databaseMethods.getUserByUserEmail(emailTextEditingController.text).then((val) {
snapshotUserInfo = val;
HelperFunctions.saveUserNameSharedPrefrence(
snapshotUserInfo.docs[0].data()["name"]); });
setState(() {
isLoading = true; });
print("the size of the returnd query snapshot is:"); print(snapshotUserInfo.size);
print("is the snapshot null? "); print(snapshotUserInfo == null);
authMethods
.signInWithEmailAndPassword(emailTextEditingController.text,
passwordTextEditingController.text)
.then((val) {
if (val != null) {
HelperFunctions.saveUserLoggedInSharedPrefrence(true);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => ChatRoom())); }
});
}}
This is the code of the helper functions:
import 'package:shared_preferences/shared_preferences.dart';
class HelperFunctions {
static String sharedPrefrenceUserLoggedInKey = "ISLOGGEDIN";
static String sharedPrefrenceUserNameKey = "USERNAMEKEY";
static String sharedPrefrenceUserEmailKey = "USEREMAILKEY";
//saving data to share prefrence
static Future<bool> saveUserLoggedInSharedPrefrence(
bool isUserLoggedIn) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setBool(sharedPrefrenceUserLoggedInKey, isUserLoggedIn);
}
static Future<bool> saveUserNameSharedPrefrence(String userName) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setString(sharedPrefrenceUserNameKey, userName);
}
static Future<bool> saveUserEmailSharedPrefrence(String userEmail) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setString(sharedPrefrenceUserEmailKey, userEmail);
}
//getting data from share prefrence
static Future<bool> getUserLoggedInSharedPrefrence() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(sharedPrefrenceUserLoggedInKey);
}
static Future<String> getUserNameSharedPrefrence() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(sharedPrefrenceUserNameKey);
}
static Future<String> getUserEmailSharedPrefrence(String userEmail) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(sharedPrefrenceUserEmailKey);
}
}
And this the code of database.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseMethods {
getUserByUsername(String username) async {
return await FirebaseFirestore.instance
.collection("users")
.where("name", isEqualTo: username)
.get();
}
getUserByUserEmail(String userEmail) async {
return await FirebaseFirestore.instance
.collection("users")
.where("email", isEqualTo: userEmail)
.get();
}
uploadUserInfo(userMap) {
FirebaseFirestore.instance.collection("users").add(userMap).catchError((e) {
print(e.toString());
});
}
createChatRoom(String chatRoomId, chatRoomMap) {
FirebaseFirestore.instance
.collection("ChatRoom")
.doc(chatRoomId)
.set(chatRoomMap)
.catchError((e) {
print(e.toString());
});
}
}
And here is a screenshot from my firebase database:
I have two tables: 'notes' and 'groups'.Querying from groups works fine, as do all other requests, but from notes it does not.
I have the following: enter image description here
I do not understand what is the problem, code for getting the tables is the same, only names and formating to and from Json.
I hope it is not some obvious mistake that I just can not see.
My code is as follows:
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';
import 'package:path/path.dart';
import '../models/databaseException.dart' as de;
import '../models/note.dart';
import '../models/group.dart';
class DBProvider {
DBProvider._();
static final DBProvider db = DBProvider._();
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await initDatabase();
return _database;
}
initDatabase() async {
await deleteDatabase(join(await getDatabasesPath(), 'faks_projekt.db'));
return await openDatabase(
join(await getDatabasesPath(), 'faks_projekt.db'), //Path for db
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE notes(
id TEXT PRIMARY KEY,
n INTEGER,
title TEXT,
date TEXT,
groupId TEXT,
text TEXT
)
''');
await db.execute('''
CREATE TABLE groups(
id TEXT PRIMARY KEY,
title TEXT,
r INT,
g INT,
b INT
)
''');
},
version: 1,
);
}
Future<Group> getGroupById(String id) async {
try {
final db = await database;
final res = await db.query('groups', where: 'id=?', whereArgs: [id]);
return res.isNotEmpty ? Group.fromJson(res.first) : null;
} catch (error) {
throw new de.DatabaseException('Error while GETTING GROUP BY ID.');
}
}
Future<List<Group>> getAllGroups() async {
try {
var db = await database;
final res = await db.query('groups');
return res.isNotEmpty ? res.map((e) => Group.fromJson(e)).toList() : null;
} catch (error) {
throw new de.DatabaseException('Error while GETTING ALL GROUPS.');
}
}
Future<Note> getNoteById(String id) async {
try {
final db = await database;
final res = await db.query('notes', where: 'id=?', whereArgs: [id]);
return res.isNotEmpty ? Note.fromJson(res.first) : null;
} catch (error) {
print(error.toString());
throw new de.DatabaseException('Error while GETTING NOTE BY ID.');
}
}
Future<List<Note>> loadNotes() async {
try {
final db = await database;
final res = await db.query('notes');
return res.isNotEmpty ? res.map((e) => Note.fromJson(e)).toList() : null;
} catch (error) {
print(error.toString());
throw new de.DatabaseException('Error while GETTING ALL NOTES.');
}
}
}
I have found the solution, wrong data type when I was converting from json.