How can I update a data with SQFLite in Flutter? - database

static Future<int?> update(
String cariadi,
) async {
var dbClient = await _db;
return await dbClient?.rawUpdate('UPDATE $_tableName SET $cariadi = ');
}
This is how I created the database
void getCari() async {
List<Map<String, dynamic>> cariler = await DBCari.query();
cariList.assignAll(cariler.map((data) => Cari.fromJson(data)).toList());
}
void updateData(Cari cari) {
DBCari.update(cari.cariadi!);
getCari();
}
Try to connect value = key by creating a controller named CariController.
final _cariController = Get.put(CariController());
onTap: () {
_cariController.update();
},
Finally, I wanted to enable the user to edit the data entered by clicking on the edit part in a button I wanted. But nothing happened when the button was clicked.
What kind of code do I need to write in the database, controller and homepage I created so that the user can edit and update the data entered?

here is a reference :
Future<int> update(Map<String, dynamic> row) async {
Database db = await instance.database;
int id = row[columnId];
return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
}
https://github.com/DaymaManish/flutter_sqflite_crud/blob/main/lib/db_manager.dart

Related

.NET MAUI Setting an item SelectedIndex on Page Load is Delayed

When the view appears on the screen there is a short delay setting the values to each control. Is it possible to set the values before the user sees the view?
public UserSettingsView()
{
InitializeComponent();
LoadAsync();
}
private async void LoadAsync()
{
try
{
// Loading data from API
Languages = await _languageService.GetAsync(AccessToken);
USStates = await _uSStateService.GetAsync(AccessToken);
// Assigning the list to the ItemSource of each Picker.
ddlLanguages.ItemsSource = Languages;
ddlUSStates.ItemsSource = USStates;
// Getting the user's preferred settings
var userSettings = await _accountService.GetSettingsAsync(UserID, AccessToken);
if (userSettings != null)
{
// Setting user values to each Picker control.
// This is where the delay happens.
ddlLanguages.SelectedIndex = Languages.FindIndex(x => x.ID == userSettings .LanguageID);
ddlUSStates.SelectedIndex = USStates.FindIndex(x => x.ID == userSettings .USStateID);
cbAge.IsChecked = currentSettings.AgeQualified;
}
}
catch
{
await DisplayAlert("Oh no!", "Error loading the page", "OK");
}
}
To resolve the delay, I am passing the two lists for the languages and the States from the previous page.
public UserSettingsView(List<Language> _languages, List<USState> _usStates)
{
InitializeComponent();
Languages = _languages;
USStates = _usStates;
LoadAsync();
}
private async void LoadAsync()
{
try
{
ddlLanguages.ItemsSource = Languages;
ddlUSStates.ItemsSource = USStates;
var currentSettings = await _accountService.GetSettingsAsync(UserID, AccessToken);
if (currentSettings != null)
{
ddlLanguages.SelectedIndex = Languages.FindIndex(x => x.ID == currentSettings.LanguageID);
ddlUSStates.SelectedIndex = USStates.FindIndex(x => x.ID == currentSettings.USStateID);
switchAgeQualification.IsToggled = currentSettings.AgeQualified;
}
}
catch
{
await DisplayAlert("Error", "Could not load page data", "OK");
}
}
If I understand correctly, you currently have a line like this:
await Navigation.PushModalAsync(new UserSettingsView());
I don't see the types of the properties involved, but the basic idea is to do all the slow awaits BEFORE doing new UserSettingsView....
Something like this:
public class UserSettingsData
{
SomeType1 Languages;
SomeType2 USStates;
SomeType3 UserSettings;
}
...
// Slow await calls.
var data = await UserSettingsView.PrepAsync(UserId, AccessToken);
// Now create and display the view.
await Navigation.PushModalAsync(new UserSettingsView(data));
...
public static async UserSettingsData PrepAsync(SomeType4 UserId, SomeType5 AccessToken)
{
var data = new UserSettingsData();
data.Languages = await _accountService.GetSettingsAsync(...);
data.USStates = await ...;
data.UserSettings = await ...;
}
public UserSettingsView(UserSettingsData data)
{
...
// NOT AN ASYNC METHOD, so happens immediately, before page is shown.
Load(data);
}
// NOT AN ASYNC METHOD, so happens immediately.
private void Load(UserSettingsData data)
{
Languages = data.Languages;
USStates = data.USStates;
var userSettings = data.UserSettings;
...
// if still need DisplayAlert
Dispatcher.InvokeOnMainThread(async () =>
await DisplayAlert...
);
}
Replace "SomeType" etc with your actual types.

