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

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!

Related

Receiving null Parcelable object Android

I'm trying to pass an object from my RecyclerView adapter to a fragment using parcelable. However when I try to receive the data, the bundle is null. I've looked at other examples, but I can't see where I'm going wrong.
Parcelable class
public class Country extends BaseObservable implements Parcelable {
#SerializedName("name")
#Expose
private String name;
#SerializedName("snippet")
#Expose
private String snippet;
#SerializedName("country_id")
#Expose
private String countryId;
#SerializedName("id")
#Expose
private String id;
#SerializedName("coordinates")
#Expose
private Coordinates coordinates;
#SerializedName("images")
#Expose
private List<CountryImage> images;
protected Country(Parcel in) {
name = in.readString();
snippet = in.readString();
}
public static final Creator<Country> CREATOR = new Creator<Country>() {
#Override
public Country createFromParcel(Parcel in) {
return new Country(in);
}
#Override
public Country[] newArray(int size) {
return new Country[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(snippet);
}
#Override
public int describeContents() {
return 0;
}
#Bindable
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
notifyPropertyChanged(BR.countryId);
}
#Bindable
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
notifyPropertyChanged(BR.id);
}
#Bindable
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
notifyPropertyChanged(BR.coordinates);
}
#Bindable
public List<CountryImage> getImages() {
return images;
}
public void setImages(List<CountryImage> images) {
this.images = images;
notifyPropertyChanged(BR.images);
}
#Bindable
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
notifyPropertyChanged(BR.snippet);
}
#Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
RetrofitAdapter.java
public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.MyViewHolder> implements CustomClickListener {
private List<Country> cities;
private CustomClickListener customClickListener;
private View view;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
RetroItemBinding retroItemBinding =
DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
R.layout.retro_item, viewGroup, false);
view = viewGroup;
return new MyViewHolder(retroItemBinding);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.bindTo(cities.get(i));
myViewHolder.retroItemBinding.setItemClickListener(this);
}
#Override
public int getItemCount() {
if (cities != null) {
return cities.size();
} else {
return 0;
}
}
public void setCityList(ArrayList<Country> cities) {
this.cities = cities;
notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private RetroItemBinding retroItemBinding;
public MyViewHolder(#NonNull RetroItemBinding retroItemBinding) {
super(retroItemBinding.getRoot());
this.retroItemBinding = retroItemBinding;
}
void bindTo(Country country) {
retroItemBinding.setVariable(BR.city, country);
retroItemBinding.setVariable(BR.itemClickListener, customClickListener);
retroItemBinding.executePendingBindings();
}
}
public void cardClicked(Country country) {
CountryFragment countryFragment = new CountryFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("Country", country);
countryFragment.setArguments(bundle);
((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction()
.replace(R.id.frag_container, new CountryFragment())
.commit();
}
}
Where I receive attempt to receive the data in CountryFragment.java
Country country;
Bundle bundle = this.getArguments();
if (bundle != null) {
country = bundle.getParcelable("Country");
}
.replace(R.id.frag_container, new CountryFragment())
should be
.replace(R.id.frag_container, countryFragment)
You are creating a second instance instead of passing the one you set the arguments on.

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.

Error getItemCount() Android

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

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"

Using Retrofit 2.0 + RxJava + Realm + RecyclerView saves no data into DB

I'm pretty new to android and third-party libraries, so I have one problem.
I want to store some data coming from REST API into Realm, then show it into RecyclerView. I have three tabs using the same recyclerView, so it can display three different states.
Here's my classes:
public class RealmContentAdapter extends RealmRecyclerViewAdapter<ContentDataModel, RealmContentAdapter.ViewHolder> {
private Context mContext;
public static class ViewHolder extends RecyclerView.ViewHolder{
private ImageView cardIcon;
private TextView likeCounter, cardHeader, cardAddress, cardDate, cardDays;
public ViewHolder(View itemView) {
super(itemView);
this.cardIcon = (ImageView) itemView.findViewById(R.id.card_icon);
this.likeCounter = (TextView) itemView.findViewById(R.id.like_counter);
this.cardHeader = (TextView) itemView.findViewById(R.id.card_header_text);
this.cardAddress = (TextView) itemView.findViewById(R.id.card_address_text);
this.cardDate = (TextView) itemView.findViewById(R.id.card_date_text);
this.cardDays = (TextView) itemView.findViewById(R.id.card_days_text);
}
}
public RealmContentAdapter (Context context, OrderedRealmCollection<ContentDataModel> data){
super(context, data, true);
mContext = context;
}
#Override
public RealmContentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RealmContentAdapter.ViewHolder holder, int position) {
ContentDataModel model = getData().get(position);
holder.likeCounter.setText(String.valueOf(model.getLikesCounter()));
holder.cardHeader.setText(model.getTitle());
holder.cardIcon.setImageResource(R.drawable.nature);
if (model.getGeoAddress() != null){
holder.cardAddress.setText(model.getGeoAddress().getAddress());
} else {
holder.cardAddress.setText("");
}
holder.cardDate.setText(model.getNormalDate());
holder.cardDays.setText(String.valueOf(model.getDays()));
}
public class ContentDataModel extends RealmObject {
#SerializedName("id")
#Expose
private int id;
#SerializedName("user")
#Expose
private User user;
#SerializedName("geo_address")
#Expose
private GeoAddress geoAddress;
#SerializedName("category")
#Expose
private Category category;
#SerializedName("type")
#Expose
private Type type;
#SerializedName("title")
#Expose
private String title;
#SerializedName("body")
#Expose
private String body;
#SerializedName("created_date")
#Expose
private int createdDate;
#SerializedName("start_date")
#Expose
private int startDate;
#SerializedName("state")
#Expose
private State state;
#SerializedName("ticket_id")
#Expose
private String ticketId;
#SerializedName("files")
#Expose
#Ignore
private List<Files> files = new ArrayList<>();
#SerializedName("performers")
#Expose
#Ignore
private List<Performer> performers = new ArrayList<>();
#SerializedName("deadline")
#Expose
private int deadline;
#SerializedName("likes_counter")
#Expose
private int likesCounter;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public GeoAddress getGeoAddress() {
return geoAddress;
}
public void setGeoAddress(GeoAddress geoAddress) {
this.geoAddress = geoAddress;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getCreatedDate() {
return createdDate;
}
public void setCreatedDate(int createdDate) {
this.createdDate = createdDate;
}
public int getStartDate() {
return startDate;
}
public void setStartDate(int startDate) {
this.startDate = startDate;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public String getTicketId() {
return ticketId;
}
public void setTicketId(String ticketId) {
this.ticketId = ticketId;
}
public List<Files> getFiles() {
return files;
}
public void setFiles(List<Files> files) {
this.files = files;
}
public List<Performer> getPerformers() {
return performers;
}
public void setPerformers(List<Performer> performers) {
this.performers = performers;
}
public int getDeadline() {
return deadline;
}
public void setDeadline(int deadline) {
this.deadline = deadline;
}
public int getLikesCounter() {
return likesCounter;
}
public void setLikesCounter(int likesCounter) {
this.likesCounter = likesCounter;
}
public String getNormalDate(){
return DateFormatter.getNormalDate(getStartDate());
}
public String getDays(){
return DateFormatter.getGoneDays(getStartDate());
}
I have some other pojo classes, but this one is the main.
And my Recycler Fragment:
public class RecyclerFragment extends Fragment {
private static final String KEY_FILE = "file";
private RealmContentAdapter mAdapter;
private RealmResults<ContentDataModel> mData;
private RecyclerView mRecyclerView;
private Realm mRealm;
public static Fragment newInstance(String file) {
RecyclerFragment fragment = new RecyclerFragment();
Bundle args = new Bundle();
args.putString(KEY_FILE, file);
fragment.setArguments(args);
return fragment;
}
public String getPage() {
return (getArguments().getString(KEY_FILE));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_fragment_layout, container, false);
mIntent = new Intent(getContext(), CardActivity.class);
mRealm = Realm.getDefaultInstance();
mData = mRealm.where(ContentDataModel.class).findAll();
ApiService apiService = ApiModule.getApiService();
Observable<List<ContentDataModel>> tabOneContent = apiService.loadCards(
getString(R.string.processing_state), 10);
Observable<List<ContentDataModel>> tabTwoContent = apiService.loadCards(
getString(R.string.done_state), 10);
Observable<List<ContentDataModel>> tabThreeContent = apiService.loadCards(
getString(R.string.pending_state), 10);
mRecyclerView = (RecyclerView) view.findViewById(R.id.tab_recycler);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mAdapter = new RealmContentAdapter(getContext(), mData);
mRecyclerView.setAdapter(mAdapter);
if (getPage().equals(getString(R.string.processing_flag))) {
tabOneContent
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<ContentDataModel>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ContentDataModel> dataSet) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(dataSet);
realm.commitTransaction();
realm.close();
}
});
} else if (getPage().equals(getString(R.string.done_flag))) {
tabTwoContent
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<ContentDataModel>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ContentDataModel> dataSet) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(dataSet);
realm.commitTransaction();
realm.close();
}
});
} else if (getPage().equals(getString(R.string.pending_flag))) {
tabThreeContent
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<ContentDataModel>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ContentDataModel> dataSet) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(dataSet);
realm.commitTransaction();
realm.close();
}
});
}
return view;
}
The problem is when I'm trying to save List dataset to Realm, it doesn't save any. And my RealmContentAdapter is empty.
P.S.: I set up GSON carefully and it ignores RealmObject.class
UPD: So, I've found what was wrong. Realm didn't want to save data, because I've missed to add #PrimaryKey to field id in my ContentDataModel. Thank you for attention.

Categories