Insert json to mysql - android

I am looking for a way to insert JSON to SQLite.
I have a php script that looks like this.
<?php
require 'connection.php';
$var_fname = "Mildred";
$var_password = "ewan";
$var_email = "saf";
$var_username = "enanpogi";
$var_lastname = "Mildred";
$var_aviaryName = "Mildred";
$var_location = "myLocation";
$insert_stmt = $db->prepare(""
. "INSERT INTO users"
. "( fname, lname, email, password, username, aviary_name, location ) "
. "VALUES( :name, :lastname, :email, :password, :username, :aviaryName, :location)" );
// prepare and bind
$insert_stmt->execute(array(
':name' => $var_fname,
':lastname' => $var_lastname,
':password' => $var_password,
':email' => $var_email,
':username' => $var_username,
':aviaryName' => $var_aviaryName,
':location' => $var_location
));
$lastId = $db->lastInsertId();
if ($insert_stmt){
echo "inserted</br>";
echo $lastId;
//get all information of newly inserted and make json encode to prepare for insertion in sqlite_array_query
$stmt = $db->prepare('SELECT * '
. 'FROM users '
. 'WHERE id = :lastInsertedID ');
$stmt->bindParam(':lastInsertedID', $lastId);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if($results > 0 ){
//echo sizeof($results);
echo "</br>";
echo json_encode(array("user_data"=>$results) );
}
}
?>
when I run that script, I was able to get below result
{"user_data":{"id":"28","fname":"Mildred","lname":"Mildred","email":"saf","username":"enanpogi","aviary_name":"Mildred","password":"ewan","location":"myLocation","phonenumber":null,"active":null}}
I am not sure if it is JSON Object or JSON array..
Now, I need help to insert that JSON to SQLite in my Android JAVA app.

Visit This Link : Json Viewer
Paste Your Output as a Text in this Link.
Click on Viewer.
You can find out that you got the json response or not.
I check your result.it's in json format.You already got the json Object.
Now, Use json_encode($results) function gives you a string so you can easily insert it database.

You will get JSON Object. json_encode will give you json object. But You will get json array when you use json_decode with second argument true.

Related

Why i can't use String array parameter in Graphql query Android/kotlin

The query is :
query profile(
$fields: [String!]!
){
fetchProfile(
fields: $fields
){
data
}
}
and Query Variables is:
{"fields": ["Total","Safe","Eco"]}
When i try to Build , i get
Error: Variable `fields` of type `[String!]!` used in position expecting type `String!`
Footnote:
I am sure that in my fetchProfile has [String!]! field. In GraphQL playground, i can get data.

Android Java equivalent of PHP implode function

