I am making a demo project to change color of a simple TextView using Firebase Remote Config. But the function mRemoteConfig.fetch(cacheExpiration) .addOnCompleteListener... does not trigger at all. The text color does not change.
Here is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
initRemoteConfig();
}
private void initRemoteConfig() {
mRemoteConfig = FirebaseRemoteConfig.getInstance();
HashMap<String, Object> defaults = new HashMap<>();
defaults.put("color_primary", getString(R.string.color_primary));
mRemoteConfig.setDefaults(defaults);
FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(true)
.build();
mRemoteConfig.setConfigSettings(remoteConfigSettings);
fetchRemoteConfigValues();
}
private void fetchRemoteConfigValues() {
long cacheExpiration = 3600;
//expire the cache immediately for development mode.
if (mRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
cacheExpiration = 0;
}
mRemoteConfig.fetch(cacheExpiration)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// task successful. Activate the fetched data
mRemoteConfig.activateFetched();
setupView();
} else {
//task failed
}
}
});
}
private void setupView() {
setTextColor();
}
private void setTextColor() {
boolean isPromoOn = true;
int color = isPromoOn ? Color.parseColor(mRemoteConfig.getString("color_primary")) :
ContextCompat.getColor(this, R.color.color_primary);
text.setTextColor(color);
}
Am I missing something ? Thanks for help :)
If you have set Firebase Console correctly, I suggest you check whether the newest Google Play Services is available on your phone and work.
Related
I am working on an application which allows a user to register their details, log in with them then fill out a questionnaire, these details will also be saved for later use. Current I have successfully got my user's details on the registration page to save however whenever they fill out the questionnaire their registration details are being overwritten with their answers on the questionnaire. Included below is the code for my questionnaire page.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faqquestions);
setupUIViews();
fAuth =FirebaseAuth.getInstance();
submitfaq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
sendScoreData();
Toast.makeText(faqquestions.this, "Successfully completed", Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(faqquestions.this, Results.class));
} else {
Toast.makeText(faqquestions.this, "Submission failed", Toast.LENGTH_LONG).show();
}
}
});
}
private void setupUIViews() {
question1 = (EditText)findViewById(R.id.question1);
question2 = (EditText)findViewById(R.id.question2);
question3 = (EditText)findViewById(R.id.question3);
question4 = (EditText)findViewById(R.id.question4);
question5 = (EditText)findViewById(R.id.question5);
question6 = (EditText)findViewById(R.id.question6);
question7 = (EditText)findViewById(R.id.question7);
question8 = (EditText)findViewById(R.id.question8);
question9 = (EditText)findViewById(R.id.question9);
question10 = (EditText)findViewById(R.id.question10);
submitfaq = (Button)findViewById(R.id.submitfaq);
}
private Boolean validate() {
boolean result = false;
questionOne = question1.getText().toString();
questionTwo = question2.getText().toString();
questionThree = question3.getText().toString();
questionFour = question4.getText().toString();
questionFive = question5.getText().toString();
questionSix = question6.getText().toString();
questionSeven = question7.getText().toString();
questionEight = question8.getText().toString();
questionNine = question9.getText().toString();
questionTen = question10.getText().toString();
if(questionOne.isEmpty() || questionTwo.isEmpty() || questionThree.isEmpty() || questionFour.isEmpty() || questionFive.isEmpty() || questionSix.isEmpty()|| questionSeven.isEmpty() || questionEight.isEmpty() || questionNine.isEmpty() || questionTen.isEmpty()) {
Toast.makeText(faqquestions.this, "Please enter in all feilds", Toast.LENGTH_LONG).show();
} else {
result = true;
}
return result;
}
private void sendScoreData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reff = firebaseDatabase.getReference(fAuth.getUid());
faqinputs FAQinputs = new faqinputs(questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix, questionSeven, questionEight, questionNine, questionTen);
reff.setValue(FAQinputs);
}
If you want to update existing data at a location in the database, then you should use updateChildren() which accepts a Map of specific child/value pairs to change at that location.
I was following a tutorial online on how to create an android chat app with Xamarin that was implemented in Visual Studio 2015 and I was using Visual Studio 2017. I also tried to InitializeApp to see if that would fix it, but it did not work. What could be the problem? There was a couple of changes that I implemented, but I have one problem. I am getting an error "Java.Lang.IllegalStateException: " on line FirebaseDatabase.Instance.GetReference("chats").AddValueEventListener(this);
This is how I implented the OnCreate method:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
FirebaseApp.InitializeApp(this);
firebase = new FirebaseClient(FirebaseURL);
//firebase = new FirebaseClient(GetString(Resource.String.firebase_url)); //not working
FirebaseDatabase.Instance.GetReference("chats").AddValueEventListener(this);
fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
edtChat = FindViewById<EditText>(Resource.Id.input);
lstChat = FindViewById<ListView>(Resource.Id.list_of_messages);
fab.Click += delegate
{
PostMessage();
};
if (FirebaseAuth.Instance.CurrentUser == null)
{
StartActivityForResult(new Android.Content.Intent(this, typeof(Signin)), MyResultCode);
}
else
{
Toast.MakeText(this, "Welcome " + FirebaseAuth.Instance.CurrentUser.Email, ToastLength.Short).Show();
DisplayChatMessage();
}
}
private async void PostMessage()
{
var items = await firebase.Child("chats").PostAsync(new MessageContent(FirebaseAuth.Instance.CurrentUser.Email, edtChat.Text));
edtChat.Text = "";
}
public void OnCancelled(DatabaseError error)
{
}
public void OnDataChange(DataSnapshot snapshot)
{
DisplayChatMessage();
}
private async void DisplayChatMessage()
{
lstMessage.Clear();
var items = await firebase.Child("chats")
.OnceAsync<MessageContent>();
foreach (var item in items)
lstMessage.Add(item.Object);
ListViewAdapter adapter = new ListViewAdapter(this, lstMessage);
lstChat.Adapter = adapter;
}
I developed an application to my school and one of the features is principal's updates. For this, I'm using the Firebase realtime database. I need that the app will send automatically notification(background) when a new child(message) is added.
this is my read code(swift):
var messages = [Message]()
override func viewDidLoad() {
super.viewDidLoad()
observeMessages()
}
func observeMessages() {
let dbRef = FIRDatabase.database().reference().child("messageS")
dbRef.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let text = Message()
text.setValuesForKeys(dictionary)
self.messages.insert(text, at: 0)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}, withCancel: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId")
let message = messages[indexPath.row]
cell.textLabel?.text = message.title
cell.textLabel?.textAlignment = .center
cell.detailTextLabel?.text = message.message
cell.detailTextLabel?.textAlignment = .right
// Configure the cell...
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = messages[indexPath.row]
let title = message.title
let msg = message.message
let controller = UIAlertController(title: title, message: msg, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "סגור", style: .cancel) { (handler) in
// Any action when you cancel
}
controller.addAction(cancelAction)
self.present(controller, animated: true, completion: nil)
}
this is my write code(swift):
#IBOutlet weak var MessageTitle: UITextField!
#IBOutlet weak var MessageText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func post() {
let title: String = MessageTitle.text!
let message: String = MessageText.text!
let post: [String: AnyObject] = ["title": title as AnyObject,
"message": message as AnyObject]
let dbRef = FIRDatabase.database().reference()
dbRef.child("messageS").childByAutoId().setValue(post)
}
#IBAction func Publish(_ sender: AnyObject) {
post()
let MessageSent = UIAlertController(title: "נשלח", message: "ההודעה נשלחה בהצלחה", preferredStyle: UIAlertControllerStyle.alert)
MessageSent.addAction(UIAlertAction(title: "תודה", style: UIAlertActionStyle.default, handler: nil))
self.present(MessageSent, animated: true, completion: nil)
}
this is my read code(android):
private Firebase mRef;
public ArrayList<String> messages = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_updates);
mRef = new Firebase("https://ksharet-d6a24.firebaseio.com");
mRef.child("messageS");
// Get ListView object from xml
final ListView listView = (ListView) findViewById(R.id.ListView);
// Create a new Adapter
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, messages);
// Assign adapter to ListView
listView.setAdapter(adapter);
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Message message = postSnapshot.getValue(Message.class);
messages.add(0, message.getTitle() + '\n' + message.getMessage());
}
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
this is my write code(android):
private Button sendData;
private Firebase mRef;
private EditText messageBox = (EditText) findViewById(R.id.MessageText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_publish);
Firebase.setAndroidContext(this);
mRef = new Firebase("https://ksharet-d6a24.firebaseio.com/");
mRef.child("message");
sendData = (Button) findViewById(R.id.sendMessage);
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = messageBox.getText().toString();
//Firebase mRefChild = mRef.child("message");
//mRefChild.setValue(message);
mRef.push().setValue(message);
}
});
}
what should I create or change in the code(if you can, for both iOS and Android).
I recently purchased the Apple Developer Program membership and It'll probably be activated soon.
thanks for the helpers.
so, after a lot of time that I've been searching for solutions, I found a really easy way to do it, and it is by using cloud kit. that's the brian advent's tutorial:
https://youtu.be/BXl5o5_2aEU
I suggest you to go to his first video: https://youtu.be/XQ3nLV2778U and just do few of those things.
EDIT: 2017
Now we can use Firebase cloud functions in order to send a push notification when the database changes.
I tried implementing a signIn method from the OneDrive API, but I am not sure I correctly understood the workflow.
Basically, on first launch of the app, I want to have both the login window and the "authorise the app to..." window". But then, when the user launches the app again, I would like to be directly connected to the app, without any window.
Instead, with the following code, I keep having the second window (where the user decides to accept the app)
#Override
public void signIn() {
//personal code
linkingStarted = true;
signInStatus = SignInStatus.SIGNING_IN;
activity.setUpWait(R.layout.popup_waitgif_white);
//end of personal code
mAuthClient = AuthClientFactory.getAuthClient(activity.getApplication());
if (mAuthClient.getSession().isExpired() && Util.isConnectedToInternet(activity)) {
activity.alertOnUIThread("Login again");
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mAuthClient.login(activity, SCOPES, mAuthListener);
}
});
} else if (!Util.isConnectedToInternet(activity)) {
activity.alertOnUIThread(activity.getString(R.string.alert_verifyconnection));
} else {
activity.alertOnUIThread("Resigned In OneDrive");
signInStatus = SignInStatus.SIGNED_IN;
mAuthClient.initialize(SCOPES, new AuthListener() {
#Override
public void onAuthComplete(final AuthStatus status, final AuthSession session, final Object userState) {
if (status == AuthStatus.CONNECTED) {
authToken = session.getAccessToken();
oneDriveService = getOneDriveService();
signInStatus = SignInStatus.SIGNED_IN;
} else {
authenticationFailure();
Log.v(TAG, "Problem connecting");
}
}
#Override
public void onAuthError(final AuthException exception, final Object userState) {
//mAuthClient.login(activity, SCOPES, mAuthListener);
}
}, null, authToken);
}
}
and the AuthClientFactory is just this:
public class AuthClientFactory {
private static AuthClient authClient;
private static final String CLIENT_ID = "00000000XXXXX";
public static AuthClient getAuthClient(Context context) {
if (authClient == null)
authClient = new AuthClient(context, OneDriveOAuthConfig.getInstance(), CLIENT_ID);
return authClient;
}
}
You would have an easier time with the OneDrive SDK for Android, as authentication is a much simpler process.
final MSAAuthenticator msaAuthenticator = new MSAAuthenticator() {
#Override
public String getClientId() {
return "<msa-client-id>";
}
#Override
public String[] getScopes() {
return new String[] { "onedrive.appfolder", "wl.offline_access"};
}
}
final IClientConfig oneDriveConfig = new DefaultClientConfig.createWithAuthenticator(msaAuthenticator);
final IOneDriveClient oneDriveClient = new OneDriveClient
.Builder()
.fromConfig(oneDriveConfig)
.loginAndBuildClient(getActivity());
That will take care of the user authentication flow and then give you a service object that makes interacting with OneDrive straight-forward. See the full example application.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I having some issue in creating a dialog of type group in quickblox chat service on android. I am able to get all the user from the server side of quickblox, able to build dialog and adding those users i got in it but when it comes to call groupChatManager.createDialog(dialog, new QBEntityCallbackImpl(). I am getting a null pointer exception on that. I found later that i have to initialise chatService in class that extends application i did that but still same error. here is my code
enter code here
My applicationSingeltonClass
public class ApplicationSingleton extends Application
{
private QBUser currentUser;
//quickBlox
private static final String APP_ID = "key";
private static final String AUTH_KEY = "authkey";
private static final String AUTH_SECRET = "authsec";
private static ApplicationSingleton instance;
private Map<Integer, QBUser> dialogsUsers = new HashMap<Integer, QBUser>();
private QBRoomChat currentRoom;
#Override
public void onCreate()
{
super.onCreate();
initApplication();
initImageLoader(getApplicationContext());
}
public static ApplicationSingleton getInstance()
{
return instance;
}
private void initImageLoader(Context context)
{
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.enableLogging() // Not necessary in common
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
public QBUser getCurrentUser()
{
return currentUser;
}
public void setCurrentUser(QBUser currentUser)
{
this.currentUser = currentUser;
}
public Map<Integer, QBUser> getDialogsUsers()
{
return dialogsUsers;
}
public void setDialogsUsers(List<QBUser> setUsers)
{
dialogsUsers.clear();
for (QBUser user : setUsers)
{
dialogsUsers.put(user.getId(), user);
}
}
public void addDialogsUsers(List<QBUser> newUsers)
{
for (QBUser user : newUsers)
{
dialogsUsers.put(user.getId(), user);
}
}
public Integer getOpponentIDForPrivateDialog(QBDialog dialog)
{
Integer opponentID = -1;
for(Integer userID : dialog.getOccupants())
{
if(userID != getCurrentUser().getId())
{
opponentID = userID;
break;
}
}
return opponentID;
}
private void initApplication()
{
instance = this;
QBChatService.setDebugEnabled(true);
QBSettings.getInstance().fastConfigInit(APP_ID, AUTH_KEY,AUTH_SECRET);
}
}
here is my other class were i create a dialog
enter code here
protected void onPostExecute(final Boolean success)
{
if(status.equals("accepted"))
{
pagedRequestBuilder.setPage(1);
pagedRequestBuilder.setPerPage(10);
final ArrayList<String> usersLogins = new ArrayList<String>();
usersLogins.add(userID);
usersLogins.add(herocivID);
final ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
occupantIdsList.add(civID);
occupantIdsList.add(heroCivID);
QBUsers.getUsersByFacebookId(usersLogins, pagedRequestBuilder, new QBEntityCallbackImpl<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> users, Bundle params)
{
if (!QBChatService.isInitialized())
{
QBChatService.init(getApplicationContext());
chatService = QBChatService.getInstance();
chatService.addConnectionListener(chatConnectionListener);
}
QBDialog dialog = new QBDialog();
dialog.setName("chat with mostafa wo may");
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);
QBGroupChatManager groupChatManager = chatService.getInstance().getGroupChatManager();
groupChatManager.createDialog(dialog, new QBEntityCallbackImpl<QBDialog>()
{
#Override
public void onSuccess(QBDialog dialog, Bundle args)
{
Log.i("", "dialog: " + dialog);
}
#Override
public void onError(List<String> errors) {
Toast.makeText(getBaseContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onError(List<String> errors)
{
Toast.makeText(getBaseContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(getBaseContext(), "you accepted the request", Toast.LENGTH_SHORT).show();
}
else if(status.equals("rejected"))
{
Toast.makeText(getBaseContext(), "you rejected the request", Toast.LENGTH_SHORT).show();
}
}
i need to know were exactly i have to configure the chat service to prevent the null pointer while creating a dialog.
Any help would be appreciated thank you.
You're right,
chatService.getInstance().getGroupChatManager();
is null if you're not logged in ti Chat
so you have to login to chat first and then call this method
I managed to solve this issue.
First you need to check roomChatManager if its equal to null you have to ask the user to login in.
Second in the login wether your using social provider or by mail you have to login to chatService ( ApplicationSingleton.getInstance().chatService.login(userResult);)
ApplicationSingleton is a java class were it extends Application in it you initialise the ChatService.
Thats it now you can create your dialog successfully.