Reading the results of SQLite SELECT query in Ionic2 v3.4 - android

So I'm using the most recent version of Ionic2 (v3.4) and I'm trying to get the ionic native SQLite to work. I've been able to create database file and put a table in it like so:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql(tableQuery, {})
.then(() => console.log("success"))
.catch(() => console.log("fail"));
})
Inserting works too. But when I try to get the result of a selection:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql("SELECT * FROM savedCoupons where itemId=" + itemId, {})
.then((db) => {console.log(JSON.stringify(db))})
.catch(() => console.log("***ERROR WITH SELECT***"));
})
.catch(() => console.log("ERROR: FAILED TO CREATE/OPEN DATABASE."));
I get lost because of the lack of documentation. JSON.stringify() is being run so it would seem the query worked. It returns {"rows":{"length":1}, "rowsAffected":0} and that's it. How do I access the result of the query?

Let you have three columns e.x id,name,lastname in your table.
after querying you can access it like:
db.executeSql('SELECT * FROM student WHERE id='+1, {})
.then(result => {
for (var i = 0; i < result.rows.length; i++) {
console.log("---Id---"+result.rows.item(i).id);
console.log("---Name---"+result.rows.item(i).name);
console.log("---Lastname---"+result.rows.item(i).lastname);
}
});

Related

Why is array empty when running Android Studio?

I am using react native and firebase realtime database to store and query a list of properties. It seems that when I run the below query in XCode for iOS the array created here shows a list of the property objects. However, when I run this android studio the array is empty. Do you know what may be causing this? Can someone please help here I am very new to react native and using firebase realtime database?
I really do apologies for the poor code formatting:
const array = []
await db.ref(`users/`).on(`value`, snapshot => {
if (snapshot.exists()) {
snapshot.forEach(function(userSnapshot){
if(userSnapshot.hasChild("properties")){
userSnapshot.child("properties").forEach((propertySnapshot) => {
array.push({
key: userSnapshot.key,
property: propertySnapshot.val(),
username: userSnapshot.val().username,
email: userSnapshot.val().email,
phoneNumber: (userSnapshot.val().phoneNumber != null)?userSnapshot.val().phoneNumber:null,
propertyName: propertySnapshot.key,
profile_pic: userSnapshot.val().profile_pic,
connectedAccount_id: (userSnapshot.val().connectedAccount_id != null)?userSnapshot.val().connectedAccount_id:null,
customer: (userSnapshot.val().customer != null)?userSnapshot.val().customer:null,
});
})
}
})
}
});
await database().ref(`users/${auth().currentUser.uid}/your_location`).once(`value`, function(snap){
....
Geocoder.init("******");
Geocoder.from(locationPostcode)
.then(json => {
var location = json.results[0].geometry.location;
global.latitude = location.lat;
global.longtitude = location.lng;
})
.catch(error => console.warn(error));
console.log("array result "+array)
.....
})
The log array shows an array of objects for iOS:
array result [object Object],[object Object],[object Object],[object Object],[object Object]
but for android it's empty:
array result

Unable to connect to SQLite in React-Native

I have pre-defined sqlite database using DB Browser for SQLite. I have place the db file in the path root/android/app/src/main/assets/www/mysqlite.db, unfortunately I'm unable to
connect. Below are my versioning.
Samsung Galaxy Android 11,
"react-native-sqlite-storage": "^6.0.1",
"react": "17.0.2",
"react-native": "0.65.1",
"#react-navigation/native": "^6.0.4",
My script(I make it simplified):
import SQLite from 'react-native-sqlite-storage';
SQLite.DEBUG(true);
SQLite.enablePromise(false);
export const AppSignIn = (props) => {
const OpenDB = () => {
return new Promise((resolve, reject) => {
global.db = SQLite.openDatabase(
{
name: 'mysqlite.db',
createFromLocation: '~mysqlite.db',
},
() => {
console.log("Connection success!");
},
error => {
console.log(error);
reject();
});
resolve();
});
}
const ReadDB = () => {
return new Promise((resolve) => {
global.db.transaction(function (tx) {
tx.executeSql(
// The rest of the trx
);
resolve();
});
});
}
async function ConnectDB() {
return new Promise(async (resolve, reject) => {
await OpenDB()
.then(async () => {
await ReadDB()
.then(() => {
console.log('YEAY FINALLY');
resolve();
})
})
.catch((error) => {
console.log(error);
reject();
});
});
}
React.useEffect(() => {
(async () => {
await ConnectDB()
.then()
.catch();
})();
}, []);
}
The log writes:
LOG OPEN database: mysqlite.db
LOG SQLite.open({"name":"mysqlite.db","createFromLocation":"~mysqlite.db","dblocation":"nosync","assetFilename":"~mysqlite.db"})
LOG new transaction is waiting for open operation
LOG Phone connected? true, Server connected? true
LOG OPEN database: mysqlite.db failed, aborting any pending transactions
LOG [Error: Could not open database]
I have tried several ways but I'm unable to connect to it.
Move from www to assets folder directly. Uninstall app on phone and run again.
Remove SQLite.enablePromise(false);
react-native link react-native-sqlite-storage
cd android && ./gradlew clean
Follow step to opendatabase call
Try moving your file for android from root/android/app/src/main/assets/www/mysqlite.db -> root/android/app/src/main/assets/mysqlite.db
I finally able to run it on Samsung Galaxy with Android 11. I've tried on Redmi6 with Android 9 and it can run.
I've removing react-native.config.js which contain SQLite
module.exports = {
dependencies: {
"react-native-sqlite-storage": {
platforms: {
android: {
sourceDir: "../node_modules/react-native-sqlite-storage/platforms/android-native",
packageImportPath: "import io.liteglue.SQLitePluginPackage;",
packageInstance: "new SQLitePluginPackage()"
}
}
}
}
};
I also remove the import module import io.liteglue.SQLitePluginPackage; in MainApplication.java and the database finally open.
I'm not sure if this way are absolute. I hope it was temporary as it oppose the way from the tutorial.

