how to get spinner item on selection of previous spinner in android? - java

I have 3 spinner in my Home Activity.If i select 1 other should change according to 1st spinner.I have Country, City and Location as spinner, if i select country then city and location should change according to that.Till now i manage to get country item in spinner (item from database).Now how to get only selected item in spinner..i m confused.??
here is my Home Activity(where i am getting spinner (country) item):
public class Home extends AppCompatActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
private Spinner countrySpinner, locationSpinner, citySpinner;
private TextView cityCodeTextView;
private Button submitButton;
private ArrayList<String> country_list, location_list, city_list;
private JSONArray result;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
countrySpinner = (Spinner) findViewById(Country);
//citySpinner = (Spinner) findViewById(City);
//locationSpinner = (Spinner) findViewById(R.id.Location);
countrySpinner .setOnItemSelectedListener(this);
country_list = new ArrayList<String>();
//location_list = new ArrayList<String>();
// city_list = new ArrayList<String>();
getData();
}
private void getData(){
StringRequest
stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
Log.d("Test",response);
JSONArray result = new JSONArray(response);
//Calling method getCountry to get the Country from the JSON Array
getCountry(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getCountry(JSONArray jsonArrayCountry){
//Traversing through all the items in the json array
List<Country> countries = new ArrayList<>();
try {
String country_name, country_code;
JSONObject countries_object;
for (int i = 0; i < jsonArrayCountry.length(); i++) {
countries_object = jsonArrayCountry.getJSONObject(i);
country_code = countries_object.getString("id");
country_name = countries_object.getString("country");
countries.add(new Country(country_code, country_name));
}
ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
countrySpinner.setPrompt("--Select Country--");
countrySpinner.setAdapter(countryAdapter);
countrySpinner.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter,
R.layout.contact_spinner_row_nothing_selected,this));
countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} catch (JSONException e) {
Log.e("Home", e.getLocalizedMessage(), e);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
//textViewName.setText(getName(position));
//textViewCourse.setText(getCourse(position));
//textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
// textViewName.setText("");
// textViewCourse.setText("");
//textViewSession.setText("");
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
this is Country.java
public class Country {
private String name;
private String id;
public Country(String id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
#Override
public String toString() {
return name;
}
}
this is City.java
public class City {
private String name;
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
this is Location.java
public class Location {
private String name;
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
this is Config.java
public class Config {
//JSON URL
public static final String DATA_URL = "http://demo5...../get_country.php";
public static final String DATA_URL1 = "http://demo5...../get_jsoncity.php?id=";
//Tags used in the JSON String
public static final String DATA_URL2 = "http://demo5...../get_jsonlocation.php?id=";
//Tags used in the JSON String
//JSON array name
public static final String JSON_ARRAY = "result";
}
this is my json for 1st spinner:
[
{
"id": "1",
"country": "UAE"
},
{
"id": "2",
"country": "UK"
},
{
"id": "3",
"country": "SAUDI ARABIA"
},
{
"id": "4",
"country": "OMAN"
},
{
"id": "5",
"country": "BAHRAIN"
},
{
"id": "6",
"country": "INDIA"
}
]
this is for city if i selected id=1
[
{
"id": "1",
"city_name": "Abu Dhabi"
},
{
"id": "2",
"city_name": "Dubai"
},
{
"id": "3",
"city_name": "Sharjah"
},
{
"id": "4",
"city_name": "Ajman"
},
{
"id": "5",
"city_name": "Ummal Qwain"
}
]
I am already getting 1st spinner item i.e Country , i need to get item for city(2nd spinner) and location(3rd spinner) as per selection of 1st spinner.

Your country.class should have getter setter of city and location.
public class Country {
private String name;
private String id;
private Location loc;
ArrayList<City> Cityarr = new ArrayList<City>();
public ArrayList<City> getCityarr() {
return Cityarr;
}
public void setCityarr(ArrayList<City> Citya) {
this.Cityarr = Citya;
}
public Country(String id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public Location getLocation() {
return loc;
}
#Override
public String toString() {
return name;
}
}
and spinner.OnItemSelectedLisenter should nested
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
vbopr.get(i).getCityarr().size();
cityname.clear();
cityname.add("All");
for (int j = 0; j < vbopr.get(i).getCityarr().size(); j++) {
cityname.add(vbopr.get(i).getCityarr().get(j).getCityname());
}
try {
adpcity.notifyDataSetChanged();
} catch (NullPointerException ne) {
}
adpcity = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_items, cityname);
city.setAdapter(adpcity);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
my url contains data in xml form
example
<world>
<country>
<countryid>2</countryid>
<countryname>India</countryname>
<city>
<city_id>1462</city_id>
<city_name>abc</city_name>
</city>
<city>
<city_id>1460</city_id>
<city_name>def</city_name>
</city>
<city>
<city_id>1461</city_id>
<city_name>jkl PLANT</city_name>
</city>
</country>
<country>
<countryid>3</countryid>
<countryname>Australia</countryname>
<city>
<city_id>1462</city_id>
<city_name>gdfg PLANT</city_name>
</city>
<city>
<city_id>1460</city_id>
<city_name>xdfPLANT</city_name>
</city>
<city>
<city_id>1461</city_id>
<city_name>dfgPLANT</city_name>
</city>
<city>
<city_id>617</city_id>
<city_name>dgvdfgg</city_name>
</city>
</country>
</world>

try this:
spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if (spinner_1.getSelectedItem().equals("UAE")) {
//cal api url here to get data
// set adapter to spinner_2 here for "UAE" selected
} else if (spinner_1.getSelectedItem().equals("UK")) {
//same..
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
);

Related

Failed to convert a value of type java.lang.String to int (in explore_fragment)

Showing error on getValue(User.class) in explore_fragment.
My explore_fragment is:
public class exploreFragment extends Fragment {
FragmentExploreBinding binding;
ArrayList<User> list = new ArrayList<>();
FirebaseAuth auth;
FirebaseDatabase database;
public exploreFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
database= FirebaseDatabase.getInstance();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding= FragmentExploreBinding.inflate(inflater, container, false);
UserAdapter adapter = new UserAdapter(getContext(),list);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
binding.usersRV.setLayoutManager(layoutManager);
binding.usersRV.setAdapter(adapter);
database.getReference().child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
user.setUserID(dataSnapshot.getKey());
if(!dataSnapshot.getKey().equals(FirebaseAuth.getInstance().getUid())){
list.add(user);
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return binding.getRoot();
}
}
User_model is:
public class User {
private String name, profession,email,password,cname;
private String profile;
private String userReff;
private int guidedCount;
private String userID;
private String coverPhoto;
public User() {
}
public int getGuidedCount() {
return guidedCount;
}
public void setGuidedCount(int guidedCount) {
this.guidedCount = guidedCount;
}
public String getCoverPhoto() {
return coverPhoto;
}
public void setCoverPhoto(String coverPhoto) {
this.coverPhoto = coverPhoto;
}
public User(String name, String profession, String email, String password, String cname) {
this.name = name;
this.profession = profession;
this.email = email;
this.password = password;
this.cname = cname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getUserReff() {
return userReff;
}
public void setUserReff(String userReff) {
this.userReff = userReff;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
User_adapter is:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.viewHolder>{
Context context;
ArrayList<User> list;
public UserAdapter(Context context, ArrayList<User> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_sample,parent,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
User user = list.get(position);
Picasso.get().load(user.getProfile()).placeholder(R.drawable.placeholder).into(holder.binding.profileImage);
holder.binding.name.setText(user.getName());
holder.binding.profession.setText(user.getProfession());
holder.binding.viewprofilebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
String visiter = list.get(holder.getAdapterPosition()).getUserID();
Intent intent= new Intent(context, VActivity.class);
intent.putExtra("usersid",visiter).toString();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
UserSampleBinding binding;
public viewHolder(#NonNull View itemView) {
super(itemView);
binding = UserSampleBinding.bind(itemView);
}
}
}
Error i am getting is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.guided_app, PID: 2744
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertInteger(CustomClassMapper.java:364)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToPrimitive(CustomClassMapper.java:290)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:215)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(CustomClassMapper.java:179)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:593)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:563)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:433)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.example.guided_app.fragment.exploreFragment$1.onDataChange(exploreFragment.java:60)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
The firebase database is:
"Users": {
"59fLuGGNugPcgp6b725cFnKIzKC2": {
"cname": "LIT",
"email": "Stephen#gmail.com",
"guidedCount": 0,
"name": "Stephen Wade",
"password": "123456",
"profession": "Developer # Adobe"
},
"7kpNGqcHeBfNqf8GrVK2Hpew0L62": {
"cname": "BIT",
"email": "anshul#gmail.com",
"guided": {
"FOQEVbKRpNYjfzAJCp1XQtnvRlh2": {
"guidedAt": 1670152487063,
"guidedBy": "FOQEVbKRpNYjfzAJCp1XQtnvRlh2"
},
"y3pV1GhdLqOnteMO64U2F4o8mMu2": {
"guidedAt": 1670151228825,
"guidedBy": "y3pV1GhdLqOnteMO64U2F4o8mMu2"
}
},
"guidedCount": 2,
"name": "Anshul Lanjewar",
"password": "123456",
"profession": "SDE # Google"
},
"FOQEVbKRpNYjfzAJCp1XQtnvRlh2": {
"cname": "SIT",
"email": "Tanvi#gmail.com",
"guidedCount": 0,
"name": "Tanvi Colson",
"password": "123456",
"profession": "Analyst # Google"
},
"Jj2RH3iopgdLU6AC3VKeeaMKAXx1": {
"cname": "PIT",
"email": "Shana#gmail.com",
"guidedCount": 0,
"name": "Shana Sharma",
"password": "123456",
"profession": "FullStack # Netflix"
},
"gAzcrP1IYmQI0ht4qfH9WGt9U7F2": {
"cname": "MIT",
"email": "John#gmail.com",
"guided": {
"7kpNGqcHeBfNqf8GrVK2Hpew0L62": {
"guidedAt": 1670614050015,
"guidedBy": "7kpNGqcHeBfNqf8GrVK2Hpew0L62"
}
},
"guidedCount": "gAzcrP1IYmQI0ht4qfH9WGt9U7F2",
"name": "John Adams",
"password": "123456",
"profession": "Developer # Apple"
},
"y3pV1GhdLqOnteMO64U2F4o8mMu2": {
"cname": "BIT",
"email": "kumar#gmail.com",
"guided": {
"7kpNGqcHeBfNqf8GrVK2Hpew0L62": {
"guidedAt": 1670154254299,
"guidedBy": "7kpNGqcHeBfNqf8GrVK2Hpew0L62"
}
},
"guidedCount": 1,
"name": "Kumar Mishra",
"password": "123456",
"profession": "SDE # Microsoft"
}
}
I recently started with android development, so was just stucked.
I want to create an explore_fragment in which list of users is added in recyclerView and with view_profile button we can view user profile.
As expected, the following error:
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
Arrives due to the fact that an int-type field holds a value of type String. So when deserializing, the guidedCount field is expected to hold a value of type int and not String, hence the error. The node that is responsible for the Exception is:
"guidedCount": "gAzcrP1IYmQI0ht4qfH9WGt9U7F2",
See, it holds a UID rather than a number. So to solve this, change that UID with a number.

No setter/getter Firebase

Hi everyone I have one question. I want to retrieve the data from the Firebase live database and it keeps telling me that it doesn't find the getter and the setter but as you can see below I did it, I create a class where I have the setter and the getter with the same name of the database fields.
Can anyone tell me what I'm doing wrong because I don't have a clue?
Thank you in advance.
Photo of the database:
Code of the Activity and the Class where you can see that I have the getter and the setter.
package com.example.ipill;
public class CartActivity extends AppCompatActivity {
private TextView total;
private ImageButton removeFromCart;
private Button pay;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
public static int cart_count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");
total = findViewById(R.id.TotalPrice);
removeFromCart = findViewById(R.id.removeFromCart);
mResultList = findViewById(R.id.cartList);
pay = findViewById(R.id.pay);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
// Attach a listener to read the data at our posts reference
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users_get post = dataSnapshot.getValue(Users_get.class);
System.out.println("DATAAAA: "+post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
#Override
protected void onStart() {
super.onStart();
invalidateOptionsMenu();
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
String nome;
String surname;
Long prezzo;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void getDetails(String name,String cognome,Long price){
nome=name;
surname=cognome;
prezzo=price;
}
public void setDetails(String name, String surname, Long price) {
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
TextView user_price = (TextView)mView.findViewById(R.id.price);
user_name.setText(name);
user_surname.setText(surname);
user_price.setText(Long.toString(price));
}
}
}
CLASS
public class Users_get {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
private String name, surname;
private Long price;
}
JSON structure
{
"Cart": {
"-M0U3UXq2ZA00Jq5o9as": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
},
"-M0WlUbQHj1hdH40uWVF": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
},
"-M0WxZhI98Xb1s9Xy5HV": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
},
"-M0X00Zr64RocyQHhoFB": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
}
},
"Users": {
"01": {
"Name": "Alex",
"Price": 120,
"Surname": "Kyto"
},
"02": {
"Name": "Alex",
"Price": 200,
"Surname": "Pablo"
}
}
}
In addition to other answer, To get Users_get data, according your database structure you have to go one level more.
Currently your database reference pointed to Cart. So iterate through children of cart to get cart data. Check below:
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Users_get post = childSnapshot.getValue(Users_get.class);
System.out.println("DATAAAA: " + post);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Change the class to this:
public class Users_get {
private String name, surname;
private Long price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public Users_get(String name,Long price,String surname) {
this.price = price;
this.name = name;
this.surname = surname;
}
public Users_get() {
}
Since you are using an IDE, then just click generate getters and setters and it will automatically do that for you instead of manually writing the methods..
You get the warning because in your Users_get class you don't have correct getters for your fields. If you have a field named name, the correct getter should be:
public String getName() {
return name;
}
And not:
public String getname() {
return name;
}
See the capital N versus lowercase n? To solve this you should change all the names of all getters in your Users_get class, as explained above.

Get data from nested json object inside json array in android

I am trying to get data from json that work for first portion but not for nested json object.I want to get the province and city from json object.
I am trying to get data from json that work for first portion but not for nested json object.I want to get the province and city from json object.
In province object i want province string and in city i want city string
........................MY JSON.................
{
"ads": [
{
"id": 8,
"title": "Software Engineering",
"description": "A book for software engineers",
"price": 100,
"user_id": 1,
"province_id": 4,
"city_id": 5,
"subject_id": 1,
"level_id": 3,
"active": 1,
"created_at": "2019-04-20 04:35:00",
"updated_at": "2019-04-20 04:35:00",
"province": {
"id": 4,
"province": "Blochistan",
"created_at": null,
"updated_at": null
},
"city": {
"id": 5,
"city": "Quetta",
"province_id": 4,
"created_at": null,
"updated_at": null
}
}
]
}
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.CustomViewHolder> {
private List<Data> adsList;
private Context context;
public AdsAdapter(List<Data> dataList,Context context) {
this.adsList=dataList;
this.context=context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.ads_list, viewGroup, false);
return new CustomViewHolder(itemView,adsList,context);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder customViewHolder, int i) {
Data data = adsList.get(i);
customViewHolder.ad_title.setText(data.getTitle());
customViewHolder.ad_price.setText(data.getPrice().toString());
// customViewHolder.ad_city.setText(();
}
#Override
public int getItemCount() {
return adsList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView ad_title,ad_price,ad_province,ad_city;
private List<Data> adsList;
private Context context;
public CustomViewHolder(#NonNull View itemView,List<Data> adsList,Context context) {
super(itemView);
this.adsList=adsList;
this.context=context;
itemView.setOnClickListener(this);
ad_title = (TextView)itemView.findViewById(R.id.current_page);
ad_price = itemView.findViewById(R.id.ad_price);
ad_province = itemView.findViewById(R.id.province);
ad_city = itemView.findViewById(R.id.city);
}
#Override
public void onClick(View v) {
int position=getAdapterPosition();
Data data = this.adsList.get(position);
Intent intent = new Intent(this.context,AdDetail.class);
intent.putExtra("title",data.getTitle());
intent.putExtra("discrip",data.getDescription());
intent.putExtra("price",data.getPrice().toString());
intent.putExtra("create",data.getCreatedAt().toString());
this.context.startActivity(intent);
}
}
}
my application terminated when i access province string.
Model Class
public class Province {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("province")
#Expose
private String province;
#SerializedName("created_at")
#Expose
private Object createdAt;
#SerializedName("updated_at")
#Expose
private Object updatedAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public Object getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Object createdAt) {
this.createdAt = createdAt;
}
public Object getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Object updatedAt) {
this.updatedAt = updatedAt;
}
}
Call call = api.getAds(parse_subject_id,parse_level_id);
/**
* Enqueue Callback will be call when get response...
*/
call.enqueue(new Callback<SubjectList>() {
#Override
public void onResponse(Call<SubjectList> call, Response<SubjectList> response) {
pDialog.dismiss();
if (response.isSuccessful()) {
/**
* Got Successfully
*/
adsList = response.body().getAds();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_Ads);
adsAdapter = new AdsAdapter(adsList,getApplicationContext());
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(eLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adsAdapter);
/////////////////////////////////////
}
}
#Override
public void onFailure(Call<SubjectList> call, Throwable t) {
pDialog.dismiss();
}
});
hare i am calling the adapter and pass parameters
From city object you can directly get province_id

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) {
}
});
}

