This is my Model Class where isChecked is non persistent.
public class MyModel extends RealmObject {
private String name;
private String destination;
#Ignore
private boolean isChecked;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
In my adapter I have to change the value of isChecked when user is selecting items in the list.
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.Name.setText(myModels.get(position).getName());
holder.Destination.setVisibility(View.VISIBLE);
holder.Destination.setText(myModels.get(position).getDestination());
updateCheckedState(holder, myModels.get(position), false);
holder.label.setOnClickListener(v -> {
myModels.get(position).setChecked(!myModels.get(position).isChecked());
updateCheckedState(holder, myModels.get(position), true);
});
}
But the value remains the same. It was working perfectly before when I was not using Realm.
Override the onResume()
Dont forget to super.onResume();
Related
So I have a simple notes app, it has a noteModel class which extends RealmObject. I added a boolean value "pinned" to it but when I set this value to true it stops returning any of the data saved to it. The title starts returning null in the adapter and I can't use it but when I set "pinned" back to false everything goes back to normal.
Here is the Model class
public class NoteModel extends RealmObject {
#PrimaryKey
private int noteID;
private String note;
private String title;
private long timeStamp;
private boolean archived;
private boolean pinned;
public NoteModel() {
}
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
public int getNoteID() {
return noteID;
}
public void setNoteID(int noteID) {
this.noteID = noteID;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public boolean isArchived() {
return archived;
}
public void setArchived(boolean archived) {
this.archived = archived;
}
}
Here is the adapter code:
switch (which) {
case 0:
if (noteModel.isPinned()) {
realm.beginTransaction();
noteModel.setPinned(false);
realm.commitTransaction();
Prevalent.allNotes.add(noteModel);
Prevalent.pinnedNotes.remove(pos);
} else {
realm.beginTransaction();
noteModel.setPinned(true);
realm.commitTransaction();
Prevalent.pinnedNotes.add(noteModel);
Prevalent.allNotes.remove(index);
}
notifyItemRemoved(index);
NotesFragment.pinNote();
break;
}
When it looses the data it just starts returning null for every get request apart from pinned
Is there any way to update certain List data from RecyclerView.Adapter class
here is my List class:
public class Idea {
private String id, name, voted;
public Idea(String id, String name, String voted) {
this.id = id;
this.name = name;
this.voted = voted;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVoted() {
return voted;
}
}
my RecyclerView Adapter class:
public class IdeaListAdapter extends RecyclerView.Adapter<IdeaListAdapter.IdeaViewHolder> {
private Context mCtx;
private List<Idea> ideaList, idlst;
public IdeaListAdapter(Context mCtx, List<Idea> ideaList) {
this.mCtx = mCtx;
this.ideaList = ideaList;
}
#NonNull
#Override
public IdeaListAdapter.IdeaViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.idea_list_object_layout, null);
return new IdeaListAdapter.IdeaViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull IdeaListAdapter.IdeaViewHolder ideaViewHolder, int i) {
final Idea idea = ideaList.get(i);
if (idea.getVoted().equals("0")) {
ideaViewHolder.checkBoxLikeIdeaListFragment.setChecked(false);
} else if (idea.getVoted().equals("1")) {
ideaViewHolder.checkBoxLikeIdeaListFragment.setChecked(true);
}
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
*** Update my idea.getVoted() here ***
} else {
*** Update my idea.getVoted() here ***
}
}
});
ideaViewHolder.textViewNameIdeaListFragment.setText(idea.getName());
}
#Override
public int getItemCount() {
return ideaList.size();
}
class IdeaViewHolder extends RecyclerView.ViewHolder {
TextView textViewNameIdeaListFragment;
CheckBox checkBoxLikeIdeaListFragment;
public IdeaViewHolder(#NonNull View itemView) {
super(itemView);
textViewNameIdeaListFragment = (TextView) itemView.findViewById(R.id.textViewNameIdeaListFragment);
checkBoxLikeIdeaListFragment = (CheckBox) itemView.findViewById(R.id.checkBoxLikeIdeaListFragment);
}
}
}
i would like to update my idea.getVoted() when the user click the checkBoxLikeIdeaListFragment
im not quite sure how i will use the ideaList.set() at this part.
should i do it on my MainActivity ? if yes, please teach me.
Create Setter method on your Model class **Idea** and access setter method to update the data.
Like this.
public class Idea {
private String id, name, voted;
public Idea(String id, String name, String voted) {
this.id = id;
this.name = name;
this.voted = voted;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVoted() {
return voted;
}
public void setVoted(String voted) {
this.voted = voted;
}
}
Use setter method of setVoted in your adapter class.
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
i
ideaList.get(i).setVoted("set your data"); //here you have to upadte the vote value.
notifiyDatasetChanged();
}
});
Quickest way to do this is to pass a OnCheckedListener on your IdeaViewHolder constructor and assign it to your checkBoxLikeIdeaListFragment.
Or on your existing code you can:
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
ideaList.get(i).setVoted(b); // i is the int index passed to onBindViewHolder(..)
IdeaListAdapter.this.notifyDatasetChanged(); //update list
}
});
I have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
This is my JSON:
I need to access to extra_services and get the service_name.
I know I can do it directly using Gson but the problem is that I need to use getters and setters because I'm using an adapter inside of a recycler, how can I do that?
here is my adapter class where I need to get the service name
public class ExtraServicesAdapter extends RecyclerView.Adapter<ExtraServicesAdapter.ViewHolder> implements View.OnClickListener
{
private ArrayList<Business> businessList;
private Activity activity;
private int layoutMolde,idb;
public ExtraServicesAdapter(Activity activity, ArrayList<Business> list, int layout)
{
this.activity = activity;
this.businessList = list;
layoutMolde = layout;
}
#Override
public ExtraServicesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_services_basic, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
if(businessList.get(position).getExtra_services()==null)
{
holder.txtNameServiceBasic.setText("There's nothing to show");
}
holder.txtNameServiceBasic.setText(businessList.get(position).getExtra_services());
}
#Override
public int getItemCount()
{
return businessList.size();
}
#Override
public void onClick(View v)
{
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView txtNameServiceBasic;
public ViewHolder( View itemView)
{
super(itemView);
txtNameServiceBasic = (TextView) itemView.findViewById(R.id.txtNameServiceBasic);
}
}
}
and this is my class where are the getters and setters that I'm using
public class Business {
private Integer id,rating;
private String name, description, cover_url_string, logo_url_string, icon_default,business_name,cover_default,extra_services;
private Boolean status;
public Business(){}
public Business(Integer id,Integer rating,String business_name, String name, String description, String logo_url_string, String cover_default, String icon_default,String cover_url_string,String extra_services) {
this.id = id;
this.name = name;
this.business_name=business_name;
this.description = description;
this.logo_url_string = logo_url_string;
this.cover_url_string = cover_url_string;
this.rating=rating;
this.icon_default=icon_default;
this.cover_default=cover_default;
this.extra_services=extra_services;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRating() {
return rating;
}
public String getBusiness_name() {
return business_name;
}
public void setBusiness_name(String business_name) {
this.business_name = business_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogo_url_string() {
return logo_url_string;
}
public void setLogo_url_string(String logo_url_string) {
this.logo_url_string = logo_url_string;
}
public String getIcon_default() {
return icon_default;
}
public String getCover_default() {
return cover_default;
}
public String getCover_url_string() {
return cover_url_string;
}
public String getExtra_services() {
return extra_services;
}
public void setExtra_services() {
this.extra_services=extra_services;
}
}
You can add an ExtraServices class that contains a list of ExtraService
ExtraService
public class ExtraService {
private String Id;
private String ServiceName;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String ServiceName) {
this.ServiceName = ServiceName;
}
ExtraServices
public class ExtraServices {
private List<ExtraService> extraServicesList;
public List<ExtraService> getExtraServicesList() {
return extraServicesList;
}
public void setExtraServicesList(List<ExtraService> extraServicesList) {
this.extraServicesList = extraServicesList;
}
public void add(ExtraService extraService){
if(extraServicesList == null){
extraServicesList = new ArrayList<>();
}
extraServicesList.add(extraService);
}
And in your Business class add getters and setters of ExtraServices
private ExtraServices extraServices;
public ExtraServices getExtraServices () {
return extraServices;
}
public void setExtraServices (ExtraServices extraServices) {
this.extraServices = extraServices;
}
After you have to do the setter process and in your Adapter you should do something like this:
holder.txtNameServiceBasic.setText(businessList.get(position).getExtraServices().getExtraServicesList().get(posistion).getServiceName());
I have an object which I for now save using SharedPreferences like this:
public String getActiveTripString(Context con) {
return preferences.getString(ACTIVE_TRIP, "-1");
}
public void setActiveTripString(Context context, String string) {
setString(context, string, ACTIVE_TRIP);
}
public PSTrip getActiveTrip(Context context) {
String active = getActiveTripString(context);
PSTrip psTrip = null;
if (active.contentEquals("-1")) {
return null;
} else {
try{
psTrip = JsonUtil.jsonToObject(active, PSTrip.class);
}catch (Exception e){
Log.i("","getActiveTrip error is:" + e.getMessage());
}
return psTrip;
}
}
public void setActiveTrip(PSTrip psTrip, Context context) {
try{
setActiveTripString(context, JsonUtil.objectToJson(psTrip, PSTrip.class));
}catch (Exception e){
Log.i("","setActiveTrip error is:" + e.getMessage());
}
}
Where I have function as you can see, that create a json and then save it as a string in SharedPrefferences. But The object is BIG, and the more I add into it, the app start to be more laggy until it's unresponsive.
I also need to use this object in a lot of places, so I always need to call:
GetActiveTrip to get it, make my modifications, then SetActiveTrip to save it.
I'm looking for a more efficient way to save it. I tried with REALM, to save it in a database, but because my object is so big, and modified in a lot of places, I did not quite manage to make it work, Having to call Realm a lot just to add items in the database, in order to have managed database items, so I can add them in my object, and so on. Which also I think might be memory consuming. And It crashes a lot with realm exceptions.
Any other way I could do this? Is saving to a file more efficient than to Shared Preferences? As I saw in Android Monitor, analysing my traces, the GSON function that creates the JSON takes a lot of resources.
Any suggestions what I could use?
EDIT: My object:
public class PSTrip extends RealmObject {
private boolean valid;
private String type;
private String travel_mode;
#PrimaryKey
private String id;
private Owner_data owner_data;
private int distance;
private String name;
private double checkinLat;
private double checkinLng;
private double checkoutLng;
private double checkoutLat;
private String icon;
private String status;
private Destination destination;
private int checkout_time;
private int checkin_time;
private Route route;
private String owner;
private String vehicle;
private Flight flight;
#SerializedName("last_updated")
private int lastUpdated;
#SerializedName("steps")
private RealmList<TripStep> tripSteps;
private RealmList<Record> records;
#SerializedName("planned_route")
private Planned_Route plannedRoute;
private Group group;
private float emissions;
private Co2PerKm co2_per_km;
private int update_interval;
private boolean isRoaming = false;
public boolean getIsRoaming() {
return isRoaming;
}
public void setIsRoaming(boolean isRoaming) {
this.isRoaming = isRoaming;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public int getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(int lastUpdated) {
this.lastUpdated = lastUpdated;
}
public RealmList<TripStep> getTripSteps() {
return tripSteps;
}
public void setTripSteps(RealmList<TripStep> steps) {
this.tripSteps = steps;
}
public String getVehicle() {
return vehicle;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
}
public Flight getFlight() {
return flight;
}
public void setFlight(Flight flight) {
this.flight = flight;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTravel_mode() {
return travel_mode;
}
public void setTravel_mode(String travel_mode) {
this.travel_mode = travel_mode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Owner_data getOwner_data() {
return owner_data;
}
public void setOwner_data(Owner_data owner_data) {
this.owner_data = owner_data;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Destination getDestination() {
return destination;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public int getCheckout_time() {
return checkout_time;
}
public void setCheckout_time(int checkout_time) {
this.checkout_time = checkout_time;
}
public int getCheckin_time() {
return checkin_time;
}
public void setCheckin_time(int checkin_time) {
this.checkin_time = checkin_time;
}
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public PSTrip() {
}
public PSTrip(String id) {
this.id = id;
}
public double getCheckoutLng() {
return checkoutLng;
}
public void setCheckoutLng(double checkoutLng) {
this.checkoutLng = checkoutLng;
}
public double getCheckinLat() {
return checkinLat;
}
public void setCheckinLat(double checkinLat) {
this.checkinLat = checkinLat;
}
public double getCheckinLng() {
return checkinLng;
}
public void setCheckinLng(double checkinLng) {
this.checkinLng = checkinLng;
}
public double getCheckoutLat() {
return checkoutLat;
}
public void setCheckoutLat(double checkoutLat) {
this.checkoutLat = checkoutLat;
}
public boolean isRoaming() {
return isRoaming;
}
public void setRoaming(boolean isRoaming) {
this.isRoaming = isRoaming;
}
public Planned_Route getPlannedRoute() {
return plannedRoute;
}
public void setPlannedRoute(Planned_Route plannedRoute) {
this.plannedRoute = plannedRoute;
}
public boolean isValid() {
return valid;
}
public float getEmissions() {
return emissions;
}
public void setEmissions(float emissions) {
this.emissions = emissions;
}
public Co2PerKm getCo2_per_km() {
return co2_per_km;
}
public void setCo2_per_km(Co2PerKm co2_per_km) {
this.co2_per_km = co2_per_km;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public int getUpdate_interval() {
return update_interval;
}
public void setUpdate_interval(int update_interval) {
this.update_interval = update_interval;
}
public RealmList<Record> getRecords() {
return records;
}
public void setRecords(RealmList<Record> records) {
this.records = records;
}
}
Where: Route, Destination are the google maps object, if you are familiar with them, you know what they include and their size;
TripStep = similar with the STEP object from google BUT, it includes 2 arrays:
private RealmList<StopInfo> filteredLocations = new RealmList<>();
private RealmList<StopInfo> rawLocations = new RealmList<>();
In which I have to add a new location every 5-6 seconds in the rawLocations.
Add a new location each time the rawlocation I get is farther than x metres from the last rawLocation I got.
Getting the Object from Preferences, deserialising, getting the latest TripStep and adding the new Location to the filteredLocations and rawLocations seems to take a log of memory. So This is what I think is the problem
After all, I chose to use Realm, instead of shared preferences, it's more efficient, and even if I still have some issues with the changes I make to my file, I'm getting to a stable version quickly.
It has it's downsides (some REALM objects are not serialised correctly by GSON, and you will need to use jackson, and also not being able to use functions inside your model, or that it supports just primitives is a big issue with it, but if you manage to go over this, it's worth it)
Would not suggest adding Realm database to a project that is already big