Sorry for bothering you guys, but I've following CodingInFlow's MVVM and everything went well until reached the the 7th video, I've created two Activities: MainActivity with a RecyclerView that displays a fake database as per MVVM and a Floating Action button and MainActivity2, whenever I move to MainActivity2 and enter some data and move back to MainActivity, I see that no item have been added to the RecyclerView but the Toasts work.
Ps: I'm new to stackoverflow so pardon me
Here are my Files:
MainActivity
public class MainActivity<O> extends AppCompatActivity {
private ActivityMainBinding mainBinding;
private NoteViewModel viewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(mainBinding.getRoot());
viewModel =new ViewModelProvider(this).get(NoteViewModel.class);
NoteAdapter adapter = new NoteAdapter();
mainBinding.recyclerView.setAdapter(adapter);
mainBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
mainBinding.recyclerView.setHasFixedSize(true);
viewModel.getAllNotes().observe(this, adapter::setList);
ActivityResultLauncher<Intent> resultLauncher =registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == Activity.RESULT_OK){
String title =result.getData().getStringExtra(MainActivity2.EXTRA_TITLE_NOTE);
String description =result.getData().getStringExtra(MainActivity2.EXTRA_DESCRIPTION_NOTE);
int priority = result.getData().getIntExtra(MainActivity2.EXTRA_PRIORITY_NOTE, 1);
Note note = new Note(title, description, priority);
viewModel.insertNote(note);
Toast.makeText(this, "Note Saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Note not saved", Toast.LENGTH_SHORT).show();
}
});
mainBinding.addFab.setOnClickListener(v -> {
resultLauncher.launch(new Intent(MainActivity.this, MainActivity2.class));
});
}
}
MainActivity2
public class MainActivity2 extends AppCompatActivity {
public static final String EXTRA_TITLE_NOTE = "title";
public static final String EXTRA_DESCRIPTION_NOTE = "description";
public static final String EXTRA_PRIORITY_NOTE = "1";
private ActivityMain2Binding mainBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainBinding = ActivityMain2Binding.inflate(getLayoutInflater());
setContentView(mainBinding.getRoot());
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
mainBinding.numPicker.setMinValue(0);
mainBinding.numPicker.setMaxValue(10);
setTitle("Add Note");
}
private void extractInputAndFinish() {
String title = mainBinding.editTitle.getText().toString();
String description = mainBinding.editDescription.getText().toString();
int priority = mainBinding.numPicker.getValue();
Intent data = new Intent(this, MainActivity.class);
data.putExtra(EXTRA_TITLE_NOTE, title);
data.putExtra(EXTRA_DESCRIPTION_NOTE, description);
data.putExtra(EXTRA_PRIORITY_NOTE, priority);
setResult(Activity.RESULT_OK, data);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.note_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.note_save:
extractInputAndFinish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Note
#Entity(tableName = "note_table")
public class Note {
private String title;
private String description;
private int priority;
#PrimaryKey(autoGenerate = true)
private int id;
public Note(String title, String description, int priority) {
this.title = title;
this.description = description;
this.priority = priority;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public int getPriority() {
return priority;
}
public int getId() {
return id;
}
}
NoteDao
#Dao
interface NoteDao {
#Insert
void insertNote(Note note);
#Update
void updateNote(Note note);
#Delete
void deleteNote(Note note);
#Query("DELETE FROM note_table")
void deleteALlNotes();
#Query("SELECT * FROM note_table ORDER BY id ")
LiveData<List<Note>> getAllNotes();
}
NoteDatabase
#Database(entities = {Note.class}, version = 1)
public abstract class NoteDatabase extends RoomDatabase{
public static NoteDatabase instance;
public abstract NoteDao getDao();
public static synchronized NoteDatabase createDatabase(Context context){
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(),
NoteDatabase.class, "file"
)
.fallbackToDestructiveMigration()
.addCallback(callback)
.build();
}
return instance;
}
public static RoomDatabase.Callback callback = new Callback() {
#Override
public void onCreate(#NonNull #NotNull SupportSQLiteDatabase db) {
super.onCreate(db);
new Thread(() ->{
for (int i = 0; i < 3; i++) {
instance.getDao().insertNote(new Note("title " + i,
"description " + i, new Random().nextInt(10)));
}
}).start();
}
};
}
NoteRepository
public class NoteRepository {
private NoteDao dao;
private LiveData<List<Note>> allNotes;
public NoteRepository(Application application) {
NoteDatabase database = NoteDatabase.createDatabase(application);
dao = database.getDao();
allNotes = dao.getAllNotes();
}
public void insertNote(Note note){
new Thread(() -> dao.insertNote(note));
}
public void updateNote(Note note){
new Thread(() -> dao.updateNote(note));
}
public void deleteNote(Note note){
new Thread(() -> dao.deleteNote(note));
}
public void deleteAllNote(){
new Thread(() -> dao.deleteALlNotes());
}
public LiveData<List<Note>> getAllNotes() {
return allNotes;
}
}
NoteViewModel
public class NoteViewModel extends AndroidViewModel{
private NoteRepository repository;
private LiveData<List<Note>> allNotes;
public NoteViewModel(Application application) {
super(application);
repository = new NoteRepository(application);
allNotes = repository.getAllNotes();
}
public LiveData<List<Note>> getAllNotes() {
return allNotes;
}
public void insertNote(Note note){
repository.insertNote(note);
}
public void deleteNote(Note note){
repository.deleteNote(note);
}
public void updateNote(Note note){
repository.updateNote(note);
}
public void deleteAllNotes(){
repository.deleteAllNote();
}
}
NoteAdapter
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> {
private List<Note> list = new ArrayList<>();
public void setList(List<Note> list) {
this.list = list;
notifyDataSetChanged();
}
public List<Note> getList() {
return list;
}
#NonNull
#NotNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_note,
parent, false);
return new NoteViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull #NotNull NoteViewHolder holder, int position) {
Note current = list.get(position);
holder.title.setText(current.getTitle());
holder.description.setText(current.getDescription());
holder.priority.setText(String.valueOf(current.getPriority()));
}
#Override
public int getItemCount() {
return list.size();
}
public static class NoteViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView description;
private TextView priority;
public NoteViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.note_title);
description = itemView.findViewById(R.id.note_desc);
priority = itemView.findViewById(R.id.note_priority);
}
}
}
I've tried to the best of my ability and read through these files multiple but nothing seems to be wrong to me(I'm still a novice).
Thanks in advance
You are nowhere telling the adapter that a new item has been added to the list therefore recycler view does not update. Try doing this,
public class MainActivity<O> extends AppCompatActivity {
private ActivityMainBinding mainBinding;
private NoteViewModel viewModel;
private List<Note> mList;
private NoteAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(mainBinding.getRoot());
viewModel =new ViewModelProvider(this).get(NoteViewModel.class);
adapter = new NoteAdapter();
mainBinding.recyclerView.setAdapter(adapter);
mainBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
mainBinding.recyclerView.setHasFixedSize(true);
viewModel.getAllNotes().observe(this, this::setList);
ActivityResultLauncher<Intent> resultLauncher =registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == Activity.RESULT_OK){
String title =result.getData().getStringExtra(MainActivity2.EXTRA_TITLE_NOTE);
String description =result.getData().getStringExtra(MainActivity2.EXTRA_DESCRIPTION_NOTE);
int priority = result.getData().getIntExtra(MainActivity2.EXTRA_PRIORITY_NOTE, 1);
Note note = new Note(title, description, priority);
viewModel.insertNote(note);
mList.add(note);
adapter.setList(mList);
Toast.makeText(this, "Note Saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Note not saved", Toast.LENGTH_SHORT).show();
}
});
mainBinding.addFab.setOnClickListener(v -> {
resultLauncher.launch(new Intent(MainActivity.this, MainActivity2.class));
});
}
private void setList(List<Note> list){
mList = list;
if (adapter != null){
adapter.setList(list);
}
}
Related
I'm a beginner programmer and I'm trying to receive data from the server using node.js and display the list on Android Studio but I keep having the following error:
E/RecyclerView: No adapter attached; skipping layout
D/HistoryActivity: HistoryResponse{result=[com.sooryong.loginexample.data.HistoryData#3303f3c, com.sooryong.loginexample.data.HistoryData#33764c5]}
D/AndroidRuntime: Shutting down VM
As you can see, I can't recall my list properly as well and I don't know how to fix it. Here are my codes:
public interface ServiceApi {
#POST("/user/login")
Call<LoginResponse> userLogin(#Body LoginData data);
#POST("/user/join")
Call<JoinResponse> userJoin(#Body JoinData data);
#GET("/test/history")
Call<HistoryResponse> getData();
}
HistoryData.java
public class HistoryData {
#SerializedName("eventID")
private int eventID;
#SerializedName("eventType")
private String eventType;
#SerializedName("eventDate")
private String eventDate;
#SerializedName("userID")
private int userID;
#SerializedName("sensorID")
private String sensorID;
public HistoryData(int eventID, String eventType, String eventDate, int userID, String sensorID) {
super();
this.eventID = eventID;
this.eventType = eventType;
this.eventDate = eventDate;
this.userID = userID;
this.sensorID = sensorID;
}
public int getEventID() {
return eventID;
}
public String getEventType() {
return eventType;
}
public String getEventDate() { return eventDate; }
public int getUserID() {
return userID;
}
public String getSensorID() { return sensorID; }
}
HistoryResponse.java
public class HistoryResponse {
#SerializedName("code")
public String code;
#SerializedName("message")
public String message;
#SerializedName("result")
public List<HistoryData> result;
#Override
public String toString() {
return "HistoryResponse{" + "result=" + result +'}';
}
}
HistoryActivity.java
public class HistoryActivity extends AppCompatActivity {
HistoryResponse dataList;
List<HistoryData> dataInfo;
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view);
dataInfo = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
ServiceApi apiInterface = RetrofitClient.getClient().create(ServiceApi.class);
Call<HistoryResponse> call = apiInterface.getData();
call.enqueue(new Callback<HistoryResponse>() {
#Override
public void onResponse(Call<HistoryResponse> call, Response<HistoryResponse> response) {
dataList = response.body();
Log.d("Response", dataList.toString());
dataInfo = dataList.result;
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), dataInfo);
recyclerView.setAdapter(recyclerAdapter);
}
#Override
public void onFailure(Call<HistoryResponse> call, Throwable t) {
Log.d("Response", t.getMessage());
}
});
}
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{
private Context c;
private List<HistoryData> dataList;
public RecyclerAdapter(Context c, List<HistoryData> dataList) {
this.c = c;
this.dataList = dataList;
}
#NonNull
#Override
public RecyclerAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(c).inflate(R.layout.recycler_view, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.MyViewHolder holder, int position) {
holder.id.setText(dataList.get(position).getSensorID());
holder.type.setText("" + dataList.get(position).getEventType());
holder.date.setText("" + dataList.get(position).getEventDate());
}
#Override
public int getItemCount() {
return (dataList == null) ? 0 : dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView type;
TextView date;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id = (TextView)itemView.findViewById(R.id.sensorID);
type = (TextView)itemView.findViewById(R.id.eventType);
date = (TextView)itemView.findViewById(R.id.eventDate);
}
}
}
I don't think the data is being initialized properly inside the RecyclerAdapter class. Is it because I couldn't load the data properly from the server?
I ever face the same issue similiar to this.
What I've done was: initialize the adapter once only the activity created:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view);
dataInfo = new ArrayList<>();
initAdapter();
....
}
private void initAdapter() {
//The adapter should create once in onCreate
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext, LinearLayoutManager.VERTICAL, false);
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), dataInfo);
recyclerView.setAdapter(recyclerAdapter);
}
Then when in callback result: you can clear the previous data before reload to the adapter:
call.enqueue(new Callback<HistoryResponse>() {
#Override
public void onResponse(Call<HistoryResponse> call, Response<HistoryResponse> response) {
dataList = response.body();
dataInfo.clear(); // <- here we clear all previous data before reload result to the adapter.
dataInfo = dataList.result;
recyclerAdapter.notifyDataSetChanged()
#Override
public void onFailure(Call<HistoryResponse> call, Throwable t) {
Log.d("Response", t.getMessage());
}
});
Hope this help.
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;
}
}
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);
....
}
}
I have an activity to implement a to-do list, containing a recyclerview with each item being a checkbox and textview, and each task is added from an edittext.
It stores data using Realm.io. The behaviour that I keep getting is that the single element in the recyclerview merely get updated, and not inflated! Please help.
TasksActivity -
public class TasksActivity extends AppCompatActivity implements View.OnClickListener{
TextView courseTitle;
RecyclerView TaskList;
EditText addTask;
Button addButton;
String transName; //Transferred Course name from MainActivity
TaskAdapter TA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
courseTitle = findViewById(R.id.CourseName);
TaskList = findViewById(R.id.TaskListRV);
TaskList.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
addTask = findViewById(R.id.InputTask);
addButton = findViewById(R.id.AddTaskButton);
//Course name is the obtained from the previous acivity.
transName =getIntent().getExtras().getString("CourseName");
courseTitle.setText(transName);
TA = new TaskAdapter(transName);
TaskList.setAdapter(TA);
addButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String task = addTask.getText().toString();
// Checking if the text is empty.
boolean flag = false;
for(int i = 0;i<task.length();i++)
{
if(task.charAt(i)!=' ')
flag = true;
}
if(!flag || task.equals(""))
{
Toast emptyWarning = Toast.makeText(getApplicationContext(),"Task cannot be Empty!",Toast.LENGTH_SHORT);
emptyWarning.show();
}
else
{
addTask.setText("");
TA.addNewTask(task);
}
}
}
TasksAdapter -
public class TaskAdapter extends RecyclerView.Adapter<TaskViewHolder> implements RealmChangeListener<RealmResults<TaskModel>>
{
private ArrayList<TaskModel> TaskList;
private String course;
private final Realm realm;
public TaskAdapter(String course)
{
this.course = course;
this.TaskList = new ArrayList<>();
realm = Realm.getDefaultInstance();
loadTaskData();
}
void loadTaskData()
{
RealmResults<TaskModel> taskModelRealmResults = realm.where(TaskModel.class).equalTo("courseName",course).findAll();
taskModelRealmResults.addChangeListener(this);
for(TaskModel iTM : taskModelRealmResults)
{
TaskList.add(realm.copyFromRealm(iTM));
}
notifyDataSetChanged();
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view= layoutInflater.inflate(R.layout.item_task,parent,false);
TaskViewHolder Tvh = new TaskViewHolder(view);
return Tvh;
}
#Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
holder.populateTask(TaskList.get(position));
}
#Override
public int getItemCount() {
return TaskList.size();
}
public void addNewTask(String task)
{
TaskModel newTaskObj = new TaskModel(task,course,false);
TaskList.add(newTaskObj);
notifyDataSetChanged();
realm.beginTransaction();
realm.insertOrUpdate(newTaskObj);
realm.commitTransaction();
}
#Override
public void onChange(RealmResults<TaskModel> taskModels) {
taskModels = realm.where(TaskModel.class).equalTo("courseName",course).findAll();
this.TaskList = new ArrayList<>();
for(TaskModel iTM : taskModels)
{
this.TaskList.add(realm.copyFromRealm(iTM));
}
notifyDataSetChanged();
}
}
TaskViewHolder and TaskModel - (in case you might need them)
public class TaskModel extends RealmObject {
String task;
#PrimaryKey
String courseName;
boolean isDone;
public TaskModel() {
task = "";
courseName = "";
isDone = false;
}
public TaskModel(String task, String courseName, boolean isDone) {
this.task = task;
this.courseName = courseName;
this.isDone = isDone;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean done) {
isDone = done;
}
}
public class TaskViewHolder extends RecyclerView.ViewHolder {
CheckBox isdone;
TextView Taskname;
public TaskViewHolder(View itemView) {
super(itemView);
isdone = itemView.findViewById(R.id.TaskCheckBox);
Taskname = itemView.findViewById(R.id.TaskName);
}
void populateTask(final TaskModel T)
{
Taskname.setText(T.getTask());
isdone.setChecked(T.isDone());
isdone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
T.setDone(isdone.isChecked());
}
});
}
}
I advise you to use Realm Android dapter, this adapter is taking care of updating your app UI. Don't need to implement OnChangeListener, your list will be automatically updated after insertion, deletion or edition
Use findAllAsync in order to not block the UI thread
OrderedRealmCollection<TaskModel> taskModels = realm.where(TaskModel.class).equalTo("courseName", course).findAllAsync();
public RealmAdapter(OrderedRealmCollection<TaskModel> data) {
super(data, true);
}
EDIT:
Also always do the process using Async method when it's possible. You can replace your addNewTask method by:
public void addNewTask(String task) {
final TaskModel newTaskObj = new TaskModel(task, course, false);
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(newTaskObj);
}
});
}
Yous should have something like this:
TasksActivity
public class TasksActivity extends AppCompatActivity implements View.OnClickListener {
private EditText addTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
String transName = getIntent().getExtras().getString("CourseName");
TextView courseTitle = findViewById(R.id.CourseName);
courseTitle.setText(transName);
addTask = findViewById(R.id.InputTask);
findViewById(R.id.AddTaskButton).setOnClickListener(this);
OrderedRealmCollection<TaskModel> taskModels = Realm.getDefaultInstance().where(TaskModel.class).equalTo("courseName", transName).findAllAsync()
TaskAdapter adapter = new TaskAdapter(this, taskModels);
RecyclerView taskList = findViewById(R.id.TaskListRV);
taskList.setLayoutManager(new LinearLayoutManager(this));
taskList.setAdapter(adapter);
}
#Override
public void onClick(View view) {
String task = addTask.getText().toString().trim();
if (task.trim().isEmpty()) {
Toast emptyWarning = Toast.makeText(getApplicationContext(),"Task cannot be Empty!",Toast.LENGTH_SHORT);
emptyWarning.show();
return;
}
addTask.setText("");
addNewTask(task);
}
private void addNewTask(String task) {
final TaskModel newTaskObj = new TaskModel(task, course, false);
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(newTaskObj);
}
});
}
}
And TaskAdapter:
public class TaskAdapter extends RealmRecyclerViewAdapter<TaskModel, TaskViewHolder> {
private LayoutInflater layoutInflater
public TaskAdapter(Context context, OrderedRealmCollection<TaskModel> taskModels) {
super(taskModels, true);
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new TaskViewHolder(layoutInflater.inflate(R.layout.item_task , parent, false));
}
#Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
holder.populateTask(getItem(position));
}
}
OP here. I ended up using the standard ReacyclerView.Adapter.
The problem was with the usage of Realm's insertOrUpdate method, when the #PrimaryKey was courseName which thus caused it to indeed update the same object and not create a new one!
insert() should have been used.
Here is the insert task method -
public void addNewTask(String task)
{
boolean flag = false;
for(int i = 0;i<TaskList.size();i++)
{
if(task.equals(TaskList.get(i).getTask()))
{
Toast.makeText(context,"Task already exists!",Toast.LENGTH_SHORT).show();
flag = true;
break;
}
}
if(!flag)
{
TaskModel newTaskObj = new TaskModel();
newTaskObj.setTask(task);
newTaskObj.setDone(false);
newTaskObj.setCourseName(course);
TaskList.add(newTaskObj);
notifyDataSetChanged();
realm.beginTransaction();
realm.insert(newTaskObj);
realm.commitTransaction();
} }
The entire project can be found here, do check it out -
https://github.com/Hariram-R/ToDoList-App
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.