How can i fetch datas positioned in list and send it to another api's query parameter?

i need to fetch a string data from an api (this data located in a list) and i need to send this data to another api as a query parameter. I dunno how to send this as query parameter because this data positioned in a list.
For a better understating : in this api there is a key named steamid i need to fetch this steam id each time and send those as a parameter to this api
class GDCubit extends Cubit<GDState> {
GDCubit({
required this.steamService,
required this.steamReviews,
}) : super(GDInitial()) {
emit(GDInitial());
}
final SteamService steamService;
final SteamReviews steamReviews;
late final steamdata;
late final steamreview;
late final player;
late String appId = '2208920';
late String userId = '76561198078971744';
late String? id = steamReviews.reviews![0].author?.steamid; // I tried to send first users steam id but cannot initialize
void getDatas() async {
try {
emit(GDLoading());
steamdata = await steamService.fetchRelatedAppWithId(appId);
steamreview = await steamService.fetchSteamReviewsRelatedAppId(appId);
player = await steamService.fetchPlayerInfo(id);
//player = await steamService.fetchPlayerInfo(userId); //works properly but manually
emit(GDLoaded(steamdata, steamreview, player));
} catch (e) {
return print('${e.toString()}' 'Error');
}
}
}
`
I tried to send steamid of first user in list but cannot initialize it
Are you trying to initialize the variable id before steamReviews, try creating the id inside your getDatas method, like this:
class GDCubit extends Cubit<GDState> {
GDCubit({
required this.steamService,
required this.steamReviews,
}) : super(GDInitial()) {
emit(GDInitial());
}
final SteamService steamService;
final SteamReviews steamReviews;
late final steamdata;
late final steamreview;
late final player;
late String appId = '2208920';
late String userId = '76561198078971744';
void getDatas() async {
try {
emit(GDLoading());
steamdata = await steamService.fetchRelatedAppWithId(appId);
steamreview = await steamService.fetchSteamReviewsRelatedAppId(appId);
final id = steamReviews.reviews![0].author?.steamid; // Create id here
player = await steamService.fetchPlayerInfo(id);
emit(GDLoaded(steamdata, steamreview, player));
} catch (e) {
return print('${e.toString()}' 'Error');
}
}
}

Discord JS - forEach looped embed

I'm quite new to Javascript, normally a Python person. I've looked at some other answers but my embed does not add the fields as expected. The embed itself is sent.
My Discord bot follows the guide provided by the devs (primary file, slash commands, command files). I am trying to loop through the entries in an SQLite query and add them as fields.
My command file is below.
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js')
const sqlite = require('sqlite3').verbose();
module.exports = {
data: new SlashCommandBuilder()
.setName('rank')
.setDescription('Rank all points.'),
async execute(interaction) {
const rankEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Rank Board')
let db = new sqlite.Database('./databases/ranktest.db', sqlite.OPEN_READWRITE);
let queryall = 'SELECT name, points FROM pointstable ORDER BY points DESC'
db.all(queryall, [], (err, rows) => {
if (err) {
console.log('There was an error');
} else {
rows.forEach((row) => {
console.log(row.name, row.points)
rankEmbed.addField('\u200b', `${row.name}: ${row.points}`, true);
});
}
})
return interaction.reply({embeds: [ rankEmbed ] });
}
}
I would also like to convert row.name - held as Discord IDs - to usernames i.e. MYNAME#0001. How do I do this by interaction? I was able to obtain the User ID in another command by using interaction.member.id, but in this case I need to grab them from the guild. In Python I did this with await client.fetch_user but in this case the error await is only valid in async functions and the top level bodies of modules is thrown.
Thanks.
OK I've solved the first aspect, I had the return interaction.reply in the wrong place.
Relevant snippet:
rows.forEach((row) => {
console.log(row.name, row.points)
rankEmbed.addField('\u200b', `${row.name}: ${row.points}`, false);
})
return interaction.reply({embeds: [rankEmbed ]} );
Would still appreciate an answer to the converting row.name (user ID) to user name via fetch.
I've solved the second aspect also. Add the below into the loop.
rows.forEach((row) => {
let client = interaction.client
const uname = client.users.cache.get(row.name);
rankEmbed.addField('\u200b', `${uname}: ${row.points}`, false);

AngularJS file upload, Express and node-postgres (pg)

Got a component in AngularJS (porting soon to Angular 7) for updating a user profile that invokes an AngularJS service method to perform a PUT to /api/user/:id.
Want to add a small photo (<100K) to send in the same PUT with the other fields then handle the request like this in the controller...
// route: PUT /api/user/:id
import db from '../../utils/db';
export async function upsert(req, res) {
const { id, name, phone, email, photo } = req.body;
// users.photo in PostgreSQL has datatype of bytea
const sql = `UPDATE users SET name = $2, phone = $3, email = $4, photo = $5) WHERE id = $1 RETURNING id, name, phone, email, photo;`;
const { rows } = db.query(sql, [id, name, phone, email, photo];
return res.status(200).send(rows);
}
Is there a clean way to encode the image client-side so it can be included in the JSON the AngularJS service PUTs? Other solutions I found seem like overkill for this use-case - requiring the image upload to be handled very differently from the other fields.
Ended up biting the bullet - creating a separate table for files along with its own API using formidable and node-postgres. In case this helps anyone else, here's how it turned out.
PostgreSQL data definition...
-- DROP SEQUENCE public.files_seq;
CREATE SEQUENCE IF NOT EXISTS public.files_seq;
-- DROP TABLE public.files;
CREATE TABLE IF NOT EXISTS public.files (
_id integer PRIMARY KEY DEFAULT nextval('files_seq'::regclass),
name character varying(512) NOT NULL,
type character varying(20) NOT NULL,
data bytea
);
-- DROP INDEX public.users_first_name;
CREATE INDEX files_name ON public.files USING btree (name);
Controller for Express...
import stream from 'stream';
import fs from 'fs';
import { IncomingForm } from 'formidable';
import db from '../../utils/db';
// Returns list of images
export async function index(req, res) {
const { rows } = await db.query('SELECT _id, name, type FROM files ORDER BY name;', []);
return res.send(rows);
}
// Uploads a single file
export async function upload(req, res) {
let _id;
new IncomingForm().parse(req, (err, fields, files) => {
if(err) throw err;
if(Array.isArray(files)) throw new Error('Only one file can be uploaded at a time');
const { name, type, path } = files.file;
fs.readFile(path, 'hex', async(err, fileData) => {
if(err) throw err;
fileData = `\\x${fileData}`;
const sql = 'INSERT INTO files (name, type, data) VALUES($1, $2, $3) RETURNING _id;';
const { rows } = await db.query(sql, [name, type, fileData]);
_id = rows[0]._id;
res.send({ id: _id });
// console.log(`Uploaded ${name} to ${path} and inserted into database (ID = ${_id})`);
// No need to delete the file uploaded as Heroku has an ephemeral file system
});
});
}
// Downloads a file by its _id
export async function download(req, res) {
const _id = req.params.id;
const sql = 'SELECT _id, name, type, data FROM files WHERE _id = $1;';
const { rows } = await db.query(sql, [_id]);
const file = rows[0];
const fileContents = Buffer.from(file.data, 'base64');
const readStream = new stream.PassThrough();
readStream.end(fileContents);
res.set('Content-disposition', `attachment; filename=${file.name}`);
res.set('Content-Type', file.type);
readStream.pipe(res);
return rows[0];
}
// Deletes a file from the database (admin-only)
export async function destroy(req, res) {
const _id = req.params.id;
const sql = 'DELETE FROM files WHERE _id = $1;';
await db.query(sql, [_id]);
res.status(204).send({ message: `File ${_id} deleted.`});
}
On the client side, I'm using ng-file-upload with AngularJS.
Here's the relevant part of the view (in pug for brevity)...
.form-group.col-md-6
label(for='photo') Teacher photo
input.form-control(ngf-select='$ctrl.uploadPhoto($file)', type='file', id='photo', name='photo', ng-model='$ctrl.user.photo', ngf-pattern="'image/*'", ngf-accept="'image/*'", ngf-max-size='100KB', ngf-min-height='276', ngf-max-height='276', ngf-min-width='236', ngf-max-width='236', ngf-resize='{width: 236, height: 276}', ngf-model-invalid='errorFile')
ng-messages.help-block.has-error(for='form.photo.$error', ng-show='form.photo.$dirty || form.$submitted', role='alert')
ng-message(when='maxSize') Please select a photo that is less than 100K.
ng-message(when='minHeight,maxHeight,minWidth,maxWidth') The image must be 236 x 276 pixels.
span(ng-if='$ctrl.user.imageId')
img(ng-src='/api/file/{{ $ctrl.user.imageId }}' alt="Photo of Teacher")
and method in its controller...
uploadPhoto(file) {
if(file) {
this.uploadService.upload({
url: '/api/file/upload',
data: { file }
})
.then(response => {
this.user.imageId = response.data.id;
}, response => {
if(response.status > 0) console.log(`${response.status}: ${response.data}`);
}, evt => {
// Math.min is to fix IE which reports 200% sometimes
this.uploadProgress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total, 10));
});
}
}

mongoose update array and add new element

I pretty sure this question was asked many items, however I cannot find an answer to my particular problem, which seems very but I just can't seem to get it working. I have a user model with cart schema array embedded in it. I am trying to add an object to an array and if it exists only update quantity and price, if it is doesn't add to an array. what happens with my code is that it adds a new item when array is empty, it updates the item's quantity and price but it doesn't want to add a new item. I read a bit a bout and as far as I understood I cannot use two different db methods in one request. I would appreciate any help on this, this is the first time I am actually using mongooose.
const CartItem = require('../models/cartModel');
const User = require('../models/userModel');
exports.addToCart = (req, res) => {
const cartItem = new CartItem.model(req.body);
const user = new User.model();
User.model
.findById(req.params.id)
.exec((err, docs) => {
if (err) res.sendStatus(404);
let cart = docs.cart;
if (cart.length == 0) {
docs.cart.push(cartItem);
}
let cart = docs.cart;
let isInCart = cart.filter((item) => {
console.log(item._id, req.body._id);
if (item._id == req.body._id) {
item.quantity += req.body.quantity;
item.price += req.body.price;
return true;
}
});
if (isInCart) {
console.log(cart.length)
} else {
cart.push(cartItem);
console.log(false);
}
docs.save(function (err, docs) {
if (err) return (err);
res.json(docs);
});
});
};
I actually managed to get it working like this
exports.addToCart = (req, res) => {
const cartItem = new Cart.model(req.body);
const user = new User.model();
User.model
.findById(req.params.id)
.exec((err, docs) => {
if (err) res.sendStatus(404);
let cart = docs.cart;
let isInCart = cart.some((item) => {
console.log(item._id, req.body._id);
if (item._id == req.body._id) {
item.quantity += req.body.quantity;
item.price += req.body.price;
return true;
}
});
if (!isInCart) {
console.log(cart.length)
cart.push(cartItem);
}
if (cart.length == 0) {
cart.push(cartItem);
}
docs.save(function (err, docs) {
if (err) return (err);
res.json(docs);
});
});
};
don't know if this is the right way to do it, but I can both add a new product into my array and update values of existing ones
Maybe your problem hava a simpler solution: check this page at the mongoose documentation: there is a compatibility issue with some versions of mongoDB and mongoose, maybe you need to edit your model code to look like this:
const mongoose = require("mongoose");
const CartSchema = new mongoose.Schema({
//your code here
}, { usePushEach: true });
module.exports = mongoose.model("Cart", CartSchema);
You can find more information here: https://github.com/Automattic/mongoose/issues/5924
Hope it helps.

Resources