i have an android app which need to post data on firebase. It work perfectly when i test it with my development device.
when i publish it on store and my friend want to post data on same firebase account --- it not work --- no error message -- no crash --- just no data on server.
I need to ask that free plan of firebase works in such scenario with published app on Google store ? or i need to upgrade it with paid plan.
My code is below:
Firebase ref = new Firebase(my_URL);
String uniqueID = UUID.randomUUID().toString();
String date = Utility.getDateTime();
Firebase jobchild = ref.child(projectId);
jobchild.setValue(uniqueID);
Firebase jimages = jobchild.child("ProjectId");
jimages.setValue(projectId);
Firebase jdate = jobchild.child("LogDate");
jdate.setValue(date);
When I put your code into an Android app, it works fine for me:
Firebase.setAndroidContext(this);
Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/32319324");
// Ensure we start out with no data at this location
ref.removeValue();
// Monitor the location and output any data there to a text view
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
TextView output = (TextView) Activity32319324.this.findViewById(R.id.content_32319324);
for (DataSnapshot project: snapshot.getChildren()) {
output.setText(
"key="+project.getKey() + "\n" +
"LogDate="+project.child("LogDate").getValue() + "\n" +
"ProjectId="+project.child("ProjectId").getValue()+"\n\n"
);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) { }
});
// Write data to the location
String projectId = "42";
String uniqueID = UUID.randomUUID().toString();
String date = new Date().toString(); //Utility.getDateTime();
Firebase jobchild = ref.child(projectId);
jobchild.setValue(uniqueID);
Firebase jimages = jobchild.child("ProjectId");
jimages.setValue(projectId);
Firebase jdate = jobchild.child("LogDate");
jdate.setValue(date);
See the app here: https://github.com/puf/firebase-stackoverflow-android (your code is in Activity32319324)
Related
i'm working on Login and register activity using Firebase that requires me to strore data in realtime database. I setup the firebase realtime database location in South East Asia, and this is the supposed URL: https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/
and this is my code on writing Users data on the DB, after succesfully creating user using .createUserWithEmailAndPassword(email, password) ==>>
myRef = FirebaseDatabase.getInstance().getReference("Users");
String currUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
User user = new User(username, "default");
myRef.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
} else{
}
}
});
After debugging, i found that the process fails at myRef.setValue(user) because the URL set up for database reference is https://chatapp-5e8ce-default-rtdb.firebaseio.com/Users instead of https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/Users.
How do i set the URL so it match my firebase database location?
You can pass the URL to FirebaseDatabase.getInstance(), so:
myRef = FirebaseDatabase.getInstance("https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app").getReference("Users");
You can also download an updated google-services.json, which will contain the correct string and replace the existing (incompletely) file in your Android Studio project with that.
I am trying to create a very simple login with Facebook using firebase and android studio. My login with Facebook works and I was able to run the app and sign in but none of my info has been stored in firebase (I want to have the persons name, email, etc.) I know it's something small I am probably missing but I cannot figure it out and I have tried so many things. Also I checked and all my gradle files are up to date and my firebase is set up correctly so it has nothing to do with that. plz help.
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuthListner = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
// what do i put here to pull out the fb users info into firebase?!
goMainScreen();
}
}
};
I have tried:
if(user != null){
String name = user.getDisplayName();
String email = user.getEmail();
String uid = user.getUid();
I have tried:
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
I know it is probably a dumb mistake because I am new to firebase and android studio but any advice will help. Thank you
Are your user stored into the firebase console? (https://console.firebase.google.com)
If it is not stored in your project, it will not return anything when you call the getDisplayName(), getUser(), etc.
If they are stored, please post the complete code that you are using to do the login.
I am trying to build a chat application using firebase.
The structure for message table :
message -
$message_id
- $message_push_id
- message {
sender : 3,
receiver : 58,
token : token_of_sender,
message : hi
....}
message_id here is generated using the sender and receiver ids "3_58"
I am using push to save messages into firebase.
{
"rules": {
".read": true,
"message":
{
"$messageid": {
"$messagepushid":
{
".read": true,
".write": "auth != null && !data.exists()",
".indexOn": ["token", "userid", "receiverid", "sent_time"],
".validate": "auth.token == newData.child('token').val() && newData.hasChildren(['token', 'userid', 'receiverid', 'text'])"
}
}
}
}
}
I have already generated token using custom token generator :
Firebase firebase = getFirebase();
Map<String, Object> authPayload = new HashMap<String, Object>();
authPayload.put("uid", user.getUserid());
authPayload.put("token", user.getToken());
TokenGenerator tokenGenerator = new TokenGenerator(Constants.FIREBASE_KEY);
TokenOptions tokenOptions = new TokenOptions();
tokenOptions.setAdmin(false);
final String firebaseToken = tokenGenerator.createToken(authPayload, tokenOptions);
firebase.authWithCustomToken(firebaseToken, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
Log.d("Auth", "Success : " + authData.toString());
Log.d("Auth", "Token : " + firebaseToken);
SharedPrefs.setFirebaseUserToken(getActivity(), firebaseToken);
}
#Override
public void onAuthenticationError(FirebaseError
firebaseError) {
firebaseError.toException().printStackTrace();
}
});
I am trying to push a new message but I am getting error :
RepoOperation﹕ setValue at /message/3_58/-Jy2We4cqLjuQNF6Oyhs failed: FirebaseError: Permission denied
I am unable to figure out where I am going wrong.
This is the code to send chat :
mConversationReferenceFireBase = mFireBase.child("message").child(mConversationId);
Chat conversation = new Chat( mToken, mUserId, mReceiverId, message );
mConversationReferenceFireBase.push().setValue(conversation, new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
if (firebaseError != null) {
Log.e("Conversation", firebaseError.toString());
}
}
});
mConversationId = 3_58
The token here is generated for a user. We have a separate server to maintain the user accounts. The token is being used to upload/ download any files, the firebase is used as Chat Server.
With the rules set to .read = true and .write = true; everything works, however when I am attempting to have an authentication performed, it results in the error mentioned above. I've tried using the token from token generator, to check if I may possibly be using the wrong token.
I am following this example to generate token for firebase auth :
https://www.firebase.com/docs/web/guide/login/custom.html
Since storing a firebase secret key is bad in terms of security, what other alternative can be followed to generate a token for authentication?
I was too stuck on this point and here's what helped me.
First things first, there are two types of users who can access database from firebase
Authorized
Non-authorized
By default it is set to non-authorized but then they do not have any permissions neither read nor write, so initially if you try to perform any operation you get the permission denied error.
So basically one has to change the required permissions on the firebase console in-order to access the database.
Complete answer here
Check the rule defined in your firebase account and also the simulator options. Description is given below in a image.
I have a very weird situation. I have an application where I am implementing a "Notification History".
I have a separate application that sends push notifications to targeted channels and then creates an entry into a table called Notifications, saving the channel that was targeted and the message that was sent.
channels = channelEditText.getText().toString();
message = messageEditText.getText().toString();
ParsePush push = new ParsePush();
push.setChannel(channels);
push.setMessage(message);
push.sendInBackground();
channelEditText.setText("");
messageEditText.setText("");
ParseObject notifications = new ParseObject("Notifications");
notifications.add("channels", channels);
notifications.put("msg", message);
notifications.saveInBackground();
My Android app's "Notification History" fragment then performs
ParseQueryAdapter<ParseObject> notificationAdapter =
new ParseQueryAdapter<ParseObject>(getActivity(), new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
ParseQuery query = new ParseQuery("Notifications");
query.whereContainedIn("channels", ParseInstallation.getCurrentInstallation().getList("channels"));
query.orderByDescending("createdAt");
return query;
}
});
notificationAdapter.setTextKey("msg");
ListView notificationListView = (ListView) rootView.findViewById(R.id.notificationListView);
notificationListView.setAdapter(notificationAdapter);
My ParseApplication.java subscribes a user to channel: "Welcome" on installation so I don't receive a null pointer. The Notifications Table entry with channel "Welcome" populates the listview.
I have two ways to subscribe to a channel. One way is on the device itself like this
final EditText syncInput = (EditText) rootView.findViewById(R.id.syncInput);
Button syncButton = (Button) rootView.findViewById(R.id.syncButton);
syncButton.setOnClickListener(new OnClickListener() {
public void onClick(View v){
String sync = null;
sync = syncInput.getText().toString();
PushService.subscribe(getActivity(), sync, DashboardActivity.class);
syncInput.setText("");
}
});
The other way is through CloudCode
Parse.Cloud.define("subscribeToChannel", function(request, response){
var channelName = request.params.channel;
var userId = request.params.userId;
if(!channelName) {
response.error("Missing parameter: channel");
return;
}
if (!userId) {
response.error("Missing paremeter: userId");
return;
}
//Create a Pointer to the user based on their object id
var user = new Parse.User();
user.id = userId;
Parse.Cloud.useMasterKey();
// A user might have more than one installation
var query = new Parse.Query(Parse.Installation);
query.equalTo("user", user); //Match Installations with a pointer to this User
query.find({
success: function(installations) {
for (var i = 0; i < installations.length; i++) {
//Add the channel to al the installations for this user
installations[i].addUnique("channels", channelName);
}
//Save all the installations
Parse.Object.saveAll(installations, {
success: function(installations) {
//All the installations where saved.
response.success("All the installations were updated with this channel.");
},
error: function(error) {
//An error occured while saving one of the objects.
console.error(error);
response.error("An error occured while updating this user's installations.");
}
});
},
error: function(error) {
console.error(error);
response.error("An error occurred while looking up this user's installations");
}
});
});
Both ways of subscribing are successful in that a Push notification sent to the target channel reaches the device. Here is the issue... If I use the device to subscribe my query will show the messages sent to that channel that is saved in the Notifications table. If I use the CloudCode my query does NOT show the message sent to the channel that is saved in the Notification table.
I'm stumped. Any help is deeply appreciated.
--------------------------------SOLUTION-------------------------------------------------
protected void onResume() {
super.onResume();
ParseInstallation.getCurrentInstallation().refreshInBackground(new RefreshCallback(){
#Override
public void done(ParseObject parseObject, ParseException e) {
List<String> channels = ParseInstallation.getCurrentInstallation().getList("channels");
for (int i = 0; i < channels.size(); i++) {
Log.w("TEST", channels.get(i));
}
}
});
}
You're editing the Installation record on the server-side in Cloud Code, but the device isn't getting the updated data. If this is a common behavior in your app, refresh the installation object when you load the app:
ParseInstallation.getCurrentInstallation().refreshInBackground();
or fetchInBackground, as shown here: https://parse.com/docs/android_guide#objects-retrieving
This could also be solved by, instead of querying from the device, calling a cloud function which does the query (with the updated channels list already on the server-side.)
Am trying to display the profile picture of users logged into my app through Google+ but am not sure how to do this.To get the image (and other information), google provides the code
#Override
public void onConnected() {
...
if (mPlusClient.getCurrentPerson() != null) {
Person currentPerson = mPlusClient.getCurrentPerson();
String personName = currentPerson.getDisplayName();
String personPhoto = currentPerson.getImage();
String personGooglePlusProfile = currentPerson.getUrl();
}
}
I am aware that ordinarily i would need to get any image i want to display from res/drawable... but i don't know what to do with the value of personPhoto (which somehow get's changed from type String to Image when you paste the code in Eclipse.
You need to use that URL to grab the photo as a bitmap and set it to an imageview.
Section 4.9 of this article explains how to make an asynctask that will do just that:
http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
First you need to add this dependency in your app/build.gradle file:
dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}
After this update your UI Accordingly :
private void updateUI(GoogleSignInAccount account) {
if (account != null){
text.setText("Sign in as :" +account.getDisplayName());
email.setText(account.getEmail());
String imgurl = account.getPhotoUrl().toString();
Glide.with(this).load(imgurl).into(profile);
sighIn.setVisibility(View.GONE);
sighOut.setVisibility(View.VISIBLE);
}
else {
text.setText("signOut");
sighIn.setVisibility(View.VISIBLE);
sighOut.setVisibility(View.GONE);
}
}
This is the solution that worked on my Android app. I developed it from an answer above by Naveen Kumar Yadav.
Prerequisites
- I am using a Google Sign-In API for my login.
- I have an XML Code with an ImageView that has an id "client_dp"
Add this dependency to your app-level build.gradle file
dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}
Then add this code to your activity java file
//Firebase get user info
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser account = firebaseAuth.getCurrentUser();
if (account != null){
//Display User Image from Google Account
//Objects.requireNonNull() prevents getPhotoUrl() from returning a NullPointerException
String personImage = Objects.requireNonNull(account.getPhotoUrl()).toString();
ImageView userImage = findViewById(R.id.client_dp);
Glide.with(this).load(personImage).into(userImage);
}
With new google sign in Options in Kotlin. Simply request for the parameters you need in your onCreate function
val gso =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString("your-client-id"))
.requestEmail()
.requestProfile()
.requestId()
.build()
When recieving back the response from google Sign in activity, inside the
Get user profile picture through:
val credential = GoogleAuthProvider.getCredential(account?.idToken, null)
val photoUrl = credential.photoUrl.toString()