How do I use a prepopulated SQLite DB with Expo on Android?

I'm trying to use a prepopulated SQLite DB for my react native app. I'm using Expo and the downloadAsync() Function to load my DB from my assets folder. This works as expected on IOS, as I can load the DB and retrieve the data.
On Android however I just can't get this to work. The db file is there in the internal storage of my emulator, but every time I try to retrieve data, an error occurs since 'there is no such table'.
My guess is that SQLite doesn't properly search for my db but instead creates a new one, where my tables are obviously missing.
I've been trying for over 7 hours now, so I appreciate any kind of help.
Folder structure:
App.js
-assets
--db
---db.db
-src
--connection
---connectionClass
App.js
const App = () => {
const [dbLoaded, setDbLoaded] = useState(false);
if(!dbLoaded){
downloadDB().then((value) => setDbLoaded(value));
return <></>
} else {
return (
<Navigation/>
);
}
};
ConnectionClass.js
export const downloadDB = async () => {
await FileSystem.deleteAsync(`${FileSystem.documentDirectory}SQLite`, {idempotent : true});
await FileSystem.makeDirectoryAsync(`${FileSystem.documentDirectory}SQLite`, {intermediates: true });
return await FileSystem.downloadAsync(
Asset.fromModule(require('../../assets/db/WaKanji.db')).uri,
`${FileSystem.documentDirectory}SQLite/WaKanji.db`
).then(({status}) => {
if(status === 200){
return true
}
return false
}).catch(error => {
console.log('Err\n' + error);
return false;
});
};

How to get JSON.parser value after save to AsyncStorage using Json.stringfy in react native?

I want to use the data from JSON.stringify that I save locally from async storage, so I can manage them locally (like user data for login)
I already save it to AsyncStorage
componentDidMount = async () => {
fetch('My_url', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
saveData = async () => {
try {
await AsyncStorage.setItem('user', JSON.stringify(this.state.data));
Alert.alert('Saved', 'Successful');
} catch (error) {
Alert.alert('Error', 'There was an error.')
}
this is the JSON
0
username "admin2"
password "*****"
access "1"
name "dwi"
phone_number "087613721"
email "**#****.com"
score null
status "0"
1
username "admin3"
password "***"
access "1"
name "Satria"
phone_number "****"
email "*****3#*****.com"
score null
status "0"
and I try to get the value using this, but can't show anything in node console.log, it said "unidentified" (i just using press button on this)
displayData = async ()=>{
try{
let user = await AsyncStorage.getItem('user');
let parsed = JSON.parse(user);
console.log(parsed.email);
}
catch(error){
alert(error)
}
}
can some JSON parser output use like to be database function?
like for login so we can log in and check the data user from json.parser that I store in the data using async storage?
or output some data that we want to be used like in where statement in the SQL ?
The response of await AsyncStorage.getItem('user'); is an array like [key,value].
You need write parsed[0] to get key and JSON.parse(parsed[1]) to get json value.

How can I populate the reference Field using Firestore

Do you know how I can populate the reference Field on a Document using Firestore?
When you create / get a document reference, you can save this into another document. This example is for the Node SDK, but it should give you an idea of how to implement this for Android.
Creating a document reference
// Create the references
let myFirstDoc = db.collection('myCollection').doc();
let mySecondDoc = db.collection('otherCollection').doc();
let batch = db.batch();
// Save the two documents to the batch
batch.set(myFirstDoc, {someData: true});
batch.set(mySecondDoc, {firstDocRef: myFirstDoc});
// Commit the batch
return batch.commit()
.then(response => {
console.log('Data saved');
})
.catch(err => {
console.error(err);
});
Getting an existing reference
return db.collection('myCollection').doc('myDocId')
.then(documentSnapshot => {
let newDoc = db.collection('otherCollection').add({otherDoc: documentSnapshot.ref});
})
.then(response => {
console.log('Data saved');
})
.catch(err => {
console.error(err)
})

Categories

Resources