TextView From Response - java

Im trying to get Geolocation JSON data with URL from this API http://ip-api.com/json/?fields=query,country,city and show IP Address, City, Country to my TextView layout
Response:
{"city":"Bandung","country":"Indonesia","query":"127.0.0.1"}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button start;
TextView textView;
RequestQueue requestQueue;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.lokasi);
textView = (TextView) findViewById(R.id.textViewLok);
requestQueue = Volley.newRequestQueue(this);
start.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View ){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ip-api.com/json/?fields=query,country,city",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject = new JSONObject(response);
String city = jsonObject.getString("city");
String country= jsonObject.getString("country");
String ip = jsonObject.getString("query");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}
)
}
}
}
}

You need to put your response (that you get from the api) into a JSONObject.
JSONObject jsonObject = new JSONObject(myResponse);
After that you can parse the jsonObject.
String city = jsonObject.getString("city");
String country= jsonObject.getString("country");
String ip = jsonObject.getString("query");
Then just put the strings into your text view.
UPDATE:
Just change the onResponse to this.
#Override
public void onResponse(JSONObject response) {
String city = response.getString("city");
String country= response.getString("country");
String ip = response.getString("query");
}

Step 1. Make One POJO for your Response like Example.java
public class Example {
#SerializedName("city")
#Expose
private String city;
#SerializedName("country")
#Expose
private String country;
#SerializedName("query")
#Expose
private String query;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
Step 2. parse a string response
Example ex = gson.fromJson(json, BoxSearch.class);
Step 3. Now get value from POJO
String city = ex.getCity();
String country= ex.getQuery();
String ip = ex.getCountry();
Step 4. Set value in Textview
txtCity.setText(city);
txtCountry.setText(country);
txtIp .setText(ip);

Related

Cannot retrieve data from Firebase Realtime Database Android

I have few tables on Firebase from where I normally retrieve data, but there is one table from where I cannot get data in the same way, although a snapshot of the table has all the values
Fragment from where I get data
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_doctors, container, false);
mClinicId = mAuth.getUid();
mDoctorList = new ArrayList<>();
mFloatingActionButton = v.findViewById(R.id.add_doctor_fab);
mEmptyListTextView = v.findViewById(R.id.empty_list_tv);
checkIsListEmpty();
mDoctorsRecyclerView = v.findViewById(R.id.doctors_rv);
mDoctorsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
RecyclerView.VERTICAL, false));
mAdapter = new DoctorAdapter(mDoctorList, getActivity());
mDoctorsRecyclerView.setAdapter(mAdapter);
DatabaseReference mReference = FirebaseDatabase.getInstance().getReference().child("employees");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
Log.d("myLog", "onDataChange: snapshot " + snapshot);
for (DataSnapshot doctorSnapshot : snapshot.getChildren()){
Doctor doctor = doctorSnapshot.getValue(Doctor.class);
mDoctorList.add(doctor);
Log.d("myLog", "onDataChange: doctor " + doctor.getEmail());
}
mAdapter.setDoctors(mDoctorList);
mAdapter.notifyDataSetChanged();
checkIsListEmpty();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("myLog", "onCancelled: " + error.getMessage());
}
});
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mClinicId != null) {
startActivity(RegistrationActivity.newInstance(getActivity(),
true, mClinicId));
}
}
});
return v;
}
Doctor.java
private String mUID;
private String mEmail;
private String mSurname;
private String mName;
private String mPatronymic;
private Date mBirthDate;
private String mClinicId;
private String mPosition;
public Doctor() {
}
public Doctor(String UID, String email, String surname, String name, String patronymic, Date birthDate, String clinicId, String position) {
mUID = UID;
mEmail = email;
mSurname = surname;
mName = name;
mPatronymic = patronymic;
mBirthDate = birthDate;
mClinicId = clinicId;
mPosition = position;
}
public String getPosition() {
return mPosition;
}
public String getUID() {
return mUID;
}
public String getEmail() {
return mEmail;
}
public String getSurname() {
return mSurname;
}
public String getName() {
return mName;
}
public String getPatronymic() {
return mPatronymic;
}
public Date getBirthDate() {
return mBirthDate;
}
public String getClinicId() {
return mClinicId;
}
}
As you can see in the snapshot there is data, but when they are initialized, they are equal to null
Logs
2021-05-02 19:03:14.510 20833-20833/com.rpkeffect.android.rpkpolyclinik D/myLog: onDataChange: snapshot DataSnapshot { key = employees, value = {-MZhhQb9EaQkjOp8GLEm={uid=frrvDpFDCiVBPxHkoq328XT0XwV2, clinicId=7iNGGrbV4cXU1NnyVYy0rNIUE0w2, patronymic=dudhdh, surname=dhdjhdjdh, name=dudhd, position=dyduxh, birthDate={date=2, hours=0, seconds=0, month=4, timezoneOffset=-240, year=94, minutes=0, time=767822400000, day=1}, email=mail#mail.ru}, -MZhi2_TqCZvabIekppj={uid=IZsIIxdlw1f7E66xoNluzyc9IPT2, clinicId=frrvDpFDCiVBPxHkoq328XT0XwV2, patronymic=djdnx, surname=djdnxxn, name=xjxbx, position=jxjxnxx, birthDate={date=2, hours=0, seconds=0, month=4, timezoneOffset=-240, year=93, minutes=0, time=736286400000, day=0}, email=mail#mail.ru}} }
2021-05-02 19:03:14.512 20833-20833/com.rpkeffect.android.rpkpolyclinik D/myLog: onDataChange: doctor null
2021-05-02 19:03:14.512 20833-20833/com.rpkeffect.android.rpkpolyclinik D/myLog: onDataChange: doctor null
If I trying to get data from the other table, I can get it successfully
Firebase table
https://i.stack.imgur.com/qkjvB.png
The problem was that I didn't generate setters on my Doctor.java class
Doctor.java
public class Doctor {
private String mUID;
private String mEmail;
private String mSurname;
private String mName;
private String mPatronymic;
private Date mBirthDate;
private String mClinicId;
private String mPosition;
public Doctor() {
}
public Doctor(String UID, String email, String surname, String name, String patronymic, Date birthDate, String clinicId, String position) {
mUID = UID;
mEmail = email;
mSurname = surname;
mName = name;
mPatronymic = patronymic;
mBirthDate = birthDate;
mClinicId = clinicId;
mPosition = position;
}
public String getPosition() {
return mPosition;
}
public String getUID() {
return mUID;
}
public String getEmail() {
return mEmail;
}
public String getSurname() {
return mSurname;
}
public String getName() {
return mName;
}
public String getPatronymic() {
return mPatronymic;
}
public Date getBirthDate() {
return mBirthDate;
}
public String getClinicId() {
return mClinicId;
}
public void setUID(String UID) {
mUID = UID;
}
public void setEmail(String email) {
mEmail = email;
}
public void setSurname(String surname) {
mSurname = surname;
}
public void setName(String name) {
mName = name;
}
public void setPatronymic(String patronymic) {
mPatronymic = patronymic;
}
public void setBirthDate(Date birthDate) {
mBirthDate = birthDate;
}
public void setClinicId(String clinicId) {
mClinicId = clinicId;
}
public void setPosition(String position) {
mPosition = position;
}
When you try to map a node from Firebase Realtime Database into an object of your "Doctor", the name of the fields that exist in your class must match the name of your properties that exist in your database. Unfortunately, in your case, the fields don't match. See, the fields in your class start with "m", while in the database doesn't start with "m", which is not correct.
To solve this, you have two options, you either change the name of your properties in the class to match the one in the database, or you can use an annotation in front of the getters. For example, if you have a field called "mEmail" and the property in the database is called "email", your getter should look like this:
#PropertyName("email")
public String getEmail() {
return mEmail;
}
In this way, you tell the compiler to look for a property called "email" and not "mEmail".

How to Load a Json data into dropdown Spinner Using Android Fragments

I need to Show Registration Form With Spinner Using Fragments and get the data using Json
This is kind of register form. At the bottom we have change language button which will reset the form and will be shown in arabic / english.
[
{
"Id":1,
"TitleEN":"Kuwait",
"TitleAR":"الكويت",
"CurrencyId":1,
"CurrencyEN":"Kuwaiti Dinar",
"CurrencyAR":"دينار كويتى",
"CodeEN":"KWD",
"CodeAR":"د.ك",
"Code":"965"
},
{
"Id":2,
"TitleEN":"Emirates",
"TitleAR":"الإمارات",
"CurrencyId":2,
"CurrencyEN":"Emirati Dirham",
"CurrencyAR":"درهم إماراتي",
"CodeEN":"AED",
"CodeAR":"درهم",
"Code":"971"
},
{
"Id":3,
"TitleEN":"Saudi Arabia",
"TitleAR":"السعودية",
"CurrencyId":3,
"CurrencyEN":"Saudi Riyal",
"CurrencyAR":"ريال سعودى",
"CodeEN":"SAR",
"CodeAR":"ر.س",
"Code":"966"
}
]
Note.I assume you have followed the first 3 steps from this [question][1]
and will start from the following
Step 1
Add spinner in xml
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title" />
Step 2
In ApiInterface Class add the following code
#GET("/app/app.asmx/GetCountries")
Call<List<Country>> getCountry();
Step 3
Create new model class by name Country
public class Country {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("CurrencyId")
#Expose
private Integer currencyId;
#SerializedName("CurrencyEN")
#Expose
private String currencyEN;
#SerializedName("CurrencyAR")
#Expose
private String currencyAR;
#SerializedName("CodeEN")
#Expose
private String codeEN;
#SerializedName("CodeAR")
#Expose
private String codeAR;
#SerializedName("Code")
#Expose
private String code;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public Integer getCurrencyId() {
return currencyId;
}
public void setCurrencyId(Integer currencyId) {
this.currencyId = currencyId;
}
public String getCurrencyEN() {
return currencyEN;
}
public void setCurrencyEN(String currencyEN) {
this.currencyEN = currencyEN;
}
public String getCurrencyAR() {
return currencyAR;
}
public void setCurrencyAR(String currencyAR) {
this.currencyAR = currencyAR;
}
public String getCodeEN() {
return codeEN;
}
public void setCodeEN(String codeEN) {
this.codeEN = codeEN;
}
public String getCodeAR() {
return codeAR;
}
public void setCodeAR(String codeAR) {
this.codeAR = codeAR;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Step 4
find view in activity or fragment and add call the request and get response and add the response in spinner adapter.Initialize a string list out side the onCreate method
List<String> codes = new ArrayList<String>();
APIInterface apiInterfacePages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
apiInterfacePages= PageApiClient.getRetrofit().create(APIInterface.class);
Call<List<Country>> getCountry = apiInterfacePages.getCountry();
getCountry.enqueue(new Callback<List<Country>>() {
#Override
public void onResponse(Call<List<Country>> call, Response<List<Country>> response) {
countryList = response.body();
for (int i = 0; i < countryList.size(); i++) {
codes.add(countryList.get(i).getCode());
}
ArrayAdapter<String> adapterTime = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, codes);
spinner.setAdapter(adapterTime);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, "" + countryList.get(i).getTitleEN(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onFailure(Call<List<Country>> call, Throwable t) {
}
});
}

Resource Not Found while converting int value of id to String using Retrofit

I am using Retrofit to fetch and display data to the screen. I want to search users by their id's. I made interface like this :
#GET("/posts/{id}")
Call<postmodel> getUsersModel(#Path("id") int id);
The problem is with DetailActivity line 52:
EndPointAccess access = APIClient.getRetrofit().create(EndPointAccess.class);
Call<postmodel> modelCall = access.getUsersModel(Integer.parseInt(_userinput));
Here is the Logcat report:
android.content.res.Resources$NotFoundException:
String resource ID #0x1
at
android.content.res.Resources.getText(Resources.java:351)
at
android.content.res.MiuiResources.getText(MiuiResources.java:97)
at
android.widget.TextView.setText(TextView.java:4562)
at com.example.sahil.typicode1.Activity.DetailActivity$2.onResponse(DetailActivity.java:60)
APIClient.java
public static final String BASE_URL = "https://jsonplaceholder.typicode.com";
private static Retrofit retrofit = null;
public static Retrofit getRetrofit()
{
if (retrofit == null)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory
.create()).build();
}
return retrofit;
}
EndPointAccess.java (Interface)
#GET("/posts/{id}")
Call<postmodel> getUsersModel(#Path("id") int id);
MainActivity.java
EditText userid;
Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userid = (EditText) findViewById(R.id.etuserid);
search = (Button) findViewById(R.id.btnsearch);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,DetailActivity.class);
intent.putExtra("STRING_I_NEED",userid.getText().toString());
startActivity(intent);
}
});
}
DetailActivity.java
TextView userid,usertitle,userbody;
Button viewall;
String _userinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
_userinput = intent.getStringExtra("STRING_I_NEED");
userid = (TextView) findViewById(R.id.textViewid);
usertitle = (TextView) findViewById(R.id.textViewtitle);
userbody = (TextView) findViewById(R.id.textViewbody);
viewall = (Button) findViewById(R.id.btnviewall);
viewall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(DetailActivity.this, "Done!", Toast.LENGTH_SHORT).show();
}
});
getinfo();
}
private void getinfo()
{
EndPointAccess access = APIClient.getRetrofit().create(EndPointAccess.class);
Call<postmodel> modelCall = access.getUsersModel(Integer.parseInt(_userinput));
modelCall.enqueue(new Callback<postmodel>() {
#Override
public void onResponse(Call<postmodel> call, Response<postmodel> response)
{
userid.setText(response.body().getId());
usertitle.setText(response.body().getTitle());
userbody.setText(response.body().getBody());
}
#Override
public void onFailure(Call<postmodel> call, Throwable t) {
Toast.makeText(DetailActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
});
}
postmodel.java (pojo class)
private int id;
private String title;
private String body;
public postmodel(int id, String title, String body) {
this.id = id;
this.title = title;
this.body = body;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
You are trying to set an integer in the setText function which only accepts String values. Therefore it is giving this error.
Hence you need to convert it into a string using String.valueOf() function.
remove userid.setText(response.body().getId());
add userid.setText(String.valueOf(response.body().getId()));
SetText with integer parameter looks resource with that id : reference
So you should pass an string value to setText()
userid.setText(String.valueOf(response.body().getId()));
So, replacing this line in DetailActivity.java might help you fix the exception :)

Upload data to firebase through a java class and retrieve one attribute in another activity

Firebase Database LinkI am trying to save data to firebase using this code.
Everything works fine. I was saving the data creating new children uder users>uid. but now when i try to save the data by creating an object and passing that object in setvalue, the app crashes. Please help.
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;
}
}
And i am also trying to retrieve UserName for the user with which i am signed in in another activity.
using this 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();
Please help
Firebase is getting confused between this field:
public String City;
And this getter:
public String getCity() {
return City;
}
The field defines a property City, while the getter defines a property city. As you can see the case is different between the two, which leads to the error message.
The easiest fix is to mark all your fields as private:
private String City;
This keeps Firebase from considering them while reading/writing users.

