Error with pre populated SQLite file: "Can't find variable: projectDB".

Hi, I’m new in React Native and I wanna connect a prepopulated SQLite database and make a insert with a register form, and when I run my app in the Android Emulator appears that in the following image happens, my app can’t find my .db file. (The error in Android Studio and the file locations):

Other solutions on Internet haven’t worked for me and I don’t understand what I’m doing wrong

Part of my code (without the form):

//Registro.js
import * as React from 'react';

import { useState } from 'react';

import { Text,View, TextInput, ScrollView, StyleSheet, SafeAreaView, Pressable, TouchableOpacity, TouchableHighlight, Alert} from 'react-native';

import Icon from 'react-native-vector-icons/FontAwesome';

import { Ionicons } from '@expo/vector-icons';

import Modal from 'react-native-modal';

// import { Asset } from 'expo-asset';

// import * as FileSystem from 'expo-file-system';

//import { SQLite } from 'expo';

import * as SQLite from 'expo-sqlite';

//Database conexion

const db = SQLite.openDatabase({name: ProjectDB.db, createFromLocation: 1});

//**HERE** I call my db like just as a tutorial would suggest to me
//I tried to do something with Asset, FileSystem and Async and it didn't work for me.

Please, help me, I don’t understand what I may need in my code. Thanks :frowning:

Hey @santiagomilliongloba, please thoroughly follow the steps detailed here and if you still are encountering issues, please create a public github repo that we can clone and run locally on our end to test your code.

Cheers,
Adam

1 Like

Hi @santiagomilliongloba

What Adam says is correct, but the error you are getting actually has nothing to do with SQLite :slight_smile:

Your code is referencing ProjectDB.db in the SQLite.openDatabase() call, but ProjectDB is not defined anywhere.

Your tutorial should show you how/where to define ProjectDB before you call SQLite.openDatabase({ name: ProjectDB.db, ... }).

1 Like

Hi Adamjnav, that was the first page I visited when I tried to do the project with SQLite, but I think at that point I had not fully understood. I don’t understand much the transaction, I don’t understan the async function and I don’t speak much english :frowning:

I create an repository in github here GitHub - santiagoglobal/project_register: CRUD Expo React Native
Now my problem is that I can’t insert in my database* (table “usuario” (user in spanish))
Thanks for your answer

Hi wodin, I did not know, I thought that it was an expo or sqlite problem, I don’t understand much this tutorial. GitHub - santiagoglobal/project_register: CRUD Expo React Native this is my project
I don’t know how/where define ProjectDB.db in my project :frowning:
Thanks for your answer

Oh, I had another look at your screenshot and I see you have a file called ProjectDB.db

In that case that should be a string. Like:

SQLite.openDatabase({ name: "ProjectDB.db", ... })

i.e. there should be quotation marks around it.

There may be other problems, but that is the immediate problem.

1 Like

Hi, thanks for your correction, now I have this; const db = SQLite.openDatabase({ name: “ProjectDB.db”, createFromLocation : 1}), but this don’t save. My code:


const db = SQLite.openDatabase({ name: "ProjectDB.db", createFromLocation : 1})

