My recyclerView showing only first user data.but when i check allusers data in my http://localhost/MyApi/public/allusers , it showing 6 user data as a JSON format
This is my JSON Image
Json image
My SingleTon class
public class RetofitClient_SingleTone {
private static final String BASE_URL = "http://192.168.0.100/MyApi/public/";
private static RetofitClient_SingleTone mInstance;
private Retrofit retrofit;
public RetofitClient_SingleTone() {
retrofit=new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetofitClient_SingleTone getInstance(){
if (mInstance==null){
mInstance = new RetofitClient_SingleTone();
}
return mInstance;
}
public Api getApi(){
return retrofit.create(Api.class);
}
}
My Api.class
public interface Api {
#GET("allusers")
Call<UsersResponse> getUsers();
}
2 Model Class
1. My UserResponse.class
public class UsersResponse {
#SerializedName("error")
#Expose
private Boolean error;
#SerializedName("users")
#Expose
private List<User> users = null;
public UsersResponse(boolean error, List<User> users) {
this.error = error;
this.users = users;
}
public boolean isError() {
return error;
}
public List<User> getUsers() {
return users;
}
}
2. My User.class
public class User {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("email")
#Expose
private String email;
#SerializedName("name")
#Expose
private String name;
#SerializedName("school")
#Expose
private String school;
public User(int id, String email, String name, String school) {
this.id = id;
this.email = email;
this.name = name;
this.school = school;
}
public int getId() {
return id;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public String getSchool() {
return school;
}
}
My Adapter Class Users_Adapter .class
public class Users_Adapter extends RecyclerView.Adapter<Users_Adapter.UserViewHolder> {
private Context context;
private List<User> userList;
public Users_Adapter(Context context, List<User> userList) {
this.context = context;
this.userList = userList;
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyler_view_users, parent, false);
return new UserViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
User user = userList.get(position);
Log.e("Name - - - -", "onBindViewHolder: "+user.getName() );
holder.name_TV.setText(user.getName());
holder.email_TV.setText(user.getEmail());
holder.school_TV.setText(user.getSchool());
}
#Override
public int getItemCount() {
return userList.size();
}
//create class that extend ViewHolder class
public class UserViewHolder extends RecyclerView.ViewHolder {
TextView name_TV;
TextView email_TV;
TextView school_TV;
public UserViewHolder(#NonNull View itemView) {
super(itemView);
name_TV = itemView.findViewById(R.id.texview_name);
email_TV = itemView.findViewById(R.id.texview_Email);
school_TV = itemView.findViewById(R.id.texview_school);
}
}
}
MY Fragment Class UsersFragment.class
public class UsersFragment extends Fragment{
RecyclerView recyclerView;
private Users_Adapter adapter;
private List<User> userList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.users_fragment,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView=view.findViewById(R.id.recylerView_id);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
Call<UsersResponse> call= RetofitClient_SingleTone.getInstance().getApi().getUsers();
call.enqueue(new Callback<UsersResponse>() {
#Override
public void onResponse(Call<UsersResponse> call, Response<UsersResponse> response) {
userList = response.body().getUsers();
adapter=new Users_Adapter(getActivity(),userList);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<UsersResponse> call, Throwable t) {
}
});
}
}
I Want to show all user in recyclerView But it Showing only first user
app screenshort
Related
I am using Android Paging with Room Database.I am going to fetch data using retrofit.But I am getting error No adapter attached; skipping layout.I searched a lot but dont find solution for this. Base url is working, for security reason i just hide base url.
private StoreAdapter storeAdapter;
private Store_ViewModel store_viewModel;
private RecyclerView recyclerView;
private static final String URL_DATA="https://xxxx/";
//insertion
private Store_Repository store_repository;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
store_repository=new Store_Repository(getApplication());
//adapter
storeAdapter=new StoreAdapter(getApplicationContext(), this);
//recycler
recyclerView=findViewById(R.id.recycler_store);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
store_viewModel=new ViewModelProvider(this).get(Store_ViewModel.class);
store_viewModel.pagedListLiveData.observe(this, new Observer<PagedList<StoreModel>>() {
#Override
public void onChanged(PagedList<StoreModel> storeModels) {
storeAdapter.submitList(storeModels);
recyclerView.setAdapter(storeAdapter);
}
});
getAllProducts();
}
private void getAllProducts() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(URL_DATA)
.addConverterFactory(GsonConverterFactory.create())
.build();
//calling api
Api api=retrofit.create(Api.class);
Call<List<StoreModel>>call=api.getAllProducts();
call.enqueue(new Callback<List<StoreModel>>() {
#Override
public void onResponse(Call<List<StoreModel>> call, Response<List<StoreModel>> response) {
if (response.isSuccessful())
{
store_repository.insert(response.body());
}
}
#Override
public void onFailure(Call<List<StoreModel>> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something get Wrong", Toast.LENGTH_SHORT).show();
}
});
}
This is my ViewModel Class
public class Store_ViewModel extends AndroidViewModel {
public LiveData<PagedList<StoreModel>>pagedListLiveData;
private StoreDao storeDao;
public Store_ViewModel(#NonNull Application application) {
super(application);
storeDao= StoreDatabase.getINSTANCE(application).storeDao();
pagedListLiveData=new LivePagedListBuilder<>(
storeDao.getAllItems(),5
).build();
}
}
And this is my adapter class
public class StoreAdapter extends PagedListAdapter<StoreModel,StoreAdapter.StoreViewHolder> {
private Context context;
private static Listener listener;
public StoreAdapter(Context context,Listener listener)
{
super(storeModelItemCallback);
this.context=context;
this.listener=listener;
}
#NonNull
#Override
public StoreViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(#NonNull StoreViewHolder holder, int position) {
StoreModel storeModel=getItem(position);
holder.Product_name.setText(storeModel.getProduct_name());
holder.Product_weight.setText(storeModel.getProduct_weight());
holder.Price.setText(storeModel.getPrice());
holder.Mrp.setText(storeModel.getMrp());
}
static class StoreViewHolder extends RecyclerView.ViewHolder
{
TextView Product_name;
TextView Product_weight;
TextView Price;
TextView Mrp;
public StoreViewHolder(#NonNull View itemView) {
super(itemView);
Product_name=itemView.findViewById(R.id.product_name);
Product_weight=itemView.findViewById(R.id.product_weight);
Price=itemView.findViewById(R.id.price);
Mrp=itemView.findViewById(R.id.mrp);
//listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemCLickListener(getAdapterPosition());
}
});
}
}
static DiffUtil.ItemCallback<StoreModel> storeModelItemCallback=new DiffUtil.ItemCallback<StoreModel>() {
#Override
public boolean areItemsTheSame(#NonNull StoreModel oldItem, #NonNull StoreModel newItem) {
return oldItem.getDatabase_id()==newItem.getDatabase_id();
}
#SuppressLint("DiffUtilEquals")
#Override
public boolean areContentsTheSame(#NonNull StoreModel oldItem, #NonNull StoreModel newItem) {
return oldItem.equals(newItem);
}
};
Json Response from Server
{"status":1,"msg":"",
"paginate":{"limit":1000,"PageNo":1},
"data":
[
{
"product_id":23234,
"product_brand_id":130,
"product_name":"Xyz"
,"product_code":"1554729666482",
"mrp":5,
"price":4,
"product_weight":1,
"product_weight_unit":"PCS"
}
,{"product_id":23244,
"product_brand_id":130,
"product_name":"Abc - 100 Gms",
"product_code":"9A","mrp":38,"price":31.94,
"product_weight":100,"product_weight_unit":"GM"}
ApiInterface
public interface Api {
#GET("/get-products")
Call<List<StoreModel>>getAllProducts();
}
Below is my StoreModel in which i am using room database fro creating tables
#Entity(tableName = "store",indices = #Index(value="product_id",unique = true))
public class StoreModel {
#PrimaryKey(autoGenerate = true)
private int database_id;
#SerializedName("product_id")
private int product_id;
#SerializedName("product_brand_id")
private int product_brand_id;
#SerializedName("product_name")
private String product_name;
#SerializedName("product_code")
private int product_code;
#SerializedName("mrp")
private int mrp;
#SerializedName("price")
private int price;
#SerializedName("product_weight")
private int product_weight;
#SerializedName("product_weight_unit")
private String product_weight_unit;
public StoreModel() {
}
public StoreModel(int product_id, int product_brand_id, String product_name, int product_code, int mrp, int price, int product_weight, String product_weight_unit) {
this.product_id = product_id;
this.product_brand_id = product_brand_id;
this.product_name = product_name;
this.product_code = product_code;
this.mrp = mrp;
this.price = price;
this.product_weight = product_weight;
this.product_weight_unit = product_weight_unit;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public int getProduct_brand_id() {
return product_brand_id;
}
public void setProduct_brand_id(int product_brand_id) {
this.product_brand_id = product_brand_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_code() {
return product_code;
}
public void setProduct_code(int product_code) {
this.product_code = product_code;
}
public int getMrp() {
return mrp;
}
public void setMrp(int mrp) {
this.mrp = mrp;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getProduct_weight() {
return product_weight;
}
public void setProduct_weight(int product_weight) {
this.product_weight = product_weight;
}
public String getProduct_weight_unit() {
return product_weight_unit;
}
public void setProduct_weight_unit(String product_weight_unit) {
this.product_weight_unit = product_weight_unit;
}
public int getDatabase_id() {
return database_id;
}
public void setDatabase_id(int database_id) {
this.database_id = database_id;
}
}
Below is Dao class
#Dao
public interface StoreDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(List<StoreModel> storeModels);
#Query("DELETE FROM store")
void deleteAll();
#Query("SELECT * FROM store ORDER BY database_id ASC")
DataSource.Factory<Integer,StoreModel>getAllItems();
}
Set recyclerView.setAdapter(storeAdapter); outside of observer because each time data is observed it will set adapter. So, adapter is attached to recyclerView only once. Like
recyclerView.setAdapter(storeAdapter);
store_viewModel.pagedListLiveData.observe(this, new Observer<PagedList<StoreModel>>() {
#Override
public void onChanged(PagedList<StoreModel> storeModels) {
storeAdapter.submitList(storeModels);
//recyclerView.setAdapter(storeAdapter);
}
});
From the API you are not getting exactly the StoreModel as response. You are getting another object which is StoreModel is a child object. You have to create resposne object like below:
public class ResponseObject{
//#SerializedName("status")
//private int status;
#SerializedName("data")
private List<StoreModel> storeModelList;
//getters and setters goes here
}
And then your interface should be like below as you are expecting
ResponseObject here
public interface Api {
#GET("/get-products")
Call<ResponseObject> getAllProducts();
}
I am trying to make a call to this api and am having difficulty as the response.body() is returning null.
http://demo.museum.vebrary.vn/api/stuff/getall
I want to get stuff name of list and show to my recyclerview.
My model:
public class SOAnswersResponse {
#SerializedName("StuffModels")
#Expose
private List<StuffModel> stuffModels = null;
public List<StuffModel> getStuffModels() {
return stuffModels;
}
public void setStuffModels(List<StuffModel> stuffModels) {
this.stuffModels = stuffModels;
}
and
public class StuffModel {
#SerializedName("STUFFID")
#Expose
private Integer sTUFFID;
#SerializedName("STUFFCODE")
#Expose
private String sTUFFCODE;
#SerializedName("STUFFNAME")
#Expose
private String sTUFFNAME;
#SerializedName("STUFFNOTE")
#Expose
private String sTUFFNOTE;
#SerializedName("STUFFORDER")
#Expose
private Integer sTUFFORDER;
#SerializedName("CUSTOMERID")
#Expose
private String cUSTOMERID;
#SerializedName("EXHIBITS")
#Expose
private List<Object> eXHIBITS = null;
Json response
{
"StuffModels":[
{
"STUFFID":2,
"STUFFCODE":"Gi",
"STUFFNAME":"Giấy",
"STUFFNOTE":"",
"STUFFORDER":2,
"CUSTOMERID":"CAMAU",
"EXHIBITS":[
]
},
ApiUtils Class
public class ApiUtils {
private ApiUtils() {
}
public static final String BASE_URL = "http://demo.museum.vebrary.vn/api/";
public static SOService getSOService() {
return RetrofitClient.getClient(BASE_URL).create(SOService.class);
}
}
Service interface
public interface SOService {
#GET("/stuff/getall")
Call<SOAnswersResponse> getAnswers();
}
RetrofitClient Class
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
My RecyclerView adapter
public class CategogyNameRecyclerViewAdapter extends RecyclerView.Adapter<CategogyNameRecyclerViewAdapter.ViewHolder> {
private List<StuffModel> mItems;
private Context mContext;
private PostItemListener mItemListener;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView titleTv;
PostItemListener mItemListener;
public ViewHolder(View itemView, PostItemListener postItemListener) {
super(itemView);
titleTv = itemView.findViewById(R.id.tvListMenuCategogy);
this.mItemListener = postItemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
StuffModel item = getItem(getAdapterPosition());
this.mItemListener.onPostClick(item.getSTUFFID());
notifyDataSetChanged();
}
}
public CategogyNameRecyclerViewAdapter(Context context, List<StuffModel> posts, PostItemListener itemListener) {
mItems = posts;
mContext = context;
mItemListener = itemListener;
}
#Override
public CategogyNameRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View postView = inflater.inflate(R.layout.item_list_text, parent, false);
ViewHolder viewHolder = new ViewHolder(postView, this.mItemListener);
return viewHolder;
}
#Override
public void onBindViewHolder(CategogyNameRecyclerViewAdapter.ViewHolder holder, int position) {
StuffModel item = mItems.get(position);
TextView textView = holder.titleTv;
textView.setText(item.getSTUFFNAME());
}
#Override
public int getItemCount() {
return mItems.size();
}
public void updateAnswers(List<StuffModel> items) {
mItems = items;
notifyDataSetChanged();
}
private StuffModel getItem(int adapterPosition) {
return mItems.get(adapterPosition);
}
public interface PostItemListener {
void onPostClick(long id);
}
}
And my main activity
public class Testttt extends AppCompatActivity {
private CategogyNameRecyclerViewAdapter mAdapter;
private RecyclerView mRecyclerView;
private SOService mService;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.test );
mService = ApiUtils.getSOService();
mRecyclerView = (RecyclerView) findViewById(R.id.rcvCategogyNameMenuTest);
mAdapter = new CategogyNameRecyclerViewAdapter(this, new ArrayList<StuffModel>(0), new CategogyNameRecyclerViewAdapter.PostItemListener() {
#Override
public void onPostClick(long id) {
Toast.makeText(Testttt.this, "Post id is" + id, Toast.LENGTH_SHORT).show();
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
mRecyclerView.addItemDecoration(itemDecoration);
loadAnswers();
}
public void loadAnswers() {
mService.getAnswers().enqueue(new Callback<SOAnswersResponse>() {
#Override
public void onResponse(Call<SOAnswersResponse> call, Response<SOAnswersResponse> response) {
Toast.makeText(Testttt.this, "333333333333333333"+response.body(), Toast.LENGTH_SHORT).show();
if(response.isSuccessful()) {
mAdapter.updateAnswers(response.body().getStuffModels());
Log.d("AnswersPresenter", "posts loaded from API");
}else {
int statusCode = response.code();
}
}
#Override
public void onFailure(Call<SOAnswersResponse> call, Throwable t) {
showErrorMessage();
Log.d("AnswersPresenter", "error loading from API");
}
});
}
public void showErrorMessage() {
Toast.makeText(this, "Error loading posts", Toast.LENGTH_SHORT).show();
}
}
The first thing that came in my mind:
Your
public static final String BASE_URL = "http://demo.museum.vebrary.vn/api/";
has a "/" at the the end and your
#GET("/stuff/getall")
Call<SOAnswersResponse> getAnswers();
starts with a "/". So there is a double backslash in the url that might leads to the 404 code. Does this solve the problem?
When i call your URL i receive XML. Maybe the API is not configured correctly?
Change your Service interface
public interface SOService {
#GET("stuff/getall")
Call<SOAnswersResponse> getAnswers();
}
it occurred because you have use start with backslash it already added in your base url
I am try to parse this Json array from this site NewsApi and display it in a listView.When I run the app nothing is displaying.Here is my code.What am doing wrong?.I have tried to debug the problem to no avail.
public class NewsApiClient {
public static String API_BASE_URL = "https://newsapi.org/v1/";
public static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create()
);
public static Retrofit retrofit = builder.client(httpClient.build()).build();
NewsApiClient client = retrofit.create(NewsApiClient.class);
}
calling the endpoint?
public interface NewsApiInterface {
//endpoint
#GET("sources")
Call <SourcesResponse> getTechSources(
#Query("language") String language,
#Query("category") String category)
}
I am only using the name,description and category attributes.
public class Source {
#SerializedName("id")
public String id;
#SerializedName("name")
public String name;
#SerializedName("description")
public String description;
#SerializedName("url")
public String url;
#SerializedName("category")
public String category;
#SerializedName("language")
public String language;
#SerializedName("country")
public String country;
}
public class SourcesAdapter extends BaseAdapter {
Context context;
List<Source> sourceList;
public SourcesAdapter( Context context,List<Source> sourceList){
this.context = context;
this.sourceList = sourceList;
}
#Override
public int getCount() {
return sourceList.size();
}
#Override
public Object getItem(int position) {
return sourceList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.sources_list,null);
Source currentsource = sourceList.get(position);
TextView sourcesName = (TextView) convertView.findViewById(R.id.sources_name);
TextView sourcesDescription = (TextView) convertView.findViewById(R.id.sources_description);
TextView sourcesCategory = (TextView) convertView.findViewById(R.id.sources_category);
sourcesName.setText(currentsource.name);
sourcesDescription.setText(currentsource.description);
sourcesCategory.setText(currentsource.category);
return convertView;
}
}
public class SourcesFragment extends Fragment {
ListView listView;
public SourcesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//
//instance of the adapter to this listview
View view = inflater.inflate(R.layout.fragment_sources, container, false);
listView = (ListView)view.findViewById(R.id.list_view_sources) ;
getSources();
return view;
}
public void getSources(){
Retrofit retrofit = NewsApiClient.builder.build();
NewsApiInterface newsApiInterface = retrofit.create(NewsApiInterface.class);
Call<SourcesResponse> sourcesCall = newsApiInterface.getTechSources("en", "technology");
sourcesCall.enqueue(new Callback<SourcesResponse>() {
#Override
public void onResponse(Call<SourcesResponse> call, Response<SourcesResponse> response) {
List<Source> sources = response.body().sources;
SourcesAdapter sourcesAdapter = new SourcesAdapter(getContext(),sources);
listView.setAdapter(sourcesAdapter);
}
#Override
public void onFailure(Call<SourcesResponse> call, Throwable t) {
}
});
}
}
public class SourcesResponse {
#SerializedName("status")
public String status;
#SerializedName("sources")
public List<Source> sources;
}
I have created 3 fragments,the sources fragment is one of them.On the sources fragment i only want to display sources with technology.
Thank you in advance!
In your retrofit's onResponse callback method, you are accessing sources list like response.body().sources. Instead of this in the SourcesResponse , add a getter and setter for sources like this
public List<SourcesResponse> getSources() {
return sources;
}
public void setSources(List<SourcesResponse> sources) {
this.sources = sources;
}
Now go to your onResponse callback of retrofit and change
response.body().sources
to
response.body().getSources()
am trying to add json object on my spinner but its giving proper result as per my way i am following tutoreal of https://inducesmile.com/android/populate-android-spinner-data-from-remote-mysql-database/please suggest me.
#SerializedName("Status")
#Expose
private String status;
#SerializedName("ExpiryDate")
#Expose
private String expiryDate;
#SerializedName("MessagesLeft")
#Expose
private String messagesLeft;
#SerializedName("Users")
#Expose
private List<User> users = null;
#SerializedName("Balance")
#Expose
private String balance;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public String getMessagesLeft() {
return messagesLeft;
}
public void setMessagesLeft(String messagesLeft) {
this.messagesLeft = messagesLeft;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public String getBalance() {
return balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
}
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("username")
#Expose
private String username;
#SerializedName("userid")
#Expose
private String userid;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}
and Adpater Class is that.
public class SpinnerAdapter extends BaseAdapter{
private LayoutInflater layoutInflater;
private List<GetBalance> listData;
private Context context;
public SpinnerAdapter(Context context, List<GetBalance> listData) {
this.context = context;
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listData = listData;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return (GetBalance)listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder spinnerHolder;
if(convertView == null){
spinnerHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.spinner_list, parent, false);
spinnerHolder.spinnerItemList = (TextView)convertView.findViewById(R.id.spinner_list_item);
convertView.setTag(spinnerHolder);
}else{
spinnerHolder = (ViewHolder)convertView.getTag();
}
spinnerHolder.spinnerItemList.setText(listData.get(position).getUsers());
return convertView;
}
class ViewHolder{
TextView spinnerItemList;
}
}
Your are trying to set list data to a TextView view.Instead of that try this statment,where position will the user position that you want to display
spinnerHolder.spinnerItemList.setText(listData.get(position).getUsers().get(position).getUsername());
You are trying to set list to textview which is not possible ,try following code to settext
spinnerHolder.spinnerItemList.setText(listData.get(position).getUsers().get(0).getUsername());
Hi Im trying to show a list from retrofit onResponse and I am using recyclerview inside a fragment. The list shoud show chefs but I got an error from RecyclerView
Conexion Class
public class Conexion {
public static String BASE_URL = "http://10.30.0.133:8091/Service1.asmx/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
EndPoint Interface
public interface EndPointsInterface {
#GET("chef/{idUser}")
Call<ChefResponse> GetChefsCercanos(#Path("idUser") Integer id_usuario);
}
Entity Usuario
public class Usuario {
#SerializedName("id_usuario")
private Integer id_usuario;
#SerializedName("NombreUsuario")
private String NombreUsuario;
#SerializedName("ApellidoUsuario")
private String ApellidoUsuario;
#SerializedName("TelefonoUsuario")
private String TelefonoUsuario;
#SerializedName("Email")
private String Email;
#SerializedName("Contraseña")
private String Contraseña;
#SerializedName("pos_x")
private Double pos_x;
#SerializedName("pos_y")
private Double pos_y;
public Usuario(){}
public Usuario(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y){
this.id_usuario=id_usuario;
this.NombreUsuario=NombreUsuario;
this.ApellidoUsuario=ApellidoUsuario;
this.TelefonoUsuario=TelefonoUsuario;
this.Contraseña=Contraseña;
this.pos_x=pos_x;
this.pos_y=pos_y;
}
public Integer getId_usuario() {
return id_usuario;
}
public void setId_usuario(Integer id_usuario) {
this.id_usuario = id_usuario;
}
public String getNombreUsuario() {
return NombreUsuario;
}
public void setNombreUsuario(String nombreUsuario) {
NombreUsuario = nombreUsuario;
}
public String getApellidoUsuario() {
return ApellidoUsuario;
}
public void setApellidoUsuario(String apellidoUsuario) {
ApellidoUsuario = apellidoUsuario;
}
public String getTelefonoUsuario() {
return TelefonoUsuario;
}
public void setTelefonoUsuario(String telefonoUsuario) {
TelefonoUsuario = telefonoUsuario;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getContraseña() {
return Contraseña;
}
public void setContraseña(String contraseña) {
Contraseña = contraseña;
}
public Double getPos_x() {
return pos_x;
}
public void setPos_x(Double pos_x) {
this.pos_x = pos_x;
}
public Double getPos_y() {
return pos_y;
}
public void setPos_y(Double pos_y) {
this.pos_y = pos_y;
}
}
Entity Chef
public class Chef extends Usuario{
#SerializedName("id_chef")
private Integer id_chef;
#SerializedName("TipoServicio")
private String TipoServicio;
#SerializedName("Rating")
private Double Rating;
#SerializedName("EstadoChef")
private Boolean EstadoChef;
public Chef(){}
public Chef(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y,Integer id_chef,String TipoServicio,Double Rating,Boolean EstadoChef){
super(id_usuario,NombreUsuario,ApellidoUsuario,TelefonoUsuario,Email,Contraseña,pos_x,pos_y);
this.id_chef=id_chef;
this.TipoServicio=TipoServicio;
this.Rating=Rating;
this.EstadoChef=EstadoChef;
}
public Integer getId_chef() {
return id_chef;
}
public void setId_chef(Integer id_chef) {
this.id_chef = id_chef;
}
public String getTipoServicio() {
return TipoServicio;
}
public void setTipoServicio(String tipoServicio) {
TipoServicio = tipoServicio;
}
public Double getRating() {
return Rating;
}
public void setRating(Double rating) {
Rating = rating;
}
public Boolean getEstadoChef() {
return EstadoChef;
}
public void setEstadoChef(Boolean estadoChef) {
EstadoChef = estadoChef;
}
}
Chef Response
public class ChefResponse {
#SerializedName("results")
private Chef[] results;
public Chef[] getresults(){
return results;
}
}
RecyclerView Adapter
public class ListaChefsCercanos extends RecyclerView.Adapter<ListaChefsCercanos.ListaChefsCercanosViewHolder> {
private List<Chef> chefs;
private List<Usuario> usuarios;
private int rowLayout;
private Context context;
#Override
public ListaChefsCercanosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ListaChefsCercanosViewHolder(view);
}
#Override
public void onBindViewHolder(ListaChefsCercanosViewHolder holder, int position) {
holder.nombreschefscerca.setText(chefs.get(position).getNombreUsuario());
holder.ratingchef.setText(chefs.get(position).getRating().toString());
}
#Override
public int getItemCount() {
return chefs.size();
}
public static class ListaChefsCercanosViewHolder extends RecyclerView.ViewHolder{
LinearLayout chefslayout;
TextView nombreschefscerca;
TextView ratingchef;
public ListaChefsCercanosViewHolder(View v){
super(v);
chefslayout=(LinearLayout) v.findViewById(R.id.cheflayoutcerca);
nombreschefscerca=(TextView) v.findViewById(R.id.tv_NombreChefCercano);
ratingchef=(TextView) v.findViewById(R.id.tv_RatingChefCercano);
}
}
public ListaChefsCercanos(ArrayList <Chef> chefs){
this.chefs=chefs;
//this.rowLayout = rowLayout;
//this.context = context;
}
}
and the fragment
public class RecomendadosFragment extends Fragment {
private RatingBar ratingBar;
//ListAdapter adapter;
ArrayList<Chef> listachef;
ListView lvLista;
String tag_json_array="jarray req";
RecyclerView recyclerviewChefsCarnos;
ListaChefsCercanos mListaChefsCercanos;
private ArrayList<Chef> data;
private ListaChefsCercanos adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.recomendados,null);
//ratingBar = (RatingBar) x.findViewById(R.id.rb_RatingChefCercano);
recyclerviewChefsCarnos=(RecyclerView) x.findViewById(R.id.rv_chefsCernaos);
recyclerviewChefsCarnos.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
EndPointsInterface apiService = Conexion.getClient().create(EndPointsInterface.class);
Call<ChefResponse> call = apiService.GetChefsCercanos(5);
call.enqueue(new Callback<ChefResponse>() {
#Override
public void onResponse(Call<ChefResponse> call, Response<ChefResponse> response) {
int statusCode = response.code();
if (response.isSuccessful()) {
ChefResponse jsonResponse = response.body();
if(jsonResponse != null) {
data = new ArrayList<>(Arrays.asList(jsonResponse.getresults()));
adapter= new ListaChefsCercanos(data);
recyclerviewChefsCarnos.setAdapter(adapter);
}
} else {
// Do whatever you want if API is unsuccessful.
}
// List<Chef> chefs= response.body().getResults();
// recyclerviewChefsCarnos.setAdapter(new ListaChefsCercanos( chefs,R.layout.itemchefscercanos,getActivity().getApplicationContext()));
}
#Override
public void onFailure(Call<ChefResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
return x;
}
this is the error I found while Im debuging
E/RecyclerView: No adapter attached; skipping layout
Update: Use a empty adapter for the RecyclerView in the OncreateView()
recyclerView.setAdapter(new YourAdapter(getCurrentActivity()));