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.
Related
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);
}
}
I currently get stock on this part. I want to display simple data from GSON and I practice using MVVM structure and with Hilt and "RxJava".
This is my "View Model" and I don't know what to do.(This is my first time using this structure and dependencies.)
At my "getTip()" function under my View Model how can i transfer the data from "tipsModel" to arraylist and if i did something wrong at my codes.
public class TipsViewModel extends ViewModel {
private static final String TAG = "TipsViewModel";
private Repository repository;
private MutableLiveData<ArrayList<TipsModel>> tipsList = new MutableLiveData<>();
#ViewModelInject
public TipsViewModel(Repository repository){
this.repository = repository;
}
public MutableLiveData<ArrayList<TipsModel>> getTipsList(){
return tipsList;
}
public void getTips(){
repository.getTips()
.subscribeOn(Schedulers.io())
.map(new Function<TipsModel, ArrayList<TipsModel>>() {
#Override
public ArrayList<TipsModel> apply(TipsModel tipsModel) throws Throwable {
// What i have to put here to transfer the data from "tipsModel" to my ArrayList.
return null;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> tipsList.setValue(result),
error -> Log.e(TAG,"getTips: "+error.getMessage()));
}
}
This is my Repository
public class Repository {
private TipsApiService apiService;
#Inject
public Repository(TipsApiService apiService){
this.apiService = apiService;
}
public Observable<TipsModel> getTips(){
return apiService.getTips();
}
}
And this is my Model. it a simple model.
public class TipsModel {
private Integer id;
private String gameName;
private String gameMenu;
private String subtitle;
private String description;
private Object image;
public TipsModel(Integer id, String gameName, String gameMenu, String subtitle, String description, Object image) {
this.id = id;
this.gameName = gameName;
this.gameMenu = gameMenu;
this.subtitle = subtitle;
this.description = description;
this.image = image;
}
public Integer getId() {
return id;
}
public String getGameName() {
return gameName;
}
public String getGameMenu() {
return gameMenu;
}
public String getSubtitle() {
return subtitle;
}
public String getDescription() {
return description;
}
public Object getImage() {
return image;
}
public void setId(Integer id) {
this.id = id;
}
public void setGameName(String gameName) {
this.gameName = gameName;
}
public void setGameMenu(String gameMenu) {
this.gameMenu = gameMenu;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public void setDescription(String description) {
this.description = description;
}
public void setImage(Object image) {
this.image = image;
}
}
This is my Code on my fragment
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
binding = ActivityTipsViewBinding.inflate(inflater,container,false);
return binding.getRoot();
}
#Override
public void onViewCreated(#Nonnull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
viewModel = new ViewModelProvider(this).get(TipsViewModel.class);
initRecyclerView();
observeData();
viewModel.getTips();
}
private void observeData(){
viewModel.getTipsList().observe(getViewLifecycleOwner(), new Observer<ArrayList<TipsModel>>() {
#Override
public void onChanged(ArrayList<TipsModel> tipsModels) {
Log.e(TAG,"onChanged: "+ tipsModels.size());
tipsAdapter.updateList(tipsModels);
}
});
}
private void initRecyclerView(){
binding.tipsRecyclerview.setLayoutManager(new LinearLayoutManager((getContext())));
tipsAdapter = new TipsAdapter(getContext(),tipsModels);
binding.tipsRecyclerview.setAdapter(tipsAdapter);
}
}
I'm trying to pass an object from my RecyclerView adapter to a fragment using parcelable. However when I try to receive the data, the bundle is null. I've looked at other examples, but I can't see where I'm going wrong.
Parcelable class
public class Country extends BaseObservable implements Parcelable {
#SerializedName("name")
#Expose
private String name;
#SerializedName("snippet")
#Expose
private String snippet;
#SerializedName("country_id")
#Expose
private String countryId;
#SerializedName("id")
#Expose
private String id;
#SerializedName("coordinates")
#Expose
private Coordinates coordinates;
#SerializedName("images")
#Expose
private List<CountryImage> images;
protected Country(Parcel in) {
name = in.readString();
snippet = in.readString();
}
public static final Creator<Country> CREATOR = new Creator<Country>() {
#Override
public Country createFromParcel(Parcel in) {
return new Country(in);
}
#Override
public Country[] newArray(int size) {
return new Country[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(snippet);
}
#Override
public int describeContents() {
return 0;
}
#Bindable
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
notifyPropertyChanged(BR.countryId);
}
#Bindable
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
notifyPropertyChanged(BR.id);
}
#Bindable
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
notifyPropertyChanged(BR.coordinates);
}
#Bindable
public List<CountryImage> getImages() {
return images;
}
public void setImages(List<CountryImage> images) {
this.images = images;
notifyPropertyChanged(BR.images);
}
#Bindable
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
notifyPropertyChanged(BR.snippet);
}
#Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
RetrofitAdapter.java
public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.MyViewHolder> implements CustomClickListener {
private List<Country> cities;
private CustomClickListener customClickListener;
private View view;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
RetroItemBinding retroItemBinding =
DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
R.layout.retro_item, viewGroup, false);
view = viewGroup;
return new MyViewHolder(retroItemBinding);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.bindTo(cities.get(i));
myViewHolder.retroItemBinding.setItemClickListener(this);
}
#Override
public int getItemCount() {
if (cities != null) {
return cities.size();
} else {
return 0;
}
}
public void setCityList(ArrayList<Country> cities) {
this.cities = cities;
notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private RetroItemBinding retroItemBinding;
public MyViewHolder(#NonNull RetroItemBinding retroItemBinding) {
super(retroItemBinding.getRoot());
this.retroItemBinding = retroItemBinding;
}
void bindTo(Country country) {
retroItemBinding.setVariable(BR.city, country);
retroItemBinding.setVariable(BR.itemClickListener, customClickListener);
retroItemBinding.executePendingBindings();
}
}
public void cardClicked(Country country) {
CountryFragment countryFragment = new CountryFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("Country", country);
countryFragment.setArguments(bundle);
((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction()
.replace(R.id.frag_container, new CountryFragment())
.commit();
}
}
Where I receive attempt to receive the data in CountryFragment.java
Country country;
Bundle bundle = this.getArguments();
if (bundle != null) {
country = bundle.getParcelable("Country");
}
.replace(R.id.frag_container, new CountryFragment())
should be
.replace(R.id.frag_container, countryFragment)
You are creating a second instance instead of passing the one you set the arguments on.
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.
I am trying to get images from an API, and I have written code but images are not loading in emulator
Main activity
public class MainActivity extends ListActivity {
List<Flower> flowerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RestAdapter restadapter = new RestAdapter.Builder().setEndpoint("http://services.hanselandpetal.com").build();
api flowerapi = restadapter.create(api.class);
flowerapi.getData(new Callback<List<Flower>>() {
#Override
public void success(List<Flower> flowers, Response response) {
flowerList = flowers;
adapter adapt = new adapter(getApplicationContext(),R.layout.item_file,flowerList);
setListAdapter(adapt);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_SHORT).show();
}
});
}
In package model I have flower class
public class Flower {
private int productId;
private String name;
private String category;
private String instructions;
private double price;
private String photo;
private Bitmap bitmap;
public Flower() {
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
}
In network package I have api java class
public interface api {
#GET("/feeds/flowers.jason")
public void getData(Callback<List<Flower>>response);
}
And then I have adaptor java class
public class adapter extends ArrayAdapter<Flower> {
String url="http://services.hanselandpetal.com/photos/";
private Context context;
private List<Flower> flowerList;
public adapter(Context context, int resource, List<Flower> objects) {
super(context, resource, objects);
this.context = context;
this.flowerList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_file,parent,false);
Flower flower = flowerList.get(position);
TextView tv = (TextView) view.findViewById(R.id.name);
tv.setText(flower.getName());
ImageView img = (ImageView) view.findViewById(R.id.img);
Picasso.with(getContext()).load(url+flower.getPhoto()).resize(100,100).into(img);
return view;
}
}
I am getting nothing on emulator and it says it failed. Is the fault in emulator.
I have included internet permission in manifest.
Might be blowing up on your #GET annotation param "/feeds/flowers.jason"
try ".json"