state = {

    visibleModal: null,

    item: null,

  };

  state = {nro_cedula: ''}
  state = {nombre: ''}
  state = {apellidos: ''}
  state = {alias: ''}
  state = {correo: ''}
  state = {celular: ''}
  state = {op_envio: ''}
  state = {op_nombre: ''}
  state = {passwd: ''}
  state = {passwd2: ''}
  state = {acordado: ''}
  state = {nacionalidadID: ''}
  state = {verificado: ''}
  state = {ip: ''}
  state = {cft: ''}
  state = {fecha_sistema: ''}
  state = {eliminado: ''}
  state = {foto_perfil: ''}
  state = {nro_verificador: ''} 


  handleSave() {
    const {nro_cedula} = this.state;
    const {nombre} = this.state;
    const {apellidos} = this.state;
    const {alias} = this.state;
    const {correo} = this.state;
    const {celular} = this.state;
    const {op_envio} = this.state;
    const {op_nombre} = this.state;
    const {passwd} = this.state;
    const {passwd2} = this.state;
    const {acordado} = this.state;
    const {nacionalidadID} = this.state;
    const {verificado} = this.state;
    const {ip} = this.state;
    const {cft} = this.state;
    const {fecha_sistema} = this.state;
    const {eliminado} = this.state;
    const {foto_perfil} = this.state;
    const {nro_verificador} = this.state;

    if(acordado != "" && passwd2 != "" && passwd != "" && op_nombre != "" && op_envio != "" && celular != "" && correo != "" && apellidos != "" && nro_cedula != "" && nombre != ""){

      this.insert(nro_cedula, nombre, apellidos, alias, op_nombre, nacionalidadID, foto_perfil, correo, celular, op_envio, passwd, passwd2, cft, acordado, nro_verificador, verificado, ip, fecha_sistema, eliminado);

      Alert.alert("Alert","User's dates readies for be saved"); 
//ONLY GETS HERE

    }else{

      Alert.alert("Alerta","Not valid user date's"); 

    }

  }


  insert(nro_cedula, nombre, apellidos, alias, op_nombre, nacionalidadID, foto_perfil, correo, celular, op_envio, passwd, passwd2, cft, acordado, nro_verificador, verificado, ip, fecha_sistema, eliminado){

    var query = "INSERT INTO usuario (nro_cedula, nombre, apellidos, alias, op_nombre, nacionalidadID, foto_perfil, correo, celular, op_envio, passwd, passwd2, cft, acordado, nro_verificador, verificado, ip, fecha_sistema, eliminado) VALUES (null, ?, ?, ?, ?, null, null, null, ?, ?, null, ?, ?, null, null, null, null, null, null, '0')";

var params = [nro_cedula, nombre, apellidos, alias, op_nombre, nacionalidadID, foto_perfil, correo, celular, op_envio, passwd, passwd2, cft, acordado, nro_verificador, verificado, ip, fecha_sistema, eliminado];

    db.transaction((tx) => {

      tx.executeSql(query, params, (tx, results) =>

      {
        console.log(results);
        Alert.alert("Congratulations","Finally saved in table USER"); 
// MUST BE SHOW THIS MESSAG

      }, function (tx, err) {

        Alert.alert("Alert","Not saved in table USER"); 

        return;

      });

    });

  }

In the tutorial SQLite - Expo Documentation

async function openDatabase(pathToDatabaseFile: string): Promise<SQLite.WebSQLDatabase> {
  if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + 'SQLite')).exists) {
    await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + 'SQLite');
  }
  await FileSystem.downloadAsync(
    Asset.fromModule(require(pathToDatabaseFile)).uri,
    FileSystem.documentDirectory + 'SQLite/myDatabaseName.db'
  );
  return SQLite.openDatabase('myDatabaseName.db');
}

I never understood where to put this code, type annotation can only be used in typescript files. Where do I make the typescript document and where do I put it? I don’t understand very much English and I don’t understand this tutorial, I’m very confused

Hi

Your code has basic JavaScript problems, unrelated to Expo, that you will need to fix too. e.g.:

The above code is equivalent to writing just:

  state = {fecha_sistema: ''}

All of the earlier assignments are irrelevant because they are superseded by the later ones.

Btw, here’s an example TODO app in case you haven’t seen it before:

What are you trying to accomplish? e.g. are you planning to start with a blank database that the app can insert things into? Or are you planning to start with a database that already has stuff in it when the user installs the app? What about when the app is upgraded? What about other devices that also have a copy of the app installed? Are they supposed to see the same data? It would help if you could explain what you’re trying to do.

1 Like

The app registers users and they can log in, that’s phase one, basically a CRUD. Yes, I planning to start with a database that already has stuff in it when the user installs the app, that database is pre populated, the idea is to insert users into the users table and in this exist, for example, the foreign key “nacionalidad” (nationality, with all countries and denonyms).
It’s an app that will be connected to a server at sometime, in which a user will be register, when the app is updated they would’nt have to lose the data from the database, only certain containt but not the user accounts.
I uploaded part of the app to github: GitHub - santiagoglobal/project_register: CRUD Expo React Native