Save the edittext data of a dynamic generated forms to server

I have generated dynamic forms according to type i.e String, int and spinner according to the json data provided by backend.
I have created a recylerview adapter and in pojo class I have added extra variable as answer and provided setter method to it.
Now, forms have generated according to type but I need to save data to server. To save data, i need to get each edittext value with respective id and type and I need to loop it but I couldnot do it so. I cannot define the edittext value with its ID and type. I hope you guys will help me.
There are three paramters to post to server,in method callRetrofitSaveForm() i. vendorId, ii. userid
iii. formData, I have problem with param iii because it has its format to pass. I have used retrofit to parse and problem is with third parameter formData.
the value format of third paramter is
[{"id":"24","label":"Customer ID","value":"102"},{"id":"25","label":"Amount","value":"2000"}]
My Adapter
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
HelpForm.FormSetting formSetting=formArrayList.get(position);
final String description = formArrayList.get(position).getLabel();
Log.d("cjjdnjcnjd",description);
if (formSetting.getType().equals("STRING")){
Log.d("dndjkd",String.valueOf(holder.getAdapterPosition()));
holder.textViewString = new TextView(activity);
holder.linearLayout.addView(holder.textViewString);
holder.textViewString.setText(formSetting.getLabel());
holder.textViewString.setPadding(24, 4, 24, 2);
holder.textViewString.setTextColor(context.getResources().getColor(R.color.colorTexts));
holder.textViewString.setTextSize(15);
holder.editTextString = new EditText(activity);
holder.linearLayout.addView(holder.editTextString);
editTextListString.add(holder.editTextString);
}
if (formSetting.getType().equals("INT")){
holder.textViewInt = new TextView(activity);
holder.linearLayout.addView(holder.textViewInt);
holder.textViewInt.setText(formSetting.getLabel());
holder.textViewInt.setPadding(24, 4, 24, 2);
holder.textViewInt.setTextColor(context.getResources().getColor(R.color.colorTexts));
holder.textViewInt.setTextSize(15);
holder.editTextINT = new EditText(activity);
holder.linearLayout.addView(holder.editTextINT);
}
if (formSetting.getType().equals("DATE")){
holder.textViewDate = new TextView(activity);
holder.linearLayout.addView(holder.textViewDate);
holder.textViewDate.setText(formSetting.getLabel());
holder.textViewDate.setPadding(24, 4, 24, 2);
holder.textViewDate.setTextColor(context.getResources().getColor(R.color.colorTexts));
holder.textViewDate.setTextSize(15);
holder.editTextDate = new EditText(activity);
holder.linearLayout.addView(holder.editTextDate);
}
if(formSetting.getType().equals("DROPDOWN")){
holder.textViewSpinner = new TextView(context);
holder.linearLayout.addView(holder.textViewSpinner);
holder.textViewSpinner.setText(formSetting.getLabel());
holder.textViewSpinner.setPadding(16, 4, 8, 4);
holder.spinner = new Spinner(context);
holder.linearLayout.addView(holder.spinner);
ArrayList<String> err = new ArrayList<>();
err = formSetting.getOptions();
holder.spinner.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, err));
}
VendorFormActivity.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callRetrofitSaveForm();
}
});
}
#Override
public int getItemCount() {
return formArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewString,textViewInt,textViewDate;
LinearLayout linearLayout;
EditText editTextString,editTextINT,editTextDate;
Spinner spinner;
TextView textViewSpinner;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout=itemView.findViewById(R.id.dynamiccontainer);
}
}
JSON Response
{
"status": "200",
"message": "success",
"formSetting": [
{
"label": "Customer ID",
"id": 24,
"type": "INT"
},
{
"label": "Amount",
"id": 25,
"type": "INT"
}
]
}
HelpForm
public class HelpForm {
#SerializedName("status")
#Expose
public String status;
#SerializedName("message")
#Expose
public String message;
#SerializedName("formSetting")
#Expose
public ArrayList<FormSetting> formSetting = null;
public ArrayList<FormSetting> getFormSetting() {
return formSetting;
}
public String getStatus() {
return status;
}
public String getMessage() {
return message;
}
public class FormSetting {
#SerializedName("options")
#Expose
public ArrayList<String> options = null;
#SerializedName("label")
#Expose
public String label;
#SerializedName("id")
#Expose
public String id;
#SerializedName("type")
#Expose
public String type;
#SerializedName("answer")
#Expose
public String answer;
public ArrayList<String> getOptions() {
return options;
}
public String getLabel() {
return label;
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
}
public void callRetrofitSaveForm() {
RestClient.RetroInterfaceAPI mInterface = RestClient.getClient();
Call<SaveForm> call = mInterface.getSaveForm( vendorID, userID,formData);
call.enqueue(new Callback<SaveForm>() {
#Override
public void onResponse(Call<SaveForm> call, Response<SaveForm> response) {
if (response.body() != null) {
}
}
#Override
public void onFailure(Call<SaveForm> call, Throwable t) {
}
});
}
}
You can grab the parent view and loop through it and get all editText.
private HashSet<EditText> getTextViews(ViewGroup root){
HashSet<EditText> views=new HashSet<>();
for(int i=0;i<root.getChildCount();i++){
View v=root.getChildAt(i);
if(v instanceof EditText){
views.add((EditText)v);
}else if(v instanceof ViewGroup){
views.addAll(getTextViews((ViewGroup)v));
}
}
return views;
}

Categories