Transfer information to firebase using a Java class and fetch a single attribute in a different activity

Firebase Database LinkI've been encountering an issue while trying to store data in Firebase using a particular code snippet. Previously, I was able to save data by creating new children under users>uid without any problems. However, now that I am attempting to save data by instantiating an object and passing it into setvalue, the app crashes. Any assistance would be greatly appreciated.

public class RegComplete extends AppCompatActivity {

private EditText Name, Surname, Address, Tel, DateOfBirth,Username;
private String _name, _surname, _address, _Tel, _DateOfBirth,_UserName, email;
public String uid = "";

FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference mdatabase;
private DatabaseReference fdatabase;
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser objuser = auth.getCurrentUser();

List<String> lstSports = new ArrayList<String>();
List<String> lstSteden = new ArrayList<String>();
String strSport1,strSport2,strSport3;
public String strCity;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reg_complete);

    fdatabase = database.getReference();

    fdatabase.child("Steden").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot DS:dataSnapshot.getChildren()) {
                String CityName = DS.child("CityName").getValue(String.class);
                City stad = new City(CityName);
                lstSteden.add(stad.CityName);
            }
            final Spinner CitySpin = (Spinner) findViewById(R.id.CitySpin);
            ArrayAdapter<String> CityAdapter = new ArrayAdapter<String>(RegComplete.this, android.R.layout.simple_spinner_item, lstSteden);
            CityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            CitySpin.setAdapter(CityAdapter);
            CitySpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    strCity = CitySpin.getSelectedItem().toString();
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });




    fdatabase.child("SPORTS").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds :dataSnapshot.getChildren()) {
                String sportName = ds.child("SportName").getValue(String.class);
                Sport objsport = new Sport(sportName);

                lstSports.add(objsport.SportName);
            }

            final Spinner Sports1 = (Spinner) findViewById(R.id.SportSpinner1);
            ArrayAdapter<String> SportAdapter = new ArrayAdapter<String>(RegComplete.this, android.R.layout.simple_spinner_item, lstSports);
            SportAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            Sports1.setAdapter(SportAdapter);
            Sports1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    strSport1 = Sports1.getSelectedItem().toString();

                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            final Spinner Sports2 = (Spinner) findViewById(R.id.SportSpinner2);
            Sports2.setAdapter(SportAdapter);
            Sports2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    strSport2 = Sports2.getSelectedItem().toString();
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });

            final Spinner Sports3 = (Spinner) findViewById(R.id.SportSpinner3);
            Sports3.setAdapter(SportAdapter);
            Sports3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    strSport3 = Sports3.getSelectedItem().toString();
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    Name = findViewById(R.id.NameeditText);
    _name = Name.getText().toString();
    Surname = findViewById(R.id.SurnameEditText);
    _surname = Surname.getText().toString();
    Address = findViewById(R.id.AdressEditText);
    _address = Address.getText().toString();
    Tel = findViewById(R.id.TelEditText);
    _Tel = Tel.getText().toString();
    DateOfBirth = findViewById(R.id.DOBEditText);
    _DateOfBirth = DateOfBirth.getText().toString();
    Username = findViewById(R.id.UserIDEditText);
    _UserName = Username.getText().toString();
    email = FirebaseAuth.getInstance().getCurrentUser().getEmail().toString();


}
public void btnSave_Click(View V){
    User usinfo = new User(email,_UserName,_name,_surname,_address,strCity,_Tel,_DateOfBirth,strSport1,strSport2,strSport3,uid);

    mdatabase = FirebaseDatabase.getInstance().getReference("USERS");
    uid = objuser.getUid();
    mdatabase.child(uid).setValue(usinfo);

    Intent i = new Intent(RegComplete.this, LoginActivity.class);
    Toast.makeText(RegComplete.this ,"Registration Complete" ,Toast.LENGTH_SHORT).show();
    startActivity(i);
}

}

The code for USER.class

public class User {

public String Email;
public String UserName;
public String Name;
public String SurName;
public String StreetAdress;
public String City;
public String Tel;
public String DOB;
public String Sport1;
public String Sport2;
public String Sport3;
public String UserId;
public User(){
    // Default constructor required by Firebase
}

public User(String email, String userName, String name, String surName, String streetAdress, String city, String tel, String DOB, String sport1, String sport2, String sport3, String userId) {
    Email = email;
    UserName = userName;
    Name = name;
    SurName = surName;
    StreetAdress = streetAdress;
    City = city;
    Tel = tel;
    this.DOB = DOB;
    Sport1 = sport1;
    Sport2 = sport2;
    Sport3 = sport3;
    UserId = userId;
}

public String getEmail() {
    return Email;
}

public String getUserName() {
    return UserName;
}

public String getName() {
    return Name;
}

public String getSurName() {
    return SurName;
}

public String getStreetAdress() {
    return StreetAdress;
}

public String getCity() {
    return City;
}

public String getTel() {
    return Tel;
}

public String getDOB() {
    return DOB;
}

public String getSport1() {
    return Sport1;
}

public String getSport2() {
    return Sport2;
}

public String getSport3() {
    return Sport3;
}

public String getUserId() {
    return UserId;
}

}

Additionally, I am attempting to retrieve the UserName for the currently signed-in user in another activity using the following code:

   mdatabase.child("USERS").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                userinf = ds.child(uid).getValue(User.class);
            };

            txtUserNaam.setText(userinf.UserName);
        }

Where

