I am using Firebase realtime database in my android app. My entries in table is around 300. I'm not able to get the data from the Firebase in Datasnapshot. Sometimes it works after loading 20 minutes. How can I access my data & response fast. It's working well & very fast in iOS with same database & same queries.
private void checkBookingInfo() throws Exception {
mDatabaseReference.child(FireBaseConstants.BOOKING_INFO_TABLE).limitToFirst(10).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
countArrival = 0;
countDeparture = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
//check arrivals date matches with today's date then increment counter
if (snapshot.hasChild(FireBaseConstants.ARRIVAL_DATE)) {
String currentDate = Utils.getCurrentDate();
String arrivalDate = snapshot.child(FireBaseConstants.ARRIVAL_DATE).getValue().toString();
String status = snapshot.child(FireBaseConstants.STATUS).getValue().toString();
if (currentDate.equalsIgnoreCase(arrivalDate) && !status.equalsIgnoreCase("Cancel")) {
countArrival++;
}
}
//check departure date matches with today's date then increment counter
if (snapshot.hasChild(FireBaseConstants.DEPARTURE_DATE)) {
String currentDate = Utils.getCurrentDate();
String departureDate = snapshot.child(FireBaseConstants.DEPARTURE_DATE).getValue().toString();
String status = snapshot.child(FireBaseConstants.STATUS).getValue().toString();
if (currentDate.equalsIgnoreCase(departureDate) && !status.equalsIgnoreCase("Cancel")) {
countDeparture++;
}
}
}
setValueInEditText();
} else {
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("notme", "");
}
});
}
To improve performance of the Firebase query you can add index on the field by which you are ordering Your query. Like
{
"rules": {
"YOUR_NODE": {
".indexOn": ["FIELD1", "FIELD2"]
}
}
}
You can find the helping link here
Firebase also says here
Important: The onDataChange() method is called every time data is
changed at the specified database reference, including changes to
children. To limit the size of your snapshots, attach only at the
highest level needed for watching changes. For example, attaching a
listener to the root of your database is not recommended.
But even if the index is not applied still 20 minutes is much time, you need to check your source code there could be some other issue in the UI, may be data is coming but not populating in the UI.
how to get the proper way or ShortCut or fastest way retrieving data of particular child from the firebase
baseRef.Child ("wordRun").Child("Players").Child(userid).Child("GameRun").Child("usercount").GetValueAsync ();
I try like something:-
example 1
var getTask =baseRef.Child ("wordRun").Child("Players").Child(userid).Child("GameRun").Child("usercount").GetValueAsync ();
yield return new WaitUntil(() => getTask.IsCompleted || getTask.IsFaulted);
if (getTask.IsCompleted) {
Debug.Log(getTask.Result.Value.ToString());
}
example 2:-
baseRef.Child("wordRun").Child("Players").Child(userid).Child("GameRun").Child("usercount").GetValueAsync .ContinueWith(task => {
if (task.IsFaulted) {
// Handle the error...
}
else if (task.IsCompleted) {
DataSnapshot snapshot = task.Result;
foreach ( DataSnapshot user in snapshot.Children){
IDictionary dictUser = (IDictionary)user.Value;
Debug.Log ("" + dictUser["usercount"]);
}
}
});
I want to get values write a single line in firebase database if anyone knew how got value in a single line in firebase then please give answer thank you for reading...
And Please Give me a way to get all data back in a class by getting GetRawJsonValue
you need to getting by the loop
foreach (var childSnapshot in args.Children) {
Debug.Log("ChildSnapshot"+childSnapshot..GetRawJsonValue());
}
and if you have any Class which have same data format then you try this
ClassName ClassObjectName = JsonUtility.FromJson<ClassName>(args.Snapshot.GetRawJsonValue());
Currently I am adding my user class to a firebase database using this code:
public void onClick(View v)
{
Firebase ref = new Firebase("https://xxxxxx.firebaseio.com/");
createAccount(emailString, passwordString);
User user = new User ();
user.setEmail(emailString);
user.setPassword(passwordString);
ref.child("users").push().setValue(user);
}
Right now, since I use the .push() method, I am creating a unique ID in my database. How do I pull that unique ID? I looked at this tutorial but I don't understand how to implement it.
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); //get the reference to your database
User user = new User ();
user.setEmail(emailString);
user.setPassword(passwordString);
String yourKey = dbRef.child("users").push().getKey(); //get the key
dbRef.child("users").child(yourKey).setValue(user); //insert user in that node
But if you want to access that node (yourKey) later, you will need to store it in some sort of permanent storage like a database on your web server.
Great example of how to get key check these docs out helped me a lot.
Firebase Docs
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
I have this simple application that I'm currently writing as practice. Its purpose is to allow the user to send a quote and the author of that quote on a server (in this case a Parse.com backend I have registered) and then show those quotes to other users of the app randomly. So by opening the app, you get a random comment that someone has posted.
The way I'm trying to accomplish this is:
On start-up, the app connects to the Parse.com backend and downloads all the currently available quotes (I call those Inanity objects because the quotes are supposedly enlightened but should actually be stupid and nonsensical - anyway, doesn't matter). This is the code:
query.findInBackground(new FindCallback<ParseObject>() {
SQLi sqlite = new SQLi(MainActivity.this);
SQLiteDatabase dbz = sqlite.getWritableDatabase();
#Override
public void done(List<ParseObject> list, ParseException e) {
//sqlite.dbDelete();
if (e == null) {
int size = list.size();
for (int i = 0; i < size; i++) {
ParseObject object = list.get(i);
String author = object.get("author").toString();
String content = object.get("content").toString();
Inanity inan = new Inanity(content, author, 1);
Log.d("FOR LOOP" + i, inan.toString());
sqlite.insertInanity(dbz, inan);
}
}
}
});
Pretty simple. (dbz is an SQLiteDatabase acquired by calling getWritableDatabase(), by the way). The code below is the code for the SQLiteOpenHelper insertInanity() method that I use to put the retrieved data from the server in the local SQLite database:
public void insertInanity(SQLiteDatabase db, Inanity inanity) {
ContentValues values = new ContentValues();
values.put(CONTENT_INANITIES, inanity.getContent());
values.put(AUTHOR_INANITIES, inanity.getAuthor());
values.put(UPVOTE_INANITIES, inanity.getUpvotes());
db.insert(TABLE_INANITIES, null, values);
}
I pass an SQLiteDatabase object to the method simply to avoid having to call getWriteableDatabase() - I had some trouble with recurring calls if I kept doing that.
After writing the server data on the local SQLite database, the user is taken to an Activity that starts showing the quotes and the author of the quotes in a couple of TextViews. This is the code the retrieves a quote/author object from the SQLite database:
public Inanity retrieveInanity(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_INANITIES, new String[] {
CONTENT_INANITIES, AUTHOR_INANITIES, UPVOTE_INANITIES },
ID_INANITIES + " = " + id, null, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
return new Inanity("a", "b", 1);
}
else {
cursor.moveToFirst();
String contentL = cursor.getString(cursor
.getColumnIndex(CONTENT_INANITIES));
String authorL = cursor.getString(cursor
.getColumnIndex(AUTHOR_INANITIES));
int upvotesL = cursor.getInt(cursor
.getColumnIndex(UPVOTE_INANITIES));
Inanity inanity = new Inanity(contentL, authorL, upvotesL);
return inanity;
}
}
Finally, the quote to be displayed is randomly selected from the locally stored results thusly ("a" is an int variable declared earlier by the way)
final SQLi sql = new SQLi(this);
a = sql.getRowCount() + 1;
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Random rand = new Random();
int e = rand.nextInt(a);
if (e != 0) {
Inanity inanity = sql.retrieveInanity(e);
String content = inanity.getContent();
String author = inanity.getAuthor();
ImageView imageView = (ImageView) findViewById(R.id.downloaded);
TextView contentView = (TextView) findViewById(R.id.content);
TextView authorView = (TextView) findViewById(R.id.author);
Picasso.with(ShowActivity.this)
.load("http://img1.etsystatic.com/000/0/5356113/il_fullxfull.314192275.jpg")
.into(imageView);
contentView.setAlpha(0.9f);
authorView.setAlpha(0.9f);
Animation alpha = new AlphaAnimation(0.1f, 1.0f);
alpha.setDuration(2000);
contentView.setText(content);
authorView.setText(author);
contentView.startAnimation(alpha);
authorView.startAnimation(alpha);
}
else {
Toast.makeText(ShowActivity.this,
"Cursor trouble in wonderland!", Toast.LENGTH_LONG)
.show();
}
}
});
}
The getRowCount() method of the SQLi class is this:
public int getRowCount() {
int count = 1;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_INANITIES, null);
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
count = cursor.getCount();
}
return count;
}
For the most part. this works great. So, what's the problem, I hear you ask? Well, since I want to refresh the quotes every time the application starts up and get fresh ones from the server, the way I'm trying to accomplish that is by deleting the contents of the Inanity table of the database and re-populate them on start-up. So, I have created this method in the SQLi database helper class that's called dbDelete() which I call right at the start of the done() method of the FindCallback class of the Parse.com library (although I have commented this out from this code, it works swimmingly: it deletes the contents of the database just fine). Unfortunately, when I do that, it appears that the local SQLite database is not repopulated on app startup for some infernal reason, so I keep getting the placeholder "a", "b" and 1 values that are returned when the retrieveInanity() method cannot find cursor contents. Here is the dbDelete() method, which is quite simple:
public void dbDelete() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_INANITIES, null, null);
}
I have been trying to solve this for quite some time and it's driving me crazy. I understand that the question is pretty convoluted, big and that it doesn't contain any catchy NullPointerExceptions/logcat action but any help would be appreciated. I must be missing something obvious related to the SQLite database use but I simply can't figure it out.
I wrote a similar app (one that made calls to a remote database and updated the info on local db). You should try using db.insertOrThrow. You will need to wrap the method in a Try...Catch statement. It will try to insert rows, and will throw an exception when a row already exists. You can then ignore the errors by leaving the Catch part blank. This will avoid the deletion and rebuild of the table.
try {
db.insertOrThrow(TABLE_INANITIES, null, values);
} catch SQLException s {
\\do nothing, as we don't care about existing rows
}
If you set up the quote server to have unique identifiers for the quote, then the local copy, your SQLite DB, will not insert duplicate entries. For example, your quote DB table on the server would look something like this
ID | Quote | Author
1 | blah | J. smith
Where the column ID is set as the unique identifier (or unique key). When your app calls the server and queries the remote DB, your local DB has only records that don't exist added to it.
You also want to make sure, I believe, that you update your cursor adapter in onResume().
i trying to insert my string into my database tables ,but it doesnt appear, so any advice on this how do i string my text so it able to appear on android database table
btnplayer = (Button) findViewById(R.id.button1);
tw1 = (TextView)findViewById(R.id.PX2);
btnplayer.setOnClickListener(new View.OnClickListener() {
SharedPreferences myPrefs = getSharedPreferences("PREF_COUNT", 0);
SharedPreferences.Editor myEditor = myPrefs.edit();
public void onClick(View v) {
String Player = myPrefs.getString("tw1",name);
DataStorage.this.btnplayer.setText("add name [" + Player + "]");
myEditor.putString("Player", Player);
myEditor.commit();
Please make your question more clear.
If you want store your data in database in android, you can go for SQLite database available in android http://developer.android.com/training/basics/data-storage/databases.html
but I suggest use sharedpreferences if only strings need to store.
I didn't get the meaning behind this statement String Player = myPrefs.getString("tw1",name); if you already have stored the same value (first time there will be no value so you will getting back the default "name" and then you will again store that name with the new key called "Player"). Where are you storing "tw1"? Exactly what issue you are facing?