I have a realm database model which i want to display in arecyclerview,
every row in the database model have a String name,int age and a boolean favourite,when i try to save the boolean value in the RecyclerviewAdapter
by using an interface but i gjava.lang.NullPointerException: Attempt to invoke virtual method 'void io.realm.Realm.beginTransaction()' on a null object reference
this the model
public class person extends RealmObject implements{
#PrimaryKey
private String name;
private String job;
private boolean favourite;
private String image;
public AuthorInfo(String image, String job, String name, boolean favoutite) {
this.image = image;
this.job = job;
this.name = name;
this.favourite = favourite;
}
public AuthorInfo() {
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFavourite() {
return favourite;
}
public void setFavourite(boolean favourite) {
this.favourite = favourite;
}
}
this is the interface
public interface ItemClickListener {
void onItemClick(View view,int position);}
and this the recyclerview adapter
public class PersonAdapter extends RecyclerView.Adapter<AuthorAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Realm mRealm;
private RealmResults<AuthorInfo> results;
public PersonAdapter(Context context, RealmResults<AuthorInfo> realmResults) {
inflater = LayoutInflater.from(context);
results = realmResults;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
AuthorInfo current = results.get(position);
holder.name.setText(current.getName());
holder.job.setText(current.getJob());
holder.setClickListener(new ItemClickListener() {
mRealm.beginTransaction();
#Override
public void onItemClick(View view, int position) {
CheckBox chk= (CheckBox) view;
if (chk.isChecked()){
results.get(position).setFavourite(true);
}
else if (!chk.isChecked()){
results.get(position).setFavourite(false);
}
}
mRealm.commitTransaction();
notifyItemChanged(position)
});
}
#Override
public int getItemCount() {
return results.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
CheckBox checkbox;
ItemClickListener itemclicklistener;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_job);
checkbox = (CheckBox) itemView.findViewById(R.id.checkbox);
checkbox.setOnClickListener(this);
}
public void setClickListener(ItemClickListener ic) {
this.itemclicklistener = ic;
}
#Override
public void onClick(View view) {
this.itemclicklistener.onItemClick(view,getAdapterPosition());
}
}
}
so and ideas?!
Related
I am new to android studios I am currently changing my FirestoreRecyclerOptions to a regular recycler view because I want to add native ads every 5 posts. The current issue I am facing is that the method getItemViewType what I want it to return is if it's either an ad or regular post using instance of. In the tutorial videos they do something along the line of
#Override
public int getItemViewType(int position) {
if (noteList.get(position) instanceof UnifiedNativeAd) {
return TYPE_AD;
}else {
return TYPE_REG;
}
}
But the condition inside the if statement is giving me this error
error: incompatible types: Note cannot be converted to UnifiedNativeAd
if (noteList.get(position) instanceof UnifiedNativeAd) {
CLASS
public class Note {
public int timestamp;
public List<String> replies;
public String ownerName;
public String ownerId;
public String text;
public String imageURL;
public List<String> usersLiked;
public String message;
public String timePosted;
public int likes;
public int replyCount;
public Note() {
}
public Note(int timestamp, String ownerId, String text, String ownerName, String imageURL, List<String> replies, List<String>
usersLiked, String message, String timePosted, int likes, int replyCount) {
this.timestamp = timestamp;
this.ownerId = ownerId;
this.text = text;
this.ownerName = ownerName;
this.imageURL = imageURL;
this.replies = replies;
this.usersLiked = usersLiked;
this.message = message;
this.timePosted = timePosted;
this.likes = likes;
this.replyCount = replyCount;
}
public int getTime() {
return timestamp;
}
public String getOwnerName() {
return ownerName;
}
public String getId() {
return ownerId;
}
public String getPost() {
return text;
}
public List<String> getreplies() {
return replies;
}
public String getImageURL() {
return imageURL;
}
public List<String> getUsersLiked() {
return usersLiked;
}
public String getMessage() {
return message;
}
public String getTimePosted() {
return timePosted;
}
public int getLikes() {
return likes;
}
public int getReplyCount() {
return replyCount;
}
}
FULL RECYCLERVIEW
ublic class adapterRegular extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final static int TYPE_AD=0;
private final static int TYPE_REG=1;
private Context context;
private List<Note> noteList;
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
if(viewType == TYPE_AD){
View view = LayoutInflater.from(context).inflate(R.layout.reclyerads,parent,false);
return new AdTemplateViewHolder(view);
}
View view = LayoutInflater.from(context).inflate(R.layout.list_row,parent,false);
return new noteHolder(view);
}
#Override
public int getItemCount() {
return noteList.size();
}
public class noteHolder extends RecyclerView.ViewHolder{
TextView ownerName;
TextView timestamp;
TextView text;
ImageView imageURL;
TextView replies;
TextView likes;
ImageView heart;
public noteHolder(#NonNull View itemView) {
super(itemView);
ownerName = itemView.findViewById(R.id.userName);
timestamp = itemView.findViewById(R.id.time);
text = itemView.findViewById(R.id.post);
imageURL = itemView.findViewById(R.id.profilePic);
replies = itemView.findViewById(R.id.REPLY);
likes = itemView.findViewById(R.id.likes);
heart = itemView.findViewById(R.id.heart);
}
}
public class AdTemplateViewHolder extends RecyclerView.ViewHolder{
TemplateView templateView;
public AdTemplateViewHolder(#NonNull View itemView) {
super(itemView);
templateView = itemView.findViewById(R.id.my_template);
NativeTemplateStyle style = new NativeTemplateStyle.Builder()
.withMainBackgroundColor(new ColorDrawable(Color.parseColor("#FFFFFF"))).build();
templateView.setStyles(style);
}
public void setUnifiedNativeAd(UnifiedNativeAd ads){
templateView.setNativeAd(ads);
}
}
#Override
public int getItemViewType(int position) {
if (noteList.get(position) instanceof UnifiedNativeAd) {
return TYPE_AD;
}else {
return TYPE_REG;
}
}
}
ANY HELP OR SUGGESTION IS APPERCIATED
Change this
private List<Note> noteList;
To this
private List<Object> noteList;
I am trying to get the details of the Recipe from which Recipe I have clicked in recycler view. I am using this to go to an edit/delete feature. Here is the code for my main activity.
The details that I am trying to get is getting the Name, Ingredients and method.
public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener {
private RecipeViewModel mRecipeViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public String Name;
public String Ingredients;
public String Method;
private RecipeListAdapter mAdapter;
private RecipeDao recDao;
private LiveData<List<Recipe>> RecipeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final RecipeListAdapter adapter = new RecipeListAdapter(this);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
#Override
public void onChanged(#Nullable final List<Recipe> recipes) {
// Update the cached copy of the words in the adapter.
adapter.setWords(recipes);
}
});
void onItemClick(int position) {
//Delete Below test to pass data through
Recipe recipe = new Recipe("Test", "Yeet", "Jim");
// showAlertDialogBox();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Edit or Delete...");
alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
update.putExtra("Name", recipe.getName());
update.putExtra("Ingredients", recipe.getIngredients());
update.putExtra("Method", recipe.getMethod());
startActivity(update);
}
});
alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Delete
}
});
alertDialog.show();
}
Here is the Recipe.class if you needed it!
#Entity(tableName = "recipe_table")
public class Recipe {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name= "recipeId")
private int RecipeId;
private String name;
private String Ingredients;
private String Method;
#Ignore
public Recipe(String name, String Ingredients, String Method) {
this.RecipeId = RecipeId;
this.name = name;
this.Ingredients = Ingredients;
this.Method = Method;
}
public Recipe(String name) {
this.name = name;
}
public void changeText1(String text){
name = text;
}
//Add Image somehow!
public int getRecipeId() {
return RecipeId;
}
public void setRecipeId(int recipeId) {
RecipeId = recipeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public String getIngredients() {
return Ingredients;
}
public void setIngredients(String ingredients) {
Ingredients = ingredients;
}
}
If you need anymore files, these are the files I have:
- RecipeListAdapter
- RecipeDao
- RecipeRepository
- RecipeRoomDatabase
- RecipeViewModel
Recipe Adapter code
public class RecipeListAdapter extends RecyclerView.Adapter {
private OnItemClickListener mListener;
private List recipeList;
public interface OnItemClickListener{
void onItemClick(int position, Recipe recipe);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position,
recipeList.get(getAdapterPosition()));
}
}
}
});
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.recipeList = recipeList;
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent,
false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't
return null).
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}
Inside the onItemClick there is one more parameter need to add.
void onItemClick(int position, Recipe recipe) {
//Delete selected recipe from recipe list
arrayList.remove(recipe)
}
The onItemClick method will get called from adapter, from there you have to pass the selected receipe. In the adapter you have to use recipeList.get(getAdapterPosition()) to get the clicked receipe and pass this to the interface method, onItemClick along with the position.
So your code will look like this way inside the adapter,
itemClickListener.onItemClick(position,
recipeList.get(getAdapterPosition()))
Just as a note, please ensure instead of List, you need to take ArrayList to perform remove operation.
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.
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"
i have a recyclerView with two sections regular and Favourites and for populating my RecyclerView i have List<Object> my object class :
public class Object {
String id,channelName;
boolean isFavorite;
}
now i want to put the values which have isfavorite == true to top of my recyclerView inside my Favourite section but i don't know where to start or exactly what to do ? do i have to sort the List<Object> with booleans ? if anybody can give me a little hint or guidance then it'll be so helpful for me,
please this image for better understanding ,
this is what i'm trying to get
i added the Section in my RecyclerView by SimpleSectionedRecyclerViewAdapter
class DataModal
{
public String title;
public boolean isFavourite;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isFavourite() {
return isFavourite;
}
public void setIsFavourite(boolean isFavourite) {
this.isFavourite = isFavourite;
}
}
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private List<DataModal> mData;
public void add(DataModal s,int position) {
position = position == -1 ? getItemCount() : position;
mData.add(position,s);
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView title;
public SimpleViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.simple_text);
}
}
public SimpleAdapter(Context context, ArrayList<DataModal> data) {
mContext = context;
if (data != null)
mData = data;
else mData = new ArrayList<DataModal>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.simple_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
DataModal data = mData.get(position);
holder.title.setText(data.getTitle());
holder.title.setOnClickListener(new Listener(position,mData.get(position)));
}
class Listener implements View.OnClickListener
{
DataModal Data;
int position;
Listener(int position,DataModal Data)
{
this.Data = Data;
this.position = position;
}
#Override
public void onClick(View view) {
if(Data.isFavourite())
{
//mark the view as unfavorite
}
else{
//mark the view as favorite
}
Toast.makeText(mContext,"Position ="+position,Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
return mData.size();
}
}
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private List<String> mData;
public void add(String s,int position) {
position = position == -1 ? getItemCount() : position;
mData.add(position,s);
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView title;
public SimpleViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.simple_text);
}
}
public SimpleAdapter(Context context, String[] data) {
mContext = context;
if (data != null)
mData = new ArrayList<String>(Arrays.asList(data));
else mData = new ArrayList<String>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.simple_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.title.setText(mData.get(position));
holder.title.setOnClickListener(new Listener(position,mData.get(position),false,favview));
}
class Listener implements View.OnClickListener
{
ImageView favoriteView;
int position;
Listener(int position,String Data,boolean isFavourite,ImageView favoriteView)
{
this.favoriteView = favoriteView;
this.position = position;
}
#Override
public void onClick(View view) {
if(isFavourite)
{
//mark the view as unfavorite
}
else{
//mark the view as favorite
}
Toast.makeText(mContext,"Position ="+position,Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
return mData.size();
}
}