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
Related
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.
I am trying to parse a Block of JSON into a RecyclerView. So far I was able to achieve this with a quite flat JSON Structure. But now I have an Array-Entry in my JSON File where I always want to get the first Entry.
The JSON looks like this:
[
{
"MatchID": 60989,
"Team1": {
"TeamName": "FC Bayern München",
"TeamIconUrl": "https://i.imgur.com/jJEsJrj.png"
},
"Team2": {
"TeamName": "VfL Wolfsburg",
"TeamIconUrl": "https://i.imgur.com/ucqKV4B.png"
},
"MatchResults": [
{
"PointsTeam1": 4,
"PointsTeam2": 0,
"ResultOrderID": 1
},
{
"PointsTeam1": 1,
"PointsTeam2": 0,
"ResultOrderID": 2
}
]
},
{
"MatchID": 60990,
"Team1": {
"TeamName": "VfL Bochum",
"TeamIconUrl": "https://i.imgur.com/5jy3Gfr.png"
},
"Team2": {
"TeamName": "1. FC Union Berlin",
"TeamIconUrl": "https://upload.wikimedia.org/wikipedia/commons/4/44/1._FC_Union_Berlin_Logo.svg"
},
"MatchResults": [
{
"PointsTeam1": 0,
"PointsTeam2": 1,
"ResultOrderID": 1
},
{
"PointsTeam1": 0,
"PointsTeam2": 1,
"ResultOrderID": 2
}
]
}
]
My Activity fetches this JSON from an API using Retrofit2
private void parseJson() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.openligadb.de/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<List<Match>> call=request.getMatchJson();
call.enqueue(new Callback<List<Match>>() {
#Override
public void onResponse(Call<List<Match>> call, Response<List<Match>> response) {
if (response.isSuccessful() && response.body() != null) {
matchList = new ArrayList<>(response.body());
matchAdapter = new MatchAdapter(matchList, ActivityMatch.this);
mRecyclerView.setAdapter(matchAdapter);
}
}
#Override
public void onFailure(Call<List<Match>> call, Throwable t) {
Log.println(Log.ERROR, "FAILED", String.valueOf(t));
Toast.makeText(ActivityMatch.this, "Oops! Somehting went wrong!", Toast.LENGTH_SHORT).show();
}
});
}
My MatchAdapter is then parsing this Data for the View. Here I want to display whatever is the first in MatchResults then using PointsTeam1 and PointsTeam2 to display something like "4 : 0"
Now in my ModelClass accessing direct Values like the TeamName and TeamIconUrl worked but I am struggeling to get to the first entry of the Array and am really stuck on even how to properly approach this issue.
The Adapter Class:
public class MatchAdapter extends RecyclerView.Adapter<MatchAdapter.MatchHolder>{
private ArrayList<Match> matchList;
private Context context;
public MatchAdapter(ArrayList<Match> matchList, Context context) {
this.context = context;
this.matchList = matchList;
}
#NonNull
#Override
public MatchAdapter.MatchHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.match_list_row_layout, viewGroup, false);
return new MatchHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MatchAdapter.MatchHolder holder, int position) {
holder.tvTeam1name.setText(matchList.get(position).Team1.TeamName);
holder.tvTeam2name.setText(matchList.get(position).Team2.TeamName);
Glide.with(context).load(matchList.get(position).Team1.TeamIconUrl).into(holder.ivTeam1Logo);
Glide.with(context).load(matchList.get(position).Team2.TeamIconUrl).into(holder.ivTeam2Logo);
//This is not working
holder.tvResult.setText(matchList.get(position).MatchResults.PointsTeam1 + " : " + matchList.get(position).MatchResults.PointsTeam2);
}
#Override
public int getItemCount() {
return matchList.size();
}
public class MatchHolder extends RecyclerView.ViewHolder {
private TextView tvTeam1name, tvTeam2name, tvResult;
private ImageView ivTeam1Logo, ivTeam2Logo;
public MatchHolder(#NonNull View itemView) {
super(itemView);
tvTeam1name = itemView.findViewById(R.id.tv_team1name);
tvTeam2name = itemView.findViewById(R.id.tv_team2name);
tvResult = itemView.findViewById(R.id.tv_result);
ivTeam1Logo = itemView.findViewById(R.id.iv_team1logo);
ivTeam2Logo = itemView.findViewById(R.id.iv_team2logo);
}
}
}
My ModelClass (Left out Getters/Setters for Readability)
package de.eahjena.app.wi.fussball;
public class Match {
Team Team1;
Team Team2;
MatchResults MatchResults;
public Match(Team Team1, Team Team2, MatchResults MatchResults) {
this.Team1 = Team1;
this.Team2 = Team2;
this.MatchResults = MatchResults;
}
}
class Team {
String TeamName;
String TeamIconUrl;
public Team (String TeamName, String TeamIconUrl) {
this.TeamName = TeamName;
this.TeamIconUrl = TeamIconUrl;
}
}
class MatchResults {
String PointsTeam1;
String PointsTeam2;
public MatchResults(String PointsTeam1, String PointsTeam2) {
this.PointsTeam1 = PointsTeam1;
this.PointsTeam2 = PointsTeam2;
}
}
As per the question you are suppose to use List<MatchResults> MatchResults since the API response contains a list of match results.
Further to use the first position from the matchResults array you cna use it like this in your adapter :
matchList.get(position).MatchResults.get(0).PointsTeam1
API File
METHOD : GET
OUTPUT:
{
"status": true,
"message": "Subjects found.",
"data": {
"subjects": [
{
"subj_id": "2",
"name": "Maths",
"img": "Math.jpg"
},
{
"subj_id": "1",
"name": "Physics",
"img": "physics.png"
}
],
"total": 2
}
}
Model Class
public class SubjectTopics
{
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
private Data data;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public class Data {
#SerializedName("subjects")
#Expose
private List<Subjects> subjects = null;
#SerializedName("total")
#Expose
private Integer total;
public List<Subjects> getSubjects() {
return subjects;
}
public void setSubjects(List<Subjects> subjects) {
this.subjects = subjects;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Subjects {
#SerializedName("subj_id")
#Expose
private String subjId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("img")
#Expose
private String img;
public String getSubjId() {
return subjId;
}
public void setSubjId(String subjId) {
this.subjId = subjId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
My Adapter
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<Subjects> movies;
private int rowLayout;
private Context context;
public static class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView subjectName;
private TextView ID;
private ImageView ImageV;
private RelativeLayout relativeClick;
public MovieViewHolder(View v) {
super(v);
subjectName = (TextView) itemView.findViewById(R.id.textView);
relativeClick = (RelativeLayout) itemView.findViewById(R.id.relative_click);
ImageV = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public MoviesAdapter(List<Subjects> movies, int rowLayout, Context context) {
this.movies = movies;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public MoviesAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new MoviesAdapter.MovieViewHolder(view);
}
#Override
public void onBindViewHolder(MoviesAdapter.MovieViewHolder holder, final int position) {
holder.subjectName.setText(movies.get(position).getName());
holder.relativeClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SubjectTopicList.class);
intent.putExtra("subject_id", movies.get(position).getSubjId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Picasso.with(context)
.load(movies.get(position).getImg())
.placeholder(R.drawable.load)
.into(holder.ImageV);
}
#Override
public int getItemCount() {
return movies.size();
}
}
Activity
private void getSubjects() {
progressBar.setVisibility(View.VISIBLE);
Call<SubjectTopics> getProductsModelClassCall = webService.getSubjects();
getProductsModelClassCall.enqueue(new Callback<SubjectTopics>() {
#Override
public void onResponse(Call<SubjectTopics> call, Response<SubjectTopics> response) {
if (response.isSuccessful()) {
List<Subjects> movies = response.body().getData().getSubjects();
MoviesAdapter newAd=new MoviesAdapter(movies, R.layout.unit_test_row, getApplicationContext());
recyclerView.setAdapter(newAd);
} else {
APIError apiError = ErrorUtils.parseError(response);
Toast.makeText(UnitTestSubjects.this, ""+apiError, Toast.LENGTH_SHORT).show();
}
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SubjectTopics> call, Throwable t) {
Toast.makeText(UnitTestSubjects.this, "Please Try Again", Toast.LENGTH_SHORT).show();
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
Retrofit Code
public class ServiceGenerator {
private final static String TAG = "ApiCall";
public static Retrofit getRetrofit(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
httpClient.connectTimeout(10, TimeUnit.SECONDS).readTimeout(14, TimeUnit.SECONDS).writeTimeout(16, TimeUnit.SECONDS);
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
return new Retrofit.Builder()
.baseUrl(WebServices.BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static Api getApi(){
return getRetrofit().create(Api.class);
}
}
After calling API's using Retrofit 2.0, Unable to get any response and getting this error:
Failure:
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall#5321
every-time after callback it directly coming out from the method
I have tried all possible ways to solve but not able to find any solution regarding this.
I think this is internal retrofit error or in the pojo class I guess. Please help!
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;
}
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) {
}
}
);