Display items on recycler view using retrofit 2 - java

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.

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

RecyclerView returning null for adapter position [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
in my app i have a Mysql and im getting data with volley and populating recyclerView with it and to be clear i have a Restaurant list that populates the recyclerView and if you long press a restaurant you can add a note to that specific restaurant so i need the restaurant id and its positon because my note table in my dataBase is a child table that is connected to Restaurant table with FK and uses restaurant id as a refrence, i dont know why im getting NPE for the adapter.getPosition please help
MainActivity
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
SwipeRefreshLayout swipeRefreshLayout;
RestaurantAdapter adapter;
List<Restaurant> restaurants = new ArrayList<>();
String request_url = "https://localhost/api/all_fastfoods.php";
String post_url= "https://localhost/api/add_note.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout=findViewById(R.id.swipe_layout);
swipeRefreshLayout.setOnRefreshListener(this);
recyclerView = findViewById(R.id.recycleViewContainer);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
restaurants = new ArrayList<>();
registerForContextMenu(recyclerView);
getData();
NukeSSLCerts.nuke();
}
private void getData() {
swipeRefreshLayout.setRefreshing(true);
sendRequest();
}
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
restaurants.clear();
for (int i = 0; i < response.length(); i++) {
Restaurant restaurant = new Restaurant();
try {
JSONObject jsonObject = response.getJSONObject(i);
restaurant.setId(jsonObject.getInt("restaurant_id"));
restaurant.setName(jsonObject.getString("restaurant_name"));
restaurant.setAddress(jsonObject.getString("restaurant_address"));
restaurant.setImage(jsonObject.getInt("restaurant_image_type"));
restaurant.setHasNote(jsonObject.getBoolean("restaurant_has_note"));
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
Log.i("Error",e.toString());
e.printStackTrace();
}
restaurants.add(restaurant);
}
mAdapter = new RestaurantAdapter(MainActivity.this, restaurants);
recyclerView.setAdapter(mAdapter);
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error:", String.valueOf(error));
}
});
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(jsonArrayRequest);
}
public boolean onContextItemSelected(MenuItem item) {
final Restaurant restaurant= new Restaurant();
if (item.getTitle().equals("Add Note")){
AlertDialog.Builder notepad = new AlertDialog.Builder(MainActivity.this);
LayoutInflater noteInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View notepadView = noteInflater.inflate(R.layout.notes,null,false);
notepad.setView(notepadView);
final AlertDialog notepadDialog = notepad.create();
notepadDialog.getWindow().getAttributes().windowAnimations = R.style.customdialog;
notepadDialog.show();
final EditText notepadedit = notepadView.findViewById(R.id.notepad);
final Button addnote = notepadView.findViewById(R.id.fab);
notepadedit.requestFocus();
addnote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONObject update = new JSONObject();
JSONObject postparams = new JSONObject();
try {
postparams.put("Content-Type", "application/json");
postparams.put("Accept", "application/json");
postparams.put("note_content",notepadedit.getText());
postparams.put("note_date_time",System.currentTimeMillis());
postparams.put("restaurant_id",restaurants.get(adapter.getPosition()).getId());
update.put("restaurant_has_note",true);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, post_url, postparams, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "SuccessFull", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("PostLog", String.valueOf(error));
}
}
RecyclerView Adapter
public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.MyViewHolder> implements View.OnClickListener{
private Context context;
private List<Restaurant> restaurantList;
private int position;
public int getPosition() {return position;}
public void setPosition(int position) {this.position = position; }
public RestaurantAdapter(Context context,List <Restaurant> restaurantList){
this.context = context;
this.restaurantList = restaurantList;
}
#Override
public void onClick(View view){
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
public TextView FastFoodName;
public TextView FastFoodAddress;
ImageView icon,noteIcon;
MyViewHolder(View itemView){
super(itemView);
icon = itemView.findViewById(R.id.type_ic);
FastFoodName = itemView.findViewById(R.id.listview_name);
FastFoodAddress = itemView.findViewById(R.id.listview_address);
noteIcon = itemView.findViewById(R.id.note_icon);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Add Note");
menu.add(0, 2, 1, "All Notes");
}
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
setPosition(holder.getAdapterPosition());
return false;
}
});
Restaurant restaurant = restaurantList.get(position);
holder.FastFoodName.setText(restaurant.getName());
holder.FastFoodAddress.setText(restaurant.getAddress());
switch (restaurant.getImage()){
case 1:
holder.icon.setImageResource(R.drawable.phoneorderr);
break;
case 2:
holder.icon.setImageResource(R.drawable.sitdownn);
break;
case 3:
holder.icon.setImageResource(R.drawable.takeaway);
break;
}
holder.noteIcon.setImageResource(R.drawable.notepadicon);
if(restaurant.isHasNote()){
holder.noteIcon.setVisibility(View.VISIBLE);
}else {
holder.noteIcon.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return restaurantList.size();
}
#Override
public long getItemId(int position) {
return position;
}
}
and My Model class
public class Restaurant implements Serializable {
private int id;
private String name;
private String address;
private int type;
private boolean hasNote = false;
private int image;
public Restaurant() {
}
public Restaurant(String name, String address,int type){
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address,int type){
this.id = id;
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address, int type,int image) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
this.image = image;
}
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 boolean isHasNote(){
return hasNote;
}
public void setHasNote(boolean hasNote){
this.hasNote = hasNote;
}
public String getAddress() { return address;}
public void setAddress(String address) { this.address = address;}
public void setType(int type) {this.type = type;}
public int getType() {return type;}
public int getImage() {return image;}
public void setImage(int image) {this.image = image;}
}
You have not initialized adapter. Try to initialize it before use.
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
//remove this
//RecyclerView.Adapter mAdapter;
//User this everywhere
RestaurantAdapter adapter;
.....
public void sendRequest() {
....
adapter = new RestaurantAdapter(MainActivity.this, restaurants);
recyclerView.setAdapter(adapter);
....
}
}

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!

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

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