Error:(93, 34) error: constructor Request in class Request cannot be applied to given types reason: actual and formal argument lists differ in length

i am currrently working on a firebase project and i am stuck with this error
it keeps showing this error during compilation.
Error:(93, 34) error: constructor Request in class Request cannot be applied to given types;
required: Uri,int,String,List<Transformation>,int,int,boolean,boolean,boolean,float,float,float,boolean,Config,Priority
found: String,String,String,String,List<Order>
reason: actual and formal argument lists differ in length
Here is my Cart Class
public class Cart extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
TextView txtTotalPrice;
FButton btnPlace;
List<Order> cart = new ArrayList<>();
CartAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
// init firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//Init
recyclerView = (RecyclerView) findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
txtTotalPrice = (TextView) findViewById(R.id.total);
btnPlace = (FButton) findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAlertDialog();
}
});
loadListFood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One More Step!");
alertDialog.setMessage("Enter your address: ");
final EditText edtAddress = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);//Add edit Text to alert dialog
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Create new Request
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
//Submit to Firebase
//We will using System.CurrentMilli to key
requests.child(String.valueOf((System.currentTimeMillis()))).setValue(request);
//Delete Cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Thank you , Order Placed", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
private void loadListFood() {
cart = new Database(this).getCarts();
adapter = new CartAdapter(cart, this);
recyclerView.setAdapter(adapter);
//calculate total price
int total = 0;
for (Order order : cart)
total += (Integer.parseInt(order.getPrice())) * (Integer.parseInt(order.getQuantity()));
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
} }
and here is my constructor class Request
package game.bakarunlimited.com.androideatit.Model;
import java.util.List; /** * Created by gaurang on 9/23/2017. */
public class Request {
private String phone;
private String name;
private String address;
private String total;
private List<Order> foods;
// list of food Order
public Request(){
}
public Request(String phone, String name, String address,String total, List<Order> foods) {
this.phone = phone;
this.name = name;
this.address = address;
this.total = total;
this.foods = foods;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public List<Order> getFoods() {
return foods;
}
public void setFoods(List<Order> foods) {
this.foods = foods;
} }
Can you check your Cart class and make sure you've imported the correct Request (just make sure the package name matches where you have your Request class at the top of the file)
The reason I say this is because your current Request class should be taking in String, String, String, String, List<Order> to create the object however it's throwing an error saying its expecting Uri,int,String,List,int,int,boolean,boolean,boolean,float,float,float,boolean,Config,Priority which makes me think you are using the wrong import for Request

Categories