I'm using Firebase for my Android app, I want read datas. In particular I want to select an user with a specific id. When I use the debugger it seems that the code doesn't execute the onDataChange() instruction.
private User readUserById(){
final User u = new User("","","");
Query query = mDatabaseReferences.child("users").orderByChild("id").equalTo(id);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
u.setId(ds.child("id").getValue(User.class).getId());
u.setNumber((ds.child("number").getValue(User.class).getNumber()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return u;
}
private void initFirebase() {
FirebaseApp.initializeApp(this);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReferences = mFirebaseDatabase.getReference();
}
public void sendCode(View v){
id= id.getText().toString();
readUserById();
phoneNumber = phoneText.getText().toString();
if (phoneNumber.equals("") || id.equals("")) {
Toast t = Toast.makeText(this, "Please insert a nickname and a valid phone number", Toast.LENGTH_LONG);
t.show();
} else {
setUpVerificationCallbacks();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
60,
TimeUnit.SECONDS,
this,
verificationCallbacks
);
}
// }
}
Using the debugger I've seen that the 'id' value is correct.
I used Firebase documentation for sendCode(), the user registration works correctly, just like the sms sending. I want to check if the nickname already exists, and the value is in the 'id' Textview. I call the sendCode() through a button.
I've tried in this way but doesn't work. Running with the debugger the result of user is null
private User readUserByName(){
final User[] user = {new User()};
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child(nick).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
user[0] = dataSnapshot.getValue(User.class);
Log.d("Tag", user[0].toString());
}
else
Log.e("Tag","No such user exists");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return user[0];
}
This is how I save the User
I've launched the app with the debugger
Assuming that users node is a direct child of your Firebase root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference testRef = rootRef.child("users").child("test");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = dataSnapshot.child("id").getValue(String.class);
String idName = dataSnapshot.child("idName").getValue(String.class);
String number = dataSnapshot.child("number").getValue(String.class);
Log.d("TAG", id + " / " + idName + " / " + number);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
testRef.addListenerForSingleValueEvent(eventListener);
The output will be:
test / f70eb... / number
Assumed that :
node "users" directly under root node.
You already know the id of the user and this id contains all the information under User.class
You only want to read a user, if exists in database.
All the getters and setter exists in User.class and a Public empty constructor exists
Here is how you should do it
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").ref(id).addListenerforSingleValueEvent(listener);
And in Listener's OnDataChange(DataSnapshot snap);
if(snap.exists()){
user = snap.getValue(User.class);
Log.d("Tag",user.toString());
}
else
Log.e("Tag","No such user exists");
Related
Apologies if my question my be so dumb but my programming skills are really limited and I'm on a hurry for a PoC.
I have the apex class below which was developed for Classic. I would like to make it work with lighting and I'm not sure if the only thing I need to replace are the url's. I have created a developer account for my PoC and everytime I launch the class I'm redirected to Classic.
public class LookupByUrlParamController {
String accountName;
String accountNumber;
String phone;
String website;
String email;
String socialhandle;
public LookupByUrlParamController () { }
public String redirectToAccount() {
Account account;
Map<String,String> params = ApexPages.currentPage().getParameters();
if(params.size() > 0) {
accountName = params.get('account_name');
accountNumber = params.get('account_number');
phone = params.get('phone');
website = params.get('website');
email = params.get('email');
socialhandle = params.get('SocialHandle');
}
try {
if(accountName != null) {
account = [select ID from Account where name = :accountName limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(accountNumber != null) {
account = [select ID from Account where AccountNumber = :accountNumber limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(phone != null) {
String npa;
String nnx;
String extension;
// Added logic for NA phone numbers
if (phone.length() == 10) {
npa = phone.substring(0,3);
nnx = phone.substring(3,6);
extension = phone.substring(6,10);
phone = '(' + npa + ') ' + nnx + '-' + extension;
}
account = [select ID from Account where phone = :phone limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(website != null) {
account = [select ID from Account where website = :website limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(email != null) {
account = [select ID from Account where email__c = :email limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(socialhandle != null) {
account = [select ID from Account where SocialHandle__c = :socialhandle limit 1];
}
} catch (System.queryException e) {//no entry found for twitter handle lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
String accountUrl;
if(account != null) {
accountUrl = '/' + account.Id;
} else {
accountUrl = '/';
}
return accountUrl;
}
public static testMethod void testLookupByUrlParamAccount() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountName = 'Avaya';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParamInvalidAccount() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountName = '';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, 'https://na7.salesforce.com/001/e');
}
public static testMethod void testLookupByUrlParamPhone() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '1234';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParamWherePhoneNumberIs10Chars() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '1234567891';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, 'https://na7.salesforce.com/001/e');//no record found
}
public static testMethod void testLookupByUrlParamInvalidPhoneNumber() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000015EKVPIA4');
}
public static testMethod void testLookupByUrlParamAccountNumber() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountNumber = '4321';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParam() {
LookupByUrlParamController controller = new LookupByUrlParamController();
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/');
}
}
In addition if anyone can tell where to being looking in the documentation to simply launch to new customer record form, or what are the redirect URLS?
It's not quite clear what you mean by
everytime I launch the class I'm redirected to Classic
However, this code appears not to have been touched in quite a number of years and there's several things you ought to change.
You are hard-coding non-My Domain Salesforce instance URLs (na7.salesforce.com). You should instead use URL.getSalesforceBaseUrl().toExternalForm(), and you'll need to turn on My Domain sooner or later.
You are using Classic-format URLs, which still work but will result in additional redirects. The Lightning equivalent for the "Create new Account" URL is lightning/o/Account/new and for a specific record is lightning/r/Account/<Id>/view. When you build Lightning components, you can use the navigation service to get these URLs dynamically.
You have inline test methods, which haven't been allowed since an API version well before I started on the platform. Break those out into a separate test class.
I have this app that registers the personal info of a patient and store it as Json Format on the database on the following format :
Patients {
patient id e.g.123456789 {
name:
email:
password:
bloodPressureReading {
10:37:13AM29Oct-2019:{
dia:34
prp:45
sys:12
}
}
}
}
I'm at the login page, and I need from the user to enter both his id and password for a simple login procedure. However, I don't know how to retrieve the password value from the firebase realtime database.
P.S. I don't want to use the firebase authentication service
I tried this code but it didn't work:
databasePatients.child("\"Patients\"").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//showData(dataSnapshot);
//old Code
/*
for(DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()){
//Loop 1 to go through all the child nodes of users
for(DataSnapshot booksSnapshot : uniqueKeySnapshot.child("123456789").getChildren()){
//loop 2 to go through all the child nodes of books node
//String bookskey = booksSnapshot.getKey();
//String password = booksSnapshot.getValue();
}
}
}*/
I tried this code also, It doesn't return any result although the id and password are corrects
Button testbutton = (Button) findViewById(R.id.button);
// To move to register page
testbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty( (testid.getText().toString().trim()))) {
Toast.makeText(getApplicationContext(), "Enter id to search for!", Toast.LENGTH_SHORT).show();
return;
}else
{
Query query = databasePatients.child("Patients").orderByChild("id").equalTo(testid.getText().toString().trim());
//Query query = databasePatients.child("Patients").child("123456789").orderByChild("id").equalTo(testid.getText().toString().trim());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Context context = getContext();
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot user : dataSnapshot.getChildren()) {
// do something with the individual "issues"
patients usersBean = user.getValue(patients.class);
if (usersBean.password.equals(txvPassword.getText().toString().trim())) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Password is wrong", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(getApplicationContext(), "User not found", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I also tried the code in
Login using email stored in firebase realtime database
,but I don't know why (dataSnapshot.exists()) return false .
Any help will be appreciated.
What can be wrong with the Onclick() method? Or verifyFromSqlite()? Trying to login with data just provided to the registration form, why the output of pressing Login button is just an error that the password/email is wrong?
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private final AppCompatActivity activity = LoginActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton appCompatButtonLogin;
private AppCompatTextView textViewLinkRegister;
private InputValidation inputValidation;
private DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
private void initViews(){
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
textInputLayoutEmail= (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword= (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail=(TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword=(TextInputEditText) findViewById(R.id.textInputEditTextPassword);
appCompatButtonLogin = (AppCompatButton) findViewById(R.id.appCompatButtonLogin);
textViewLinkRegister= (AppCompatTextView) findViewById(R.id.textViewLinkRegister);
}
private void initListeners(){
appCompatButtonLogin.setOnClickListener(this);
textViewLinkRegister.setOnClickListener(this);
}
private void initObjects(){
databaseHelper = new DatabaseHelper(activity);
inputValidation = new InputValidation(activity);
}
#Override
public void onClick(View v){
switch (v.getId()){
case R.id.appCompatButtonLogin:
verifyFromSQLite();
break;
case R.id.textViewLinkRegister:
Intent intentRegister = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intentRegister);
break;
}
}
private void verifyFromSQLite(){
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))){
return;
}
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))){
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, getString(R.string.error_message_password))){
return;
}
if(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
private void emptyInputEditText(){
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
}
This right here will do the wrong thing I believe.
if(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
please let me know what I am doing wrong because I've tried all the other answers and it won't click to me :) Why would error message me after registration and trying to log in?
Assuming that the checkUser method is unchanged from your previous question i.e. it is :-
public boolean checkUser(String password, String email){
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db= this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ? " + "AND "+ COLUMN_USER_PASSWORD+" =? ";
String[] selectionArgs = { email,password };
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if(cursorCount > 0){
return true;
}
return false;
}
Then you are passing the email as the password and the password as the email. Try changing :-
if(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
to :-
if(databaseHelper.checkUser( textInputEditTextPassword.getText().toString().trim()
,textInputEditTextEmail.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
I have a DynamoDB table with a primary key (id : integer) and secondary key (dateTo : String). I've made a Class that utilizes DynamoDBMapper:
#DynamoDBTable(tableName="MyItems"
public class MyItemsMapper {
private int id;
private String dateTo;
private String name;
#DynamoDBHashKey(attributeName="id")
public void setId(int id) { this.id = id; }
public int getId() { return id; }
#DynamoDBAttribute(attributeName="dateTo")
public void setDateTo(String dateTo) { this.dateTo = dateTo; }
public String getDateTo() { return dateTo; }
#DynamoDBAttribute(attributeName="name")
public void setName(String name { this.name = name; }
public String getName() { return name; }
public boolean saveItem(MyItemsMapper item) {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client); //<-- This connects to the DB. This works fine.
item.setId(generateUniqueNumber()); //<-- This generates a unique integer. Also seems to work fine.
mapper.save(item);
logger.info("Successfully saved item. See info below.");
logger.info(item.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
}
I then have a manager class that uses the bean above, like so:
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem(myItemsMapper);
}
}
I am running the manager class in a JUnit test:
public class MyManagerTest {
#Test
public void saveNewItemTest() {
MyManager myManager = new MyManager();
myManager.recordItem(1234567, "2018-01-01", "Anthony");
}
}
When I use the saveItem method above via my manager by running my JUnit test, I get the following error:
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: MyItemsMapper; no mapping for HASH key
Not really sure what it's pertaining to, as I definitely have a primary key for my table and my secondary key always has a value as well.
How do I get this to work?
More Info:
It's worth noting that I can record data into my DynamoDB table via the Item object. If I do the below, my data gets recorded into the database:
DynamoDB dynamoDB = new DynamoDBClient().connectToDynamoDB(); //<--
Connection. Works fine.
Table table = dynamoDB.getTable("MyItems");
item.withPrimaryKey("id", 1234567);
item.withString("dateTo", "2018-01-01");
item.withString("name", "Anthony");
PutItemOutcome outcome = table.putItem(item);
However, I'm trying to use DynamoDBMapper because I'm reading that it is a more organized, better way to access data.
Im not sure if this is causing the problem, but you are creating the myItemsMapper object, then passing a reference to this object to itself.
I would suggest removing your saveItem method. The MyItemsMapper class should be a plain old java object. Then make MyManager like this
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(myItemsMapper);
}
}
If you particularly want to keep the saveItem method make it like this
public boolean saveItem() {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(this);
logger.info("Successfully saved item. See info below.");
logger.info(this.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
And then in MyManager do
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem();
im trying to build a google app engine projekt with JPA, JAX-RS and JAX-B. My POST and GET Methods work, but my DELETE method doesn't delete the data.
Resource
#DELETE
#Path("card/{id}")
public void deleteCardById (#PathParam ("id") Long id) {
Service.removeCard(id);
}
Service
public static void removeCard(Long id) {
EntityManager em = EMFService.get().createEntityManager();
Card emp = findCard(id);
if (emp != null) {
em.remove(emp);
}
em.close();
}
public static Card findCard(Long id) {
EntityManager em = EMFService.get().createEntityManager();
Card card = em.find(Card.class, id);
em.close();
return card;
}
Entity
#XmlRootElement
#Entity
public class Card {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String begriff;
String tabu1;
String tabu2;
String tabu3;
public Card(String begriff, String tabu1, String tabu2, String tabu3) {
super();
Begriff = begriff;
Tabu1 = tabu1;
Tabu2 = tabu2;
Tabu3 = tabu3;
}
public Card() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBegriff() {
return Begriff;
}
public void setBegriff(String begriff) {
Begriff = begriff;
}
public String getTabu1() {
return Tabu1;
}
public void setTabu1(String tabu1) {
Tabu1 = tabu1;
}
public String getTabu2() {
return Tabu2;
}
public void setTabu2(String tabu2) {
Tabu2 = tabu2;
}
public String getTabu3() {
return Tabu3;
}
public void setTabu3(String tabu3) {
Tabu3 = tabu3;
}
#Override
public String toString() {
return "Card [Begriff=" + Begriff + ", Tabu1=" + Tabu1 + ", Tabu2="
+ Tabu2 + ", Tabu3=" + Tabu3 + "]";
}
When i Debug the app it gives the correct Object to the remove function. But it just don't remove the data ...
You mean you're using v1 of the GAE JPA plugin, and you don't bother putting a transaction around your remove (so the remove is delayed until the next transaction ... which never happens)?
Obviously you could either put a transaction around the remove, or better still you use v2 of the GAE JPA plugin
I was facing similar issue too. the JPA delete actually deletes the entity in the datastore,but it doesn't delete the entity from the JPA Cache.. You page is actually using the JPA Cached result list to display..
The way I used to resolve the issue is to have the JPA Cache cleared every time after a delete.
Sample Code would be something like this:
EM.getTransaction().begin();
EM.remove(current_record);
EM.getTransaction().commit();
EM.getEntityManagerFactory().getCache().evictAll();
ok i think i should write it like this
*edit the problem was the findCard function, i think because of the secone instance of the EntityManager. I chnaged it without using this method to this and now it works.
public static void removeCard(Long id) {
EntityManager em = EMFService.get().createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
Card card = em.find(Card.class, id);
if (card != null) {
em.remove(card);
}
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}