Error getItemCount() Android - java

6-06 11:18:51.673 2631-2631/com.example.user.helloworld/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.helloworld, PID: 2631
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
I get Error line public class CarAdapter extends RecyclerView.Adapter<CarAdapter.MyViewHolder>{
and line public int getItemCount()
I want to return more than 1 (dataBeen and modelsBeen)
How to fix it ?
thanks for your help ;D
CarAdapter.java
public class CarAdapter extends RecyclerView.Adapter<CarAdapter.MyViewHolder>{
private List<Car.DataBean> dataBeen;
private List<Car.DataBean.ModelsBean> modelsBeen;
public CarAdapter(List<Car.DataBean> dataBeen, List<Car.DataBean.ModelsBean> modelsBeen) {
this.dataBeen = dataBeen;
this.modelsBeen = modelsBeen;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_custom,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.brandname.setText(dataBeen.get(position).getBrand_name());
holder.name.setText(modelsBeen.get(position).getName());
}
#Override
public int getItemCount() {
return dataBeen.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView brandname,name;
public MyViewHolder(View itemView) {
super(itemView);
brandname = (TextView)itemView.findViewById(R.id.textBrandname);
name = (TextView) itemView.findViewById(R.id.txtModelsName);
}
}
}
Car.java
public class Car {
private boolean success;
private List<DataBean> data;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String brand_name;
private List<ModelsBean> models;
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public List<ModelsBean> getModels() {
return models;
}
public void setModels(List<ModelsBean> models) {
this.models = models;
}
public static class ModelsBean {
private String name;
private String detail;
private int price;
private int created_year;
private String image;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getCreated_year() {
return created_year;
}
public void setCreated_year(int created_year) {
this.created_year = created_year;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String URL = "http://xxxx/";
private static final String TAG ="MainActivity";
private RecyclerView recyclerView;
private CarAdapter carAdapter;
List<Car.DataBean> cars;
List<Car.DataBean.ModelsBean> carss;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.Recycler_item);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Accept", "Application/JSON").build();
return chain.proceed(request);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
CarInterface service = retrofit.create(CarInterface.class);
Call<Car> call = service.listCar();
call.enqueue(new Callback<Car>() {
#Override
public void onResponse(Call<Car> call, retrofit2.Response<Car> response) {
Log.d(TAG, "onResponse"+ response.body());
if (response.isSuccessful()){
cars = new ArrayList<Car.DataBean>();
carss = new ArrayList<Car.DataBean.ModelsBean>();
Car result = response.body();
cars = result.getData();
//and I want to show name in Car.DataBean.ModelsBean How to set it?????
carAdapter = new CarAdapter(cars,carss);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(carAdapter);
}
}
#Override
public void onFailure(Call<Car> call, Throwable t) {
}
});
}
}

Related

Search filter on listview of item returns wrong results on item click,

I have a listview getting filtered by an edit text on top. However, when I click on the item searched I get the result of another item being selected.
I Know similar questions are asked and answered by many already, but I went through all the forum but I am breaking my head from long back and sorry newbie much.
Any help will be appreciated.
My adapter:
public class Srv_Adapter extends RecyclerView.Adapter<Srv_Adapter.MyViewHolder> implements Filterable {
List<Srv_Pets> pets, srvPetsFilter;
private Context context;
private RecyclerViewClickListener mListener;
Srv_CustomFilter filter;
public Srv_Adapter(List<Srv_Pets> pets, Context context, RecyclerViewClickListener listener) {
this.pets = pets;
this.srvPetsFilter = pets;
this.context = context;
this.mListener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_srv, parent, false);
return new MyViewHolder(view, mListener);
}
#SuppressLint("CheckResult")
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.mName.setText(pets.get(position).getName());
holder.mType.setText(pets.get(position).getModel() + " / "
+ pets.get(position).getCreated_by());
holder.mDate.setText(pets.get(position).getBirth());
RequestOptions requestOptions = new RequestOptions();
requestOptions.skipMemoryCache(true);
requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
requestOptions.placeholder(R.drawable.logo);
requestOptions.error(R.drawable.logo);
Glide.with(context)
.load(pets.get(position).getPicture())
.apply(requestOptions)
.into(holder.mPicture);
final Boolean love = pets.get(position).getLove();
if (love){
holder.mLove.setImageResource(R.drawable.likeon);
} else {
holder.mLove.setImageResource(R.drawable.likeof);
}
}
#Override
public int getItemCount() {
return pets.size();
}
#Override
public Filter getFilter() {
if (filter==null) {
filter=new Srv_CustomFilter((ArrayList<Srv_Pets>) srvPetsFilter,this);
}
return filter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private RecyclerViewClickListener mListener;
private CircleImageView mPicture;
private ImageView mLove;
private TextView mName, mType, mDate;
private RelativeLayout mRowContainer;
public MyViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
mPicture = itemView.findViewById(R.id.picture);
mName = itemView.findViewById(R.id.name);
mType = itemView.findViewById(R.id.type);
mLove = itemView.findViewById(R.id.love);
mDate = itemView.findViewById(R.id.date);
mRowContainer = itemView.findViewById(R.id.row_container);
mListener = listener;
mRowContainer.setOnClickListener(this);
mLove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.row_container:
mListener.onRowClick(mRowContainer, getAdapterPosition());
break;
case R.id.love:
mListener.onLoveClick(mLove, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowClick(View view, int position);
void onLoveClick(View view, int position);
}
}
Search Menu Activity
public class Service_Main extends AppCompatActivity{
SharedPreferences prf;
Intent intent;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Srv_Adapter srvAdapter;
private List<Srv_Pets> srvPetsList;
Srv_ApiInterface srvApiInterface;
Srv_Adapter.RecyclerViewClickListener listener;
ProgressBar progressBar;
private String userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_main);
srvApiInterface = Srv_ApiClient.getApiClient().create(Srv_ApiInterface.class);
progressBar = findViewById(R.id.progress);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
TextView result = (TextView)findViewById(R.id.result);
recyclerView.setLayoutManager(layoutManager);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(Service_Main.this, loginActivity.class);
userInfo = prf.getString("username",null);
listener = new Srv_Adapter.RecyclerViewClickListener() {
private Srv_Pets getIteamposition(int position)
{
return srvPetsList.get(position);
}
#Override
public void onRowClick(View view, final int position) {
Intent intent = new Intent(Service_Main.this, Service_edit.class);
intent.putExtra("id", srvPetsList.get(position).getId());
intent.putExtra("name", srvPetsList.get(position).getName());
intent.putExtra("species", srvPetsList.get(position).getSpecies());
intent.putExtra("jobcard", srvPetsList.get(position).getJobcard());
intent.putExtra("model_code", srvPetsList.get(position).getModel_code());
intent.putExtra("picture", srvPetsList.get(position).getPicture());
intent.putExtra("birth", srvPetsList.get(position).getBirth());
intent.putExtra("entry_mode", srvPetsList.get(position).getEntry_mode());
intent.putExtra("pickup_done_by_code", srvPetsList.get(position).getPickup_done_by_code());
intent.putExtra("drop_mode", srvPetsList.get(position).getDrop_mode());
intent.putExtra("service_type", srvPetsList.get(position).getDrop_mode());
intent.putExtra("drop_done_by_code", srvPetsList.get(position).getDrop_done_by_code());
intent.putExtra("pick_emp_name", srvPetsList.get(position).getPick_emp_name());
intent.putExtra("drop_emp_name", srvPetsList.get(position).getDrop_emp_name());
startActivity(intent);
final int id = srvPetsList.get(position).getId();
final Boolean love = srvPetsList.get(position).getLove();
final ImageView mLove = view.findViewById(R.id.love);
if (love){
mLove.setImageResource(R.drawable.likeof);
srvPetsList.get(position).setLove(false);
updateLove("Rd_status", id, false);
srvAdapter.notifyDataSetChanged();
} else {
mLove.setImageResource(R.drawable.likeon);
srvPetsList.get(position).setLove(true);
updateLove("Rd_status", id, true);
srvAdapter.notifyDataSetChanged();
}
}
#Override
public void onLoveClick(View view, int position) {
// final int id = srvPetsList.get(position).getId();
// final Boolean love = srvPetsList.get(position).getLove();
// final ImageView mLove = view.findViewById(R.id.love);
// if (love){
// mLove.setImageResource(R.drawable.likeof);
// srvPetsList.get(position).setLove(false);
// updateLove("Rd_status", id, false);
// srvAdapter.notifyDataSetChanged();
// } else {
// mLove.setImageResource(R.drawable.likeon);
// srvPetsList.get(position).setLove(true);
// updateLove("Rd_status", id, true);
// srvAdapter.notifyDataSetChanged();
// }
}
};
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Service_Main.this, Service_edit.class));
}
});
FloatingActionButton fab1 = findViewById(R.id.log_out);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Service_Main.this, HomePage.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName())
);
searchView.setQueryHint("Search Pet...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String query) {
srvAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
srvAdapter.getFilter().filter(newText);
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getPets(){
String username = userInfo;
Call<List<Srv_Pets>> call = srvApiInterface.getPets(username);
call.enqueue(new Callback<List<Srv_Pets>>() {
#Override
public void onResponse(Call<List<Srv_Pets>> call, Response<List<Srv_Pets>> response) {
progressBar.setVisibility(View.GONE);
srvPetsList = response.body();
Log.i(Service_Main.class.getSimpleName(), response.body().toString());
srvAdapter = new Srv_Adapter(srvPetsList, Service_Main.this, listener);
recyclerView.setAdapter(srvAdapter);
srvAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<Srv_Pets>> call, Throwable t) {
Toast.makeText(Service_Main.this, "rp :"+
t.getMessage().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
public void updateLove(final String key, final int id, final Boolean love){
String night_updated_by = userInfo;
String reg_num = userInfo;
Call<Srv_Pets> call = srvApiInterface.updateLove(key, id, love, night_updated_by, reg_num);
call.enqueue(new Callback<Srv_Pets>() {
#Override
public void onResponse(Call<Srv_Pets> call, Response<Srv_Pets> response) {
Log.i(Service_Main.class.getSimpleName(), "Response "+response.toString());
String value = response.body().getValue();
String message = response.body().getMassage();
if (value.equals("1")){
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Srv_Pets> call, Throwable t) {
Toast.makeText(Service_Main.this, t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
getPets();
}
}
List of Items from PHP, MYSQL using Volly
package com.haerul.mypets.service;
import com.google.gson.annotations.SerializedName;
public class Srv_Pets {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
#SerializedName("species")
private String species;
#SerializedName("breed")
private String breed;
#SerializedName("model_code")
private int model_code;
#SerializedName("jobcard")
private int jobcard;
#SerializedName("birth")
private String birth;
#SerializedName("picture")
private String picture;
#SerializedName("love")
private Boolean love;
#SerializedName("value")
private String value;
#SerializedName("message")
private String massage;
#SerializedName("model")
private String model;
#SerializedName("entry_mode")
private int entry_mode;
#SerializedName("drop_mode")
private int drop_mode;
#SerializedName("pickup_done_by_code")
private String pickup_done_by_code;
#SerializedName("service_type")
private int service_type;
#SerializedName("drop_done_by_code")
private String drop_done_by_code;
#SerializedName("pick_emp_name")
private String pick_emp_name;
#SerializedName("drop_emp_name")
private String drop_emp_name;
#SerializedName("created_by")
private String created_by;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public int getModel_code() {
return model_code;
}
public void setModel_code(int gender) {
this.model_code = model_code;
}
public int getJobcard() {
return jobcard;
}
public void setJobcard(int jobcard) {
this.jobcard = jobcard;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public Boolean getLove() {
return love;
}
public void setLove(Boolean love) {
this.love = love;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getEntry_mode(){
return entry_mode;
}
public void setEntry_mode(int entry_mode){
this.entry_mode = entry_mode;
}
public String getPickup_done_by_code() {
return pickup_done_by_code;
}
public void setPickup_done_by_code(String pickup_done_by_code) {
this.pickup_done_by_code = pickup_done_by_code;
}
public int getDrop_mode(){
return drop_mode;
}
public void setDrop_mode(int drop_mode){
this.drop_mode = drop_mode;
}
public int getService_type(){
return service_type;
}
public void setService_type(){
this.service_type = service_type;
}
public String getDrop_done_by_code(){
return drop_done_by_code;
}
public void setDrop_done_by_code(String drop_done_by_code){
this.pickup_done_by_code = drop_done_by_code;
}
public String getPick_emp_name(){
return pick_emp_name;
}
public void setPick_emp_name(String pick_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getDrop_emp_name(){
return drop_emp_name;
}
public void setDrop_emp_name(String drop_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getCreated_by(){
return created_by;
}
public void setCreated_by(String created_by){
this.created_by = created_by;
}
}

Display items on recycler view using retrofit 2

API Json
{
"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
}
}
GET Method
#GET(WebServices.GET_ACTIVE_SUBJECT)
Call<SubjectTopics> getSubjects();
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;
}
}
#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 Class
public class DataAdapter extend
RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<Subjects> android;
private Context context;
public DataAdapter(ArrayList<Subjects> android,Context context) {
this.android = android;
this.context = context;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.subject_topic_list_row,
viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, final int position) {
viewHolder.subjectName.setText(android.get(position).getName());
viewHolder.relativeClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SubjectTopicList.class);
intent.putExtra("subject_id", android.get(position).getSubjId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Picasso.with(context)
.load(android.get(position).getImg())
.placeholder(R.drawable.load)
.into(viewHolder.ImageV);
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView subjectName;
private TextView ID;
private ImageView ImageV;
private RelativeLayout relativeClick;
public ViewHolder(View view) {
super(view);
subjectName = (TextView) itemView.findViewById(R.id.textView);
relativeClick = (RelativeLayout) itemView.findViewById(R.id.relative_click);
ImageV = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
Main Activity
private void initViews() {
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(UnitTestSubjects.this);
recyclerView.setLayoutManager(layoutManager);
if (NetworkUtils.isNetworkAvailableToastIfNot(getApplicationContext())) {
getSubjects();
}
}
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<Example> response) {
if (response.isSuccessful()) {
SubjectTopics jsonResponse = response.body();
list = new ArrayList<Subjects>(jsonResponse.getData().getSubjects());
adapter = new DataAdapter(list);
recyclerView.setAdapter(adapter);
} 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<Example> call, Throwable t) {
t.printStackTrace();
Toast.makeText(UnitTestSubjects.this, "Please Try Again", Toast.LENGTH_SHORT).show();
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
I am beginner in android Retrofit2 API call.
How to fetch items and set in recycler view .I think am not getting how to set items to the adapter class.
please help me out with this.
I have tried all possible ways to solve but not able to find any solution regarding this.
You have error with your models. They aren't properly configured. Please see this tutorial for a better understanding of retrofit and recyclerview.

How to receive a Json array ("result") with retrofit2

I know how to receive arrays when they are this type:
[
{
"username": "luis",
"job": "developer",
"age": 23
}
]
my problem is when I must receive an array with a specific name like this:
{"result":[{"userid":"1","username":"Luis","job":"developer","age":"23"}]}
in this case I must receive the array above with the name "result" using retrofit2. Can anyone please help me I'm new at Retrofit.
This is what I have tried:
MainActivity
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<Workers>> call = apiInterface.getWorkers();
call.enqueue(new Callback<List<Workers>>() {
#Override
public void onResponse(Call<List<Workers>> call, Response<List<Workers>> response) {
list=response.body();
adapter = new WorkerAdapter(getApplicationContext(),list);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<List<Workers>> call, Throwable t) {
}
});
ApiClient:
public class ApiClient {
public static final String BASE_URL="http://192.168.31.206/test1_database/";
public static Retrofit retrofit = null;
public static Retrofit getApiClient(){
if (retrofit==null){
retrofit=new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
ApiInterface:
public interface ApiInterface {
#GET("getAllUser.php")
Call<List<Workers>> getWorkers();
}
my POJO or Workers class:
public class Workers {
#SerializedName("username")
String Name;
#SerializedName("job")
String Job;
#SerializedName("age")
int Age;
public String getName() {
return Name;
}
public String getJob() {
return Job;
}
public int getAge() {
return Age;
}
}
and finally my RecyclerAdpter:
public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.ViewHolder>{
Context context;
List<Workers> list;
public WorkerAdapter(Context context,List<Workers> list) {
this.context = context;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item_recycler,parent,false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(list.get(position).getName());
holder.job.setText(list.get(position).getJob());
holder.age.setText(String.valueOf(list.get(position).getAge()));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, job, age;
public ViewHolder(View itemView) {
super(itemView);
name= (TextView) itemView.findViewById(R.id.nametxt);
job=(TextView) itemView.findViewById(R.id.jobtxt);
age=(TextView) itemView.findViewById(R.id.agetxt);
}
}
}
I've been stuck for two days now and I still can't solve it. Please help!
create a class model called Result and in Interface class write this code:
#GET("your endpoint")
Call<Result>getResult();
and in Result class write below code:
#SerializedName("result")
private List<UserInfo> userInfo;
good luck.
package com.example;
import java.util.List;
public class Example {
private List<Result> result = null;
public List<Result> getResult()
{
return result;
}
public void setResult(List<Result> result)
{
this.result = result;
}}
package com.example;
public class Result {
private String userid;
private String username;
private String job;
private String age;
public String getUserid()
{
return userid;
}
public void setUserid(String userid)
{
this.userid = userid;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getJob()
{
return job;
}
public void setJob(String job)
{
this.job = job;
}
public String getAge()
{
return age;
}
public void setAge(String age)
{
this.age = age;
}}
Make some model using this website. I have done these above code using this website.
Now, do this
#Get<"url">
call<Example> get()
if you have to use this json format
{"result":[{"userid":"1","username":"Luis","job":"developer","age":"23"}]}
you have to create two models like this:
class Result {
#SerializedName("result")
#Expose
List<ResultDetail> result;
}
class ResultDetail {
#SerializedName("userid")
#Expose
String userId ;// use int instead
String username;
String job;
String age; // use int instead
}
add GsonConverterFactory to your app build.gradle
com.squareup.retrofit2:converter-gson:2.14
now build retrofit instance :
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("some base url like : www.example.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
YourSerivce service = retrofit.create(YourService.class);
interface YourService {
#GET("someThing") // complete url is www.example.com/api/someThing
Call<Result> getResult();
}
and finally get result like this :
retrofit.getResult().enqueue(.....)
After a lot of testing guided by the 3 answers given and some video tutorial I finally figure it out.
ApiClient:
public class ApiClient {
private static final String BASE_URL="http://192.168.31.206/";
public static Retrofit retrofit = null;
public static ApiInterface instance=null;
public static Retrofit getApiClient(){
if (retrofit==null){
retrofit=new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
public static ApiInterface getInterface(){
if (instance==null){
instance=getApiClient().create(ApiInterface.class);
}
return instance;
}
}
ApiInterface:
public interface ApiInterface {
//this could be test1_database/getAllUser.json
#GET("test1_database/getAllUser.php")
Call<Result> getWorkers();
}
Workers (POJO) class:
public class Workers {
#SerializedName("userid")
private String userid;
#SerializedName("username")
private String username;
#SerializedName("job")
private String job;
#SerializedName("age")
private String age;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Result (POJO) class:
public class Result {
#SerializedName("result")
private List<Workers> result = null;
public List<Workers> getResult() {
return result;
}
public void setResult(List<Workers> result) {
this.result = result;
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
List<Workers> list = new ArrayList<>();
WorkerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
ApiInterface apiCall = ApiClient.getInterface();
Call<Result> call = apiCall.getWorkers();
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
list = response.body().getResult();
adapter = new WorkerAdapter(MainActivity.this,list);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
}}
I am Showing the results in a recyclerview using this adapter:
public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.ViewHolder>{
Context context;
List<Workers> list;
public WorkerAdapter(Context context,List<Workers> list) {
this.context = context;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item_recycler,parent,false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.id.setText(String.valueOf(list.get(position).getUserid()));
holder.name.setText(list.get(position).getUsername());
holder.job.setText(list.get(position).getJob());
holder.age.setText(String.valueOf(list.get(position).getAge()));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, job, age,id;
public ViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.idtxt);
name= (TextView) itemView.findViewById(R.id.nametxt);
job=(TextView) itemView.findViewById(R.id.jobtxt);
age=(TextView) itemView.findViewById(R.id.agetxt);
}
}
}
Thanks everyone for your help!

E/RecyclerView: No adapter attached; skipping layout . I can not find any answer for this error

This is the Data model
package com.basirahmad.qpaisa.data_model;
public class Banner_data_model {
private String banner_url_com_logo;
private String banner_txt_title;
private String banner_txt_name;
private String banner_txt_description;
private String banner_url_banner;
private String banner_date_publish;
private String banner_date_expire;
private String banner_max_view;
private int banner_com_id;
private int banner_schedual_id;
private int banner_id;
public String getBanner_url_com_logo() {
return banner_url_com_logo;
}
public void setBanner_url_com_logo(String banner_url_com_logo) {
this.banner_url_com_logo = banner_url_com_logo;
}
public String getBanner_txt_title() {
return banner_txt_title;
}
public void setBanner_txt_title(String banner_txt_title) {
this.banner_txt_title = banner_txt_title;
}
public String getBanner_txt_name() {
return banner_txt_name;
}
public void setBanner_txt_name(String banner_txt_name) {
this.banner_txt_name = banner_txt_name;
}
public String getBanner_txt_description() {
return banner_txt_description;
}
public void setBanner_txt_description(String banner_txt_description) {
this.banner_txt_description = banner_txt_description;
}
public String getBanner_url_banner() {
return banner_url_banner;
}
public void setBanner_url_banner(String banner_url_banner) {
this.banner_url_banner = banner_url_banner;
}
public String getBanner_date_publish() {
return banner_date_publish;
}
public void setBanner_date_publish(String banner_date_publish) {
this.banner_date_publish = banner_date_publish;
}
public String getBanner_date_expire() {
return banner_date_expire;
}
public void setBanner_date_expire(String banner_date_expire) {
this.banner_date_expire = banner_date_expire;
}
public String getBanner_max_view() {
return banner_max_view;
}
public void setBanner_max_view(String banner_max_view) {
this.banner_max_view = banner_max_view;
}
public int getBanner_com_id() {
return banner_com_id;
}
public void setBanner_com_id(int banner_com_id) {
this.banner_com_id = banner_com_id;
}
public int getBanner_schedual_id() {
return banner_schedual_id;
}
public void setBanner_schedual_id(int banner_schedual_id) {
this.banner_schedual_id = banner_schedual_id;
}
public int getBanner_id() {
return banner_id;
}
public void setBanner_id(int banner_id) {
this.banner_id = banner_id;
}
}
This is the Adapter Class
package com.basirahmad.qpaisa.adapter;
public class Banner_adapter_con extend
RecyclerView.Adapter<Banner_adapter_con.BannerViewHolder> {
private Context context;
private List<Banner_data_model> banner_data_models;
//the class canstractor;
public Banner_adapter_con(Context context, List<Banner_data_model>banner_data_models ){
this.context = context;
this.banner_data_models = banner_data_models;
}
#Override
public BannerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.banner_view,parent,false);
return new BannerViewHolder(view);
}
#Override
public void onBindViewHolder(BannerViewHolder holder, int position) {
Banner_data_model data_model = banner_data_models.get(position);
holder.company_logo.setImageURI(Uri.parse(data_model.getBanner_url_com_logo()));
holder.title.setText(data_model.getBanner_txt_title());
holder.name.setText(data_model.getBanner_txt_name());
holder.description.setText(data_model.getBanner_txt_description());
holder.banner.setImageURI(Uri.parse(data_model.getBanner_url_banner()));
}
#Override
public int getItemCount() {
return banner_data_models.size();
}
public class BannerViewHolder extends RecyclerView.ViewHolder{
private ImageView company_logo;
private ImageView banner;
private TextView title;
private TextView name;
private ReadMoreTextView description;
public BannerViewHolder(View itemView) {
super(itemView);
company_logo = (ImageView) itemView.findViewById(R.id.img_company_logo);
banner = (ImageView) itemView.findViewById(R.id.img_banner);
title = (TextView) itemView.findViewById(R.id.banner_txt_title);
name = (TextView) itemView.findViewById(R.id.banner_txt_name);
description = (ReadMoreTextView) itemView.findViewById(R.id.banner_txt_description);
}
}
}
This is the Fragment Class
package com.basirahmad.qpaisa.Fragment;
public class Banner_fragment extends Fragment {
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.banner_fragment,container,false);
Banner_data_server banner_data_server = new Banner_data_server(this.getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.banner_fragment);
banner_data_server.getBanner(new Banner_data_server.OnbannerRecevid() {
#Override
public void onRecevid(List<Banner_data_model> banner_data_models) {
Banner_adapter banner_adapter =new Banner_adapter(getActivity(),banner_data_models);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
recyclerView.setAdapter(banner_adapter);
}
});
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
It will not throw any error. It just means when you initialized your RecyclerView you've not set its adapter,
IF you still want to remove this warning, you can call
recyclerview.setAdapter(adapter)
just after its initialization. will remove the warning.
how derar this is the class the get data from server i forgot this class to add to the quastion.
enter code here the class code
package com.basirahmad.qpaisa.connect_to_server;
public class Banner_data_server {
private Context context;
public Banner_data_server(Context context){
this.context = context;
}
public void getBanner(final OnbannerRecevid onbannerRecevid){
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, Url_of_server.urlReadBanner, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<Banner_data_model> banner_data_models = new ArrayList<>();
for (int i =0;i<response.length();i++){
Banner_data_model data_model = new Banner_data_model();
try {
JSONObject jsonObject =response.getJSONObject(i);
data_model.setBanner_id(jsonObject.getInt("Banner_id"));
data_model.setBanner_txt_name(jsonObject.getString("Banner_name"));
data_model.setBanner_txt_description(jsonObject.getString("Banner_description"));
data_model.setBanner_url_banner(jsonObject.getString("location"));
data_model.setBanner_schedual_id(jsonObject.getInt("id"));
data_model.setBanner_date_publish(jsonObject.getString("date_publish"));
data_model.setBanner_date_expire(jsonObject.getString("expire_date"));
data_model.setBanner_com_id(jsonObject.getInt("com_id"));
data_model.setBanner_url_com_logo(jsonObject.getString("logo"));
banner_data_models.add(data_model);
} catch (JSONException e) {
e.printStackTrace();
}
}
onbannerRecevid.onRecevid(banner_data_models);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(arrayRequest);
}
public interface OnbannerRecevid{
void onRecevid(List<Banner_data_model> banner_data_models);
}
}

picasso android image not loading

I am trying to get images from an API, and I have written code but images are not loading in emulator
Main activity
public class MainActivity extends ListActivity {
List<Flower> flowerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RestAdapter restadapter = new RestAdapter.Builder().setEndpoint("http://services.hanselandpetal.com").build();
api flowerapi = restadapter.create(api.class);
flowerapi.getData(new Callback<List<Flower>>() {
#Override
public void success(List<Flower> flowers, Response response) {
flowerList = flowers;
adapter adapt = new adapter(getApplicationContext(),R.layout.item_file,flowerList);
setListAdapter(adapt);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_SHORT).show();
}
});
}
In package model I have flower class
public class Flower {
private int productId;
private String name;
private String category;
private String instructions;
private double price;
private String photo;
private Bitmap bitmap;
public Flower() {
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
}
In network package I have api java class
public interface api {
#GET("/feeds/flowers.jason")
public void getData(Callback<List<Flower>>response);
}
And then I have adaptor java class
public class adapter extends ArrayAdapter<Flower> {
String url="http://services.hanselandpetal.com/photos/";
private Context context;
private List<Flower> flowerList;
public adapter(Context context, int resource, List<Flower> objects) {
super(context, resource, objects);
this.context = context;
this.flowerList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_file,parent,false);
Flower flower = flowerList.get(position);
TextView tv = (TextView) view.findViewById(R.id.name);
tv.setText(flower.getName());
ImageView img = (ImageView) view.findViewById(R.id.img);
Picasso.with(getContext()).load(url+flower.getPhoto()).resize(100,100).into(img);
return view;
}
}
I am getting nothing on emulator and it says it failed. Is the fault in emulator.
I have included internet permission in manifest.
Might be blowing up on your #GET annotation param "/feeds/flowers.jason"
try ".json"

Categories