DatabaseReference mdatabase = FirebaseDatabase.getInstance().getReference();

Your help is much appreciated.

Answer №1

There seems to be a confusion in Firebase regarding the naming of this field:

public String City;

And its corresponding getter method:

public String getCity() {
    return City;
}

The field is named City, while the getter refers to city. This difference in casing is causing the error message.

To resolve this issue, consider marking all fields as private:

private String City;

By doing this, Firebase will no longer mix them up when handling user data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to utilize Safari driver in Selenium for positioning images

I'm attempting to capture a screenshot of a webpage, extract the size and position of an image, and then save that image to a file. Here is a snippet of code: this.driver.navigate().to(xxx); final byte[] arrScreen = ((TakesScreenshot) this.driver). ...

The SubMenu icon in Android disappears when creating a menu dynamically

I'm currently working on creating a dynamic menu list, and I've managed to create the menu options successfully. However, every time I run my code, the icon for the main item disappears. Below is a snippet of my code: private static final int SU ...

I'm stumped as to why I'm having trouble loading JSON data into a DataFrame

Is there a way to convert the JSON "Data" section into a Pandas table easily? Below is my attempted code: import json import urllib.request import pandas url = urllib.request.urlopen('https://www.cryptocompare.com/api/data/coinlist/') json_obj ...

Extract specific data points from external API responses on a webpage crafted in HTML

I require assistance on how to extract individual values from an HTML page. I received a response from the PAYU payment gateway team in HTML format, but I need to retrieve specific attribute values related to the transaction details. Below is the response ...

Unraveling the complexities of parsing multi-tiered JSON structures

I am struggling with indexing values from a multi-level JSON array. Here is the JSON data in question: { "items": [ { "snippet": { "title": "YouTube Developers Live: Embedded Web Player Customization" } ...

Understanding JavaScript's JSON Path Variables

I've scoured the internet for solutions to a similar issue but haven't been able to find any helpful information yet. My current challenge involves accessing a picture path (in JSON format) based on the material type of the selected element. Her ...

Error: Attempting to access the property 'push' of an undefined variable has resulted in an unhandled TypeError

if (Math.random() <= .1) { let orgAdmin = User.find({email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1234454665324721380c0d">[email protected]</a>'}); or ...

What are some methods for extracting text from a document using Selenium Webdriver?

If I have a single document, how can I extract text from it using the Selenium WebDriver? Below is the code I've used: d1.findElementByClassName("odd").click(); Thread.sleep(5000); d1.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); WebElem ...

Discovering and sorting an array in Vue.js based on IDs

Hello everyone, I've been attempting to filter my results using the filter and includes methods but it doesn't seem to be working. Does anyone have a solution for this, perhaps involving includes or something similar? companies ids [1,2,3] user c ...

Is there a method to transmit data without escaping it in JavaScriptSerializer?

Recently, I created a custom .ToJson() extension method like this: public static string ToJson(this object obj) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(obj); } This handy method allows me to eas ...

Utilize JavaScript to parse JSON response data, calculate the average of a specified field while keeping track of

The data returned from the API call is structured as follows: var array = {"scores":[ { userid: "1", mark: 4.3 }, { userid: "1", mark: 3.8 }, { userid: "2", mark: 4.6 }, { userid: "2&quo ...

Why is the "description" field included in JSON Schemas and what role does it serve?

I'm a bit confused about the purpose of the "description" field in a JSON Schema. Is it meant for comments or is it used as an ID? { "id": "http://www.example.org/schema#", "schema": "http://json-schema.org/draft-04/schema#", "description ...

Creating nested JSON using xpath by utilizing SmarGWT's DynamicForm and Form items

I have successfully set up a SmarGWT datasource that retrieves nested JSON data like this: {username:"tom",password:"pwd",userType:{id:1,name:"admin user type"}} The DataSource is configured with the following fields: DataSourceTextField usernameField = ...

Disable body scrolling on mobile devices in native browsers

When using the native browser on Samsung Galaxy S5 / S6, the following CSS code: body { overflow: hidden; } does not successfully prevent the body from scrolling. Is there a way to work around this issue? Edit: As mentioned below, one workaround is t ...

Convert objects to JSON using ServiceStack serialization with a specific function

I have a C# helper class that defines a JavaScript component with a specific JavaScript function name. new Button({Label = "Execute", OnClick = "ExecuteFunction"}); This will generate a JSON text: { label = "Execute", onClick = ExecuteFunction} (where ...

App builder shows raw HTML code instead of generating a dynamic table

I am currently working on an application that requires gathering data in a csv format from Google Sheets and importing it into App Inventor. Additionally, I need to include HTML code to display the table in a more visually appealing way. Here is what the ...

Tips on effectively extracting data from a SQLite JSON field that contains an array value

Within my sqlite database, there is a field that contains a complete JSON object. I need to perform some select queries on this JSON data. Specifically, I am looking to extract comments where the "pod" field is 'fb'. How can I properly extract th ...

Switch from using JSON to representing data as a String in the Swift

Received a JSON file from an API, but the content appears in this format: [ "https:\/\/seekingalpha.com\/article\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL" ] If we name the JSON Object above as json, I converted ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

Using Vue/Nuxt.js to compute the cumulative sum of hierarchically structured JSON data

When using Nuxt async data, I am retrieving a JSON object that includes a nested array in the following structure: "topic_list": { "topics": [ { "id": 9148, "title": "A", "views": 12 }, { "id": 3228, ...