This question already has answers here:
Property value doesn't update value to Label in UI in Xamarin Forms
(2 answers)
Closed 1 year ago.
The following Label does not show data while running it <Label Text="{Binding Firstname}"/> if I run code in Debug mode and if I change Label to Editor or something else it shows data.
Please let me know why is that and how can I solve it.
Code Behind
Private fields
private string email;
private string phone;
private string firstname;
private string lastname;
Method calling data from FirebaseFirestore
public async Task GetDataAsync()
{
var user = await DependencyService.Get<IAccountService>().GetUserAsync();
phone = user.Phone;
email = user.Email;
firstname = user.Firstname;
lastname = user.Lastname;
}
Public properties
public string Firstname
{
get { return firstname; }
set
{
firstname = value;
OnPropertyChanged(nameof(Firstname));
}
}
public string Lastname
{
get {return lastname;}
set
{
lastname = value;
OnPropertyChanged(nameof(Lastname));
}
}
public string Email
{
set
{
if (email != value)
{
email = value;
OnPropertyChanged("Email");
}
}
get
{
return email;
}
}
public string Phone
{
set
{
if (phone != value)
{
phone = value;
OnPropertyChanged("Phone");
}
}
get
{
return phone;
}
}
This line:
firstname = user.Firstname;
Must be changed to:
Firstname = user.Firstname;
Explanation:
If you don't use the Firstname property setter, then OnPropertyChanged(nameof(Firstname)); never gets called.
So XAML does not know that the property's value has changed.
Related
I am new to DynamoDB and wanted to know how can we query on a table in DynamoDB by using ONLY partition key in JAVA
I have table called "ervive-pdi-data-invalid-qa" and it's Schema is :
partition key is "SubmissionId"
Sort key is "Id".
City (Attribute)
Errors (Attribute)
The table looks like this:
Table
I want to retrieve the sort key value and remaining attributes data by using Partition key using (software.amazon.awssdk) new version of AWS SDK DynamoDB classes.
is it possible to get it? If so, can any one post the answers?
Have tried this:
DynamoDbClient ddb =
DynamoDbClient.builder().region(Region.US_EAST_1).build();
DynamoDbEnhancedClient enhancedClient =
DynamoDbEnhancedClient.builder()
.dynamoDbClient(ddb)
.build();
//Define table
DynamoDbTable<ErvivePdiDataInvalidQa> table =
enhancedClient.table("ervive-pdi-data-invalid-qa",
TableSchema.fromBean(ErvivePdiDataInvalidQa.class));
Key key = Key.builder().partitionValue(2023).build();
ErvivePdiDataInvalidQa result = table.getItem(r->r.key(key));
System.out.println("The record id is "+result.getId());
ErvivePdiDataInvalidQa table class is in below comment*
and it is returning "The provided key element does not match the schema (Service: DynamoDb, Status Code: 400, Request ID: PE1MKPMQ9MLT51OLJQVDCURQGBVV4KQNSO5AEMVJF66Q9ASUAAJG, Extended Request ID: null)"
Query you need is documented in one of the examples of AWS Dynamodb Query API for Java.
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
.withRegion(Regions.US_WEST_2).build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("ervive-pdi-data-invalid-qa");
QuerySpec spec = new QuerySpec()
.withKeyConditionExpression("SubmissionId = :v_id")
.withValueMap(new ValueMap()
.withInt(":v_id", 2146));
ItemCollection<QueryOutcome> items = table.query(spec);
Iterator<Item> iterator = items.iterator();
Item item = null;
while (iterator.hasNext()) {
item = iterator.next();
System.out.println(item.toJSONPretty());
}
A single Query operation can retrieve a maximum of 1 MB of data, see documentation
I have been working with Padma on this issue. We first tried A. Khan's code but could not get passed authentication with v1. Instead we got "WARNING: Your profile name includes a 'profile ' prefix. This is considered part of the profile name in the Java SDK, so you will need to include this prefix in your profile name when you reference this profile from your Java code."
ultimately it could not get the credentials. Our credentials assume IAM roles in .aws/config-i2 file. It works fine in v2 but not v1.
So then we tried v2 of the SDK and have no problems with connecting but we get NULL returned on trying to fetch all records from the table.
In all of the below attempts using v2 of SDK, table data returns NULL
We created this table class
package data;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
#DynamoDbBean
public class ErvivePdiDataInvalidQa {
private int submissionId;
private String id;
private String address1;
private String city;
private String dateOfBirth;
private String errors;
private String firstName;
private String firstNameNormalized;
private String gender;
private String lastName;
private String lastNameNormalized;
private String middleNameInitial;
private String postalCode;
private String rowNumber;
private String state;
private String submissionType;
#DynamoDbPartitionKey
public int getSubmissionId() {
return submissionId;
}
public void setSubmissionId(int submissionId) {
this.submissionId = submissionId;
}
#DynamoDbSortKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String Address1) {
this.address1 = Address1;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getErrors() {
return errors;
}
public void setErrors(String errors) {
this.errors = errors;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstNameNormalized() {
return firstNameNormalized;
}
public void setFirstNameNormalized(String firstNameNormalized) {
this.firstNameNormalized = firstNameNormalized;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastNameNormalized() {
return lastNameNormalized;
}
public void setLastNameNormalized(String lastNameNormalized) {
this.lastNameNormalized = lastNameNormalized;
}
public String getMiddleNameInitial() {
return middleNameInitial;
}
public void setMiddleNameInitial(String middleNameInitial) {
this.middleNameInitial = middleNameInitial;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getRowNumber() {
return rowNumber;
}
public void setRowNumber(String rowNumber) {
this.rowNumber = rowNumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getSubmissionType() {
return submissionType;
}
public void setSubmissionType(String submissionType) {
this.submissionType = submissionType;
}
}
DynamoDB code to get all records
//Connection
DynamoDbClient ddb = DynamoDbClient.builder().build();
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(ddb)
.build();
//Define table
DynamoDbTable<ErvivePdiDataInvalidQa> table = enhancedClient.table("ervive-pdi-data-invalid-qa", TableSchema.fromBean(ErvivePdiDataInvalidQa.class));
//Get All Items from table - RETURNING NULL
Iterator<ErvivePdiDataInvalidQa> results = table.scan().items().iterator();
while (results.hasNext()) {
ErvivePdiDataInvalidQa rec = results.next();
System.out.println("The record id is "+rec.getId());
}
Also tried:
DynamoDB code to filter by SubmissionID
AttributeValue attr = AttributeValue.builder()
.n("1175")
.build();
// Get only Open items in the Work table
Map<String, AttributeValue> myMap = new HashMap<>();
myMap.put(":val1", attr);
Map<String, String> myExMap = new HashMap<>();
myExMap.put("#sid", "SubmissionId");
// Set the Expression so only Closed items are queried from the Work table
Expression expression = Expression.builder()
.expressionValues(myMap)
.expressionNames(myExMap)
.expression("#sid = :val1")
.build();
ScanEnhancedRequest enhancedRequest = ScanEnhancedRequest.builder()
.filterExpression(expression)
.limit(15)
.build();
// Get items in the Record table and write out the ID value
Iterator<ErvivePdiDataInvalidQa> results = table.scan(enhancedRequest).items().iterator();
while (results.hasNext()) {
ErvivePdiDataInvalidQa record = results.next();
System.out.println("The record id is " + record.getId());
}
I am trying to display on the console a list of object But it doesn't show the objects...
Here is the javascript I use to display the object received from the server :
connection.on("ReceiveLog", function (chatMessages) {
console.log(chatMessages);
for (var item in chatMessages) {
// work with key and value
var encodedMsg = item.User + " says " + item.Message;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
} });
The server is sending a list of ChatMessage. Here is the ChatMessage class :
public class ChatMessage
{
string User { get; set; }
string Message { get; set; }
public ChatMessage(string user, string message)
{
this.User = user;
this.Message = message;
}
}
Why are my objects completely broken ? When I break the code on the server side, it really sends the list correctly. The problem seems to be from the javascript or maybe I need to serialize from the server side ?
I needed to set all the property of the object Public like so :
public class ChatMessage
{
public string User { get; set; }
public string Message { get; set; }
public ChatMessage(string user, string message)
{
this.User = user;
this.Message = message;
}
}
It works now.
Lets say I have 100 documents with fields
Name
Age
Address
Now suppose my business model is change and I want to add new field call PhoneNumber.
How to add field PhoneNumber in all 100 documents ?
Is is possible to such stuff on NoSQL database?
You will have to write code to iterate all the documents to update, then actually update a new value in each one of them. Firestore has no similar command as "update tablename set x=y where ..." in SQL.
Is is possible to such stuff on NoSQL database?
Yes it is! Assuming you have a User model class that look like this:
public class User {
private String name;
private int age;
private String address;
private String phoneNumber; //Property that is newly added
public User() {}
public User(String name, int age, String address, String phoneNumber) {
this.name = name;
this.age = age;
this.address = address;
this.phoneNumber = phoneNumber;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public String getPhoneNumber() { return phoneNumber; }
public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }
}
To actually add a new property and update it accordingly, you need to use setters. If you are setting the values directly onto the public fields, the setters are not mandatory.
How to add field PhoneNumber in all 100 documents?
As also #Doug Stevenson mentioned in his answer, to solve this, you need to iterate all the documents within your users collection. So please use the following lines of code:
db.collection("users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
User user = document.toObject(User.class);
user.setPhoneNumber("+1-111-111-111"); //Use the setter
String id = document.getId();
db.collection("users").document(id).set(user); //Set user object
}
}
}
});
The result of this code would be to add the phoneNumber property to all you User objects with a default value of +1-111-111-111. You can also set the value to null if it's more convenient for you. At the end, the updated object is set right on the corresponding reference.
If you are not using a model class, please see my answer from this post.
I am building a chat app with Firebase and I am having issues identifying who is who, when a user sends another user a message, he needs to post it to the receivers node and he needs to know his UID to do that. I need to know how to get the receiver's UID, so I can post directly to his own node.
I tried using intent.putExtra and intent.getExtras from my MainActivity which lists out every user from their directories, this is my current code that does not successfully pass the data I need.
public static class PlaceholderFragment extends Fragment {
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public static class UserHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View mView;
public UserHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mView = itemView;
}
public void setName(String name) {
TextView field = (TextView) mView.findViewById(R.id.thename);
field.setText(name);
}
public void setImage(String image){
ImageView pp = (ImageView) mView.findViewById(R.id.imageurl);
try{
Picasso.with(Application.getAppContext()).load(image).placeholder(R.drawable.nodp).error(R.drawable.nodp).transform(new CircleTransform()).into(pp);
}
catch (IllegalArgumentException e){
Picasso.with(Application.getAppContext()).load(R.drawable.nodp).transform(new CircleTransform()).into(pp);
}
}
#Override
public void onClick(View mView) {
//what to do here
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
//private static final String TAG = "UserListActivity";
//final TextView name = (TextView) rootView.findViewById(R.id.lastname) ;
//final ImageView profileImage = (ImageView) rootView.findViewById(R.id.imageView4);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
final DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = root.child("users");
RecyclerView recycler = (RecyclerView) rootView.findViewById(R.id.recyclerview3);
recycler.setHasFixedSize(true);
recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
FirebaseRecyclerAdapter mAdapter = new FirebaseRecyclerAdapter<UserList, UserHolder>(UserList.class, R.layout.userlistrow, UserHolder.class, userRef) {
#Override
public void populateViewHolder(UserHolder userViewHolder, final UserList userList, final int position) {
//try catch block to catch events of no posts, it will most likely return a null error, so im catching it, else
//find its exception and catch it
try {
String firstname = userList.getFirstname().toString();
String lastname = userList.getLastname().toString();
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1); //convert first string to uppercase
lastname = lastname.substring(0, 1).toUpperCase() + lastname.substring(1);// same thing happening here
String name = (firstname + " " + lastname); // concatenate firstname and lastname variable.
userViewHolder.setName(name);
}
catch(NullPointerException e) {
String firstname = "Not";
String lastname = "set";
String name = (firstname + " " + lastname );
userViewHolder.setName(name);
}
catch (StringIndexOutOfBoundsException e) {
String firstname = "No";
String lastname = "name";
String name = (firstname + " " + lastname );
userViewHolder.setName(name);
}
//note that picasso view holder was applied in the view holder instead
//String image = userList.getImgUrl().toString();
//userViewHolder.setImage(image);
//findViewById(R.id.progressBar3).setVisibility(View.GONE);
This is where I am passing the extras, and it doesnt seem to work
userViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.w(TAG, "You clicked on "+position);
//String firstname = userList.getFirstname();
//String lastname = userList.getLastname();
//firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1); //convert first string to uppercase
//lastname = lastname.substring(0, 1).toUpperCase() + lastname.substring(1);// same thing happening here
//String name = (firstname + " " + lastname); // concatenate firstname and lastname variable.
Intent intent = new Intent(getActivity(), Userdetail.class); //change to onclick
intent.putExtra("userId", userList.getUserId());//you can name the keys whatever you like
intent.putExtra("lastname", userList.getLastname().toString());
intent.putExtra("firstname", userList.getFirstname().toString());
intent.putExtra("image", userList.getImgUrl().toString()); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
startActivity(intent);
}
});
}
};
recycler.setAdapter(mAdapter);
return rootView;
}
}
If you need more information, please ask in the comments. Ive googled around but no help
package com.mordred.theschoolapp;
import com.google.firebase.database.IgnoreExtraProperties;
/**
* Created by mordred on 11/28/16.
*/
public class UserList {
public String firstname;
public String lastname;
public String userId;
public String imgUrl;
public UserList() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
How do I use the JdbcTemplate.query()/queryForList() to run a query using namedParameter and store the result set into a List of 'User's?
User Class:
public class User {
String name = null;
String id = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return name;
}
public void setId(String id) {
this.id = id;
}
}
Query:
SELECT name, id FROM USERS where email=:email
I'm looking for something like:
ArrayList<User> userList = jdbcTemplate.query(sql_query,
...some_mapper..., etc);
Seems like the answer to the question is not available at one place, on the Internet. Here's what I found out:
For adding the resultset into a List<>, we can use the NamedParameterJdbcTemplate.query() function:
NamedParameterJdbcTemplate jdbcTemplate;
ArrayList<User> usersSearchResult = (ArrayList<User>) jdbcTemplate.query(
USER_LIST_TP_query,
namedParameters,
new RowMapperResultSetExtractor<User>(new UserRowMapper(), 20));
We also have to define a custom RowMapperResultSetExtractor so that JDBC can understand how to convert each row in the result set to the type User.
private class UserRowMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getString("ID"));
user.setName(rs.getString("NAME"));
return user;
}
}