Thanks for the material and your help, I’m going to try it. :smiley:

I’m junior programmer and it’s my first time creating a mobile app, I’m learning from scratch and I started learning Ionic but it didn’t work for me, and that’s how I got to know React and Expo. (Sorry if my english reads strange, I’m not native in english language)

It’s not clear to me how this ties in with SQLite on the device. It sounds like you’re distinguishing between the user who installs the app on their phone, and other users who make use of the app on the first user’s device?

Also, if user A installs the app on device 1 and user B installs the app on device 2, then user Z gets added to the database on device 1, should they somehow also be in the database on device 2? Or are the devices completely separate? What about in future when the apps are connected to a server?

OK, so this implies you would need to somehow merge a new database with the one already on the device when the app is upgraded.

I only had a very quick look.

You should generally not add node_modules to git. It can get huge and there should be no need to do that. Your dependencies in package.json along with your npm or yarn lock files should be enough to recreate node_modules, so storing node_modules in git is redundant. If you create a new project with expo init, it will come with a default .gitignore file which tells git to ignore node_modules amongst other things.

You have both package-lock.json and yarn.lock. You should only have one or the other. If you use npm to manage your dependencies it creates/updates package-lock.json. If instead you use yarn to manage your dependencies it creates/updates yarn.lock. Choose one and delete the other lock file.

Have a look at Prettier which can format your JavaScript code. e.g. you can configure your editor to automatically format the code when you save a file.

Using "\n" is kind of weird :slight_smile::

        <View style={{flex: 1, backgroundColor: 'black'}}>
        <Text>{"\n"}</Text>
        </View>
1 Like

@wodin You seem like you know your way around.

I have a SQLite databases I want to add the my React-Native App. I do not want to download the databases through a remote URI, but basically install them with the App. Further, I need to able to replace them when the App is updated. How to access the FileSystem is well explained here. But I wonder …

… in which folder in my React Native project do I have to put the database files?

… is the folder different if I want to be able to replace (not merge) the database on update?

… if there are there differences on Android and iOS?

… if I have to change something in xCode or in some Android specific file for the App to be able to access the database?

I am struggeling with this. There is no information on where to put the files within the React-Native App, only how to access them… Any help or direction is highly appreciated.

1 Like

Yes, Distinguishing between the user who installs the app on their phone, I was redesigning and I think I will make a backend app and an app frontend conected with my DB, because exist users (clients that install and use the app, and admins) and in this moment I only develop the frontend.

Maybe there is a better option than SQLite, I tried with firebase but I did not like it, and I do not know another option for React Native, it is what has appeared to me on youtube.

User A install app in device 1, User B install app in device 2, User C install app in device, etc…, User A and User B can insert their user dates in table User. Admin 1 and Admin 2 can see a list of users and their user dates in a backend app. Is only one database.
About node_modules, I upload this because I wanna share this in snack, although when I tried to share it through that page it did not work, snack gave me an error.

I did not know about yarn.lock and package-lock, they were self-generated when creating the app. THANKS

The “\n” was for separate some gifs that I had there, before uploading the code, this app that I uploaded to github is a copy of the app I’m making, but without many details, more clean, but in this project surplus. :slight_smile:

Thanks for your answers. :smiley:

Hi stophfacee.

In the future I need my database to be on a server, while I was trying to use it within the app.

I don’t know where to put the database files, in a tutorial it appeared that I had to place the file .db in a SQLite folder.

I chose react-native because I read that it works for both, I need to make the app for both iOS and Android.

I don’t know, I am learning react-native since very recently, I have never programmed for cell phones, I must investigate what an xcode is.

This is my app: GitHub - santiagoglobal/project_register: CRUD Expo React Native
In home you go to user’s register form in the button “Registrate”, I need that this form can insert an user in the database.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.