I want to be able to import a JSON file to Firebase with a button in my app. I know that you can add a JSON file manually in the Firebase Console, but in this case, I want to let my user import a JSON file with a button and update the info in Realtime Database. Can someone help me?
You would need first to convert the json to a map and then save it directly to the path you want:
val jsonMap = Gson().fromJson<Any>(stringJson, object : TypeToken<HashMap<String, Any>>() {}.type)
Firebase ref = new Firebase(YOUR_FIREBASE_PATH);
ref.setValue(jsonMap );
I want to be able to import a JSON file to Firebase manually
There is no API for doing that. If you want to let the user the possibility to add the content of a JSON file to the Realtime Database, then you should write some code for that. Meaning that you need to implement an option in which the user can upload the JSON file to the local storage, then in your app's code, you should read the file and get the data as JSON String. To convert it to a Map, you can simply use:
val jsonObj = JSONObject(jsonString)
val map = jsonObj.toMap()
Now, to write this Map object into the Realtime Database, in a location that corresponds only to a specific user, assuming that you are using Firebase Authentication, please use the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser?.uid
val rootRef = FirebaseDatabase.getInstance()
val uidRef = rootRef.child("users").child(uid)
uidRef.setValue(map).addOnCompleteListener(/* ... /*)
Related
I cannot get a key value from firebase storage while datas exist in storage.
key = intent.getStringExtra("key").toString()
and they return null
binding.writebtn.setOnClickListener {
val title = binding.titleArea.text.toString()
val contents = binding.contentArea.text.toString()
val uid = FBAuth.getUid()
val time = FBAuth.getTime()
val key = FBRef.boardRef.push().key.toString()
FBRef.boardRef
.child(key)
.setValue(BoardModel(uid, title, contents, time))
and this is my saving function.
and as u can see, all datas are saved properly. But still I cannot get a key value.
If you want to get data from any database you need to use any clinter (Retrofit) if you have this code please share otherwise check this thread. The GetStringExtra() you are currently using is for getting shared data between android core components and it has nothing to do with firebase database.
I'm trying to retrieve and store the values within this Map in my Firestore. The way I have my Firestore set up is like so:
I've found a way to retrieve other fields within my Firestore database but when trying to access map values like so:
horsepowerTextView.text = result.data?.getValue("Horsepower").toString()
it crashes the application and gives me an error saying that "Key Horsepower is missing in the map".
Can you please tell me how I would be able to get the values within Cars?
The following picture shows Firestore layout and code:
I've tried this link (how to read mapped data from firestore in kotlin) but when creating the map it only retrieves the topmost variable in the document NOT a part of the Map which would be the values firstName and lastName:
I actually answered that question, but your use case is totally different than the linked one. Why? Simply because "Cars" is an array of maps (custom objects). If you only want to get the value of the "Horsepower" field, then simply use the following lines of code:
val db = Firebase.firestore
val usersRef = db.collection("users")
usersRef.document("TwbJb27eFL3HAS1xLhP1").get().addOnCompleteListener {
if (it.isSuccessful) {
val data = it.result.data
data?.let {
val cars = data["Cars"] as List<*>
for (car in cars) {
val carMap = car as Map<*, *>
val horsepower = carMap["Horsepower"]
Log.d(TAG, "$horsepower")
}
}
}
}
The result in the logcat will be:
120
If you want however to map the "Cars" array into a list of custom objects, then I recommend reading the following resource:
How to map an array of objects from Cloud Firestore to a List of objects?
I'm working on Couchbase lite, and I want to prepare a pre built database from a json file.
Each time I import the file which has an array of 12 keys, that has 100 line, each line is a single array.
Cblite imports all the file into a single document, which won't allow me to use the content of the document based on the keys, because all the 12 keys are duplicated 100 times. But I found out that i can import the single file into several documents (each line/array) and become a separate document.
But i’m not able to do that with the commands provided in cblite, I got error from cblite including (Can't parse json)
DESTINATION : Database path, replication URL, or JSON file path:
*.cblite2 : Copies local database file, and assigns new UUID to target
*.cblite2 : With --replicate flag, runs local replication [EE]
ws://* : Networked replication
wss://* : Networked replication, with TLS
*.json : Imports/exports JSON file (one doc per line)
*/ : Imports/exports directory of JSON files (one per doc)
I can rearrange the file of json anyway that fits… but I can’t create a single file for each array.
The arrays look like that
{"_id":13,"id":"51333591918","owner":"126542062#N08","secret":"16f1758279","server":"65535","farm":66,"title":"dreamland","ispublic":1,"isfriend":0,"isfamily":0,"url_s":"https://live.staticflickr.com/65535/51333591918_16f1758279_m.jpg","height_s":148,"width_s":240}
{"_id":14,"id":"51333156717","owner":"97978797#N03","secret":"82f0fb71aa","server":"65535","farm":66,"title":"Tagpfauenauge","ispublic":1,"isfriend":0,"isfamily":0,"url_s":"https://live.staticflickr.com/65535/51333156717_82f0fb71aa_m.jpg","height_s":160,"width_s":240}
cblite -tool version: cblite tool 2.8 EE
Couchbase lite version : 2.8.6
Error: NullPointerException
I tried several files. one JSON which is public file ( i used it as a test also) is the flickr json response Flickr Photos Json File
also I used the files of the company which are items for POS.
i tried to change the structure of the json files manually even. but all leading to the same result... (putting all the arrays in a single document)
in the db query i used this code
val query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("owner"),
SelectResult.property("secret"),
SelectResult.property("server"),
SelectResult.property("farm"),
SelectResult.property("title"),
SelectResult.property("ispublic"),
SelectResult.property("isfriend"),
SelectResult.property("isfamily"),
SelectResult.property("url_s"),
SelectResult.property("height_s"),
SelectResult.property("width_s"),
)
.from(DataSource.database(database))
val result = query.execute().allResults()
for (rs in result) {
// val doc = database.getDocument(photo.id)
val id = rs.getString("id")
val owner = rs.getString("owner")
val secret = rs.getString("secret")
val server = rs.getString("server")
val farm = rs.getInt("farm")
val title = rs.getString("title")
val ispublic = rs.getInt("ispublic")
val isfriend = rs.getInt("isfriend")
val isfamily = rs.getInt("isfamily")
val url_s = rs.getString("url_s")
val height_s = rs.getInt("height_s")
val width_s = rs.getInt("width_s")
photoList.add(
photo(
id!!,
owner!!,
secret!!,
server!!,
farm,
title!!,
ispublic,
isfriend,
isfamily,
url_s!!,
height_s,
width_s
)
)
i noticed in Kotlin the option of SelectResult.all() doesn't bring anything, i have to specify the keys one by one to be fetched. but that is not an issue.
i often managed to print the whole document in the console, but i will never be able to use any key within. always getting the NullPointer as an error.
I'm still learning on couchbase and i looking to learn about N1QL, i rarely find something for Kotlin unfortunately
Any help?
Please see the example repo in GitHub:
https://github.com/biozal/cbmobile-split-data-example
I made the assumption that all records in the photo array that is a child object of the photos object is what you wanted to save to the database and that each object you wanted to be a new document.
Given this I wrote a very simple shell script (using "bash") that does the following:
get the count of how many items are in the document
loop through the number of items I need to create documents for
used the open source jq command (https://github.com/stedolan/jq) to get the content and save it into a variable named json
each document needs a unique key so I used the id field for this and pull it from the json
finally I call the cblite tool and have it create the document based on the id I pulled for the item and the json value of it
A screenshot of this query is provided named query-database.png. To query I did the following:
./cblite sampleDb.cblite2
query --limit 10 ["=", [".owner"], "138459774#N07"]
That query will return the document that the value is in.
I added a JSON to firebase realtime database and when I retrieved it it all goes smooth until I add a new element to the list through the app and it transforms it on a Hashmap.
How can I mantain it as a list.
override fun onDataChange(p0: DataSnapshot) {
val database = p0.getValue(ListOfGamesJavaModel::class.java)!!
val lastUpdate = database.date
}
This works fine before I add new elements to list
val newGameRef = database.child("gamesList")
newGameRef.child(System.currentTimeMillis().toString()).setValue(game)
database.child("date").setValue("23-08-2019 20:32")
After that when I run the code to retrieve the list I get this error.
com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap
Can you help me retrieve it as a List
Working
NOT WORKING
UPDATE
If I add it like this it works, but I'm trying to add a new one without knowing the list size.
val newGameRef = database.child("gamesList")
newGameRef.child(int.toString()).setValue(game)
database.child("date").setValue("23-08-2019 20:32")
The Firebase Realtime Database it always stores data as key-value pairs, with the keys being strings. In Java this translates to a Map<String,Object>. In some cases the Firebase clients are able to automatically convert the data to an array, which translates to List<Object> in your case. But in your second JSON screenshot, the client will not automatically convert the data to a List, so you'll have to do that yourself.
As Constantin commented, start by getting the Map<String, ...> from the database, and then get the list of values from that.
override fun onDataChange(p0: DataSnapshot) {
val map = p0.getValue(MapOfGamesJavaModel::class.java)!!
val database = map.values
val lastUpdate = database.date
}
The MapOfGamesJavaModel is a new class you'll have to create. Alternatively you can read Map<String, GamesJavaModel>, but you may have to do some casting with generic types in that case.
To learn more the way Firebase Realtime Database works with arrays, see Best Practices: Arrays in Firebase.
I am a newbie with firebase and trying to use this as the backend for an android app to store data. The format of the data is a key,value pair.
This is the code that I am using to store the data :
Map<Integer, PersonData> map = new HashMap<Integer, PersonData>();
map.put(PersonData.getID(), new PersonData("abcd", 12345));
Firebase ref = new Firebase(url).push();
ref.setValue(map);
Due to the push reference being used the data is getting stored like this :
-J5upSABqTLJ1Wfu-jFq
12345
id: 12345
name: abcd
Where-as I want the data to be store like this :
12345
id: 12345
name: abcd
I am not entirely sure if the code sample above is the right way to store data. Since I want to be able to update the existing data at a later point in time . Any suggestions ?
EDIT 1: I am thinking I need to use push so that I don't over-write the existing data in the firebase repo.
I have just tried to get the data back using the getValue() method and I can only fetch data which is in MAP
EDIT 2: without using a push() method with my reference I can see that the any previous data is getting overwritten and only the latest information is available. I am wondering if they is a better way to obtain the reference and still maintain the previous information
So it looks like you have your own system of unique ids, in which case you shouldn't need to use the .push method (that is just a helper to get a unique ref for new data). So instead of push you should be able to do:
Map<Integer, PersonData> map = new HashMap<Integer, PersonData>();
map.put(PersonData.getID(), new PersonData("abcd", 12345));
Firebase ref = new Firebase(url).child("12345");
ref.setValue(map);
Assuming your id is "12345" and url is pointing at the location where you want to store all of your persons.
To update the data without overwriting, your ref would be:
Firebase ref = new Firebase(url).child("12345");
And instead of using .setValue you would want to use ref.updateChildren(updates). You can see how to structure the updates from the example in the docs:
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("first", "Fred");
updates.put("last", "Swanson");
nameRef.updateChildren(updates);