I've copied a snippet of a function I use in php to take an array and convert it into a sql where clause using the implode function. I would like to be able to repeat this function in Android Java code.
In other words pass a function a json array and have it do the equivalent of the implode function below to create the where clause in the query string. Does Java in Android have an "implode" equivalent or would anyone be able to help with an elegant solution to creating that where clause from a json array in Android Java? The json array would be of the form {"var1":"val1", "var2":"val2"}
// select from fact sighings - requires an array to do the where clause
public function select_from_fact_sighting($whereArray) {
$jsonArray = json_decode($whereArray, true);
$elementCount = count($jsonArray);
$where = array();
foreach($jsonArray as $row) {
foreach($row as $key => $val) {
$qval = $this -> quote($val);
$where[] = $key . " = " . $qval;
}
}
if (!empty($where))
$query = sprintf('SELECT * FROM fact_sightings WHERE %s', implode(' AND ', $where)');
Kotlin you convert your JSON objects into string list and pass like this to get the string form of the json with appended string
fun main(){
val arrayOrg = arrayOf("a","b","b","c","a","c","a")
println(arrayOrg.joinToString(" "))
}
//prints
a b b c a c a
in Java I guess this should work.
public static void main(String args[])
{
String gfg2 = String.join(" ", "select", "*", "from", "table", "where");
System.out.println(gfg2);
}

Query Data from Google Spreadsheet in Android

I am trying to query data form Google Spreadsheet available to be read by anyone with the Read Only link.
I implemented this Quickstart solution but here is what I need:
Access data just with URL, no authentication needed
Query item in column A and get value in column B
No need for updating any data
I tried constructing queries like:
http://spreadsheets.google.com/tq?tq=SELECT%20*%20WHERE%20A=C298732300456446&key=2aEqgR1CDJF5Luib-uTL0yKLuDjcTm0pOIZeCf9Sr0wAL0yK
But all I get is:
/*O_o*/
google.visualization.Query.setResponse(
{
"version": "0.6",
"reqId": "0",
"status": "error",
"errors": [
{
"reason": "invalid_query",
"message": "INVALID_QUERY",
"detailed_message": "Invalid query: NO_COLUMN: C298732300456446"
}
]
}
This comes when the data is actually present in the sheet in column A with value C298732300456446.
What can I do for getting the data, without any authentication from my spreadsheet?
I am not sure if this can be done. If fine, I can suggest an alternative solution. You can try writing a Google App script like:
function doGet(e) { return getInfo(e); }
function doPost(e) { return getInfo(e); }
function getInfo(request) {
var someValueFromUrl = request.parameter.value;
var requiredValue = "";
var sheet = SpreadsheetApp.openById("spreadsheet_id");
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
Logger.log("Reading row num: " + i);
if(data[i][0] == someValueFromUrl) {
requiredValue = data[i][1];
break;
}
}
Logger.log(requiredValue);
return ContentService.createTextOutput(JSON.stringify(requiredValue));
}
This way, you can publish this script as web app and call it using an URL which will be obtained when you publish this script.
Call the script like:
https://script.google.com/macros/s/obtained_url/exec?value=1234
If key is found, you will get the String response as:
"value"
I hope this helps.
C298732300456446 needs to be put within single quotes.
So you need to enclose C298732300456446 as %27C298732300456446%27
Your'e modified query would be
http://spreadsheets.google.com/tq?tq=SELECT%20*%20WHERE%20A=%27C298732300456446%27&key=2aEqgR1CDJF5Luib-uTL0yKLuDjcTm0pOIZeCf9Sr0wAL0yK
I'm unable to test this though - looks like you've removed/removed access from this spreadsheet.

Remove DataSnapshot From Firebase setValue()

My Firebase database storage format like this.
{
key=3553: 3223,
value={
-KZMFwmCYKevESD6qtjD={
text=Hello I am,
timestamp=[
.sv: timestamp
],
imageUrl=,
senderId=yDapbI755tOD72ivfsdferOv1RIHMnAe03
}
}
}
but at the time of set value to store in firebase database i am doing like this.
String Temp = "{timestamp: [.sv: timestamp], imageUrl: , senderId: " + Utils.SET_HEADER_ID + ", text: " + strMessage + "}";
System.out.println("===== Temp String : " + Temp);
String key = mFirebaseDatabaseReference.child("threads/3333:3333").push().getKey();
mFirebaseDatabaseReference.child("threads/3333:3333").child(key).setValue(Temp);
As I wrote above code I added a data in Firebase database. But it will automatically include DataSnapshot JsonObject at top my insert database format like this, which is wrong.
DataSnapshot{
key=3333: 3333,
value={
-KZPfTKJhaCC4RkIj45P={
timestamp: [
.sv: timestamp
],
imageUrl: ,
senderId: yDapbI755tOD72ivOv1RIHMnAe03,
text: hiiiiiiiii
}
}
}
How can I remove this DataSnapshot from insert format of Firebase?
You cannot pass a raw JSON value to Firebase. You'll instead have to build the data structure in your code:
Map<String,String> map = new HashMap<String,String>();
map.put("timestamp", Firebase.Database.ServerValue.TIMESTAMP);
map.put("imageUrl", "an actual image URL, which is missing from your question");
map.put("senderId", Utils.SET_HEADER_ID);
map.put("text", strMessage);
mFirebaseDatabaseReference.child("threads/3333:3333").child(key).setValue(map);
Alternatively you can use a library such as Jackson to convert the JSON intro the required nested map structure. See for example Nested Json to Map using Jackson.

How do I solved java.lang.String cannot converted to JSON object? [duplicate]

This question already has answers here:
JSONException: Value of type java.lang.String cannot be converted to JSONObject
(14 answers)
Closed 7 years ago.
I have lerant about android and MySQL, and I have view about this web:http://codeoncloud.blogspot.tw/2013/07/android-mysql-php-json-tutorial.html
but I don't know how to solve this problem:
enter image description here
<?php
$host="sql113.byethost14.com"; //replace with database hostname
$username=" xxx "; //replace with database username
$password=" xxx "; //replace with database password
$db_name="b14_16972597_food"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
You solve this by returning a valid JSON string.
You can use a service to check its validity:
http://jsonlint.com/
Your script should return JSON and only a JSON string nothing else.
To debug this in your app you should log the string and check it before even attempting to convert it JSON.

Categories

Resources