I am planning to save this ImageView :
to my RealmDatabase, but the image is not appearing when I want to retrieve it. it should appear here:
here is the my onSaveExpense code
public void onSaveExpense() {
//TODO - BITMAP EXPENSE ICONS
if (mCategoriesSpinnerAdapter.getCount() > 0 ) {
if (!Util.isEmptyField(etTotal)) {
Category currentCategory = (Category) spCategory.getSelectedItem();
String total = etTotal.getText().toString();
String description = etDescription.getText().toString();
Bitmap bitmap = BitmapFactory.decodeByteArray(currentCategory.getImgico(),0,currentCategory.getImgico().length);
ByteArrayOutputStream imgbyte = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, imgbyte);
byte[] expenseIcons = imgbyte.toByteArray();
if (mUserActionMode == IUserActionsMode.MODE_CREATE) {
//TODO - CONSTRUCTOR expenseIcons
RealmManager.getInstance().save(new Expense(description, selectedDate,expenseIcons,mExpenseType, currentCategory, Float.parseFloat(total)), Expense.class);
} else {
Expense editExpense = new Expense();
editExpense.setId(mExpense.getId());
editExpense.setTotal(parseFloat(total));
editExpense.setDescription(description);
editExpense.setIconViewer(expenseIcons);
editExpense.setCategory(currentCategory);
editExpense.setDate(selectedDate);
RealmManager.getInstance().update(editExpense);
}
// update widget if the expense is created today
if (DateUtils.isToday(selectedDate)) {
Intent i = new Intent(getActivity(), ExpensesWidgetProvider.class);
i.setAction(ExpensesWidgetService.UPDATE_WIDGET);
getActivity().sendBroadcast(i);
}
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
dismiss();
} else {
DialogManager.getInstance().showShortToast(getString(string.error_total));
}
} else {
DialogManager.getInstance().showShortToast(getString(string.no_categories_error));
}
}
Here is my CategoriesSpinnerAdapter code
public class CategoriesSpinnerAdapter extends ArrayAdapter<Category> {
Category[] categoriesList = null;
LayoutInflater inflater;
public CategoriesSpinnerAdapter(Activity context, Category[] categoriesList) {
super(context, R.layout.spinner_ui, categoriesList);
this.categoriesList = categoriesList;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
View row = inflater.inflate(R.layout.spinner_ui, parent, false);
Category category = categoriesList[position];
Bitmap bitmap = BitmapFactory.decodeByteArray(category.getImgico(),0,category.getImgico().length);
ImageView imgview = (ImageView)row.findViewById(R.id.spinnerimg);
TextView title = (TextView)row.findViewById(R.id.spinnertext);
title.setText(category.getName());
imgview.setImageBitmap(bitmap);
return row;
}
here is my BaseExpenseAdapter code (The Cardview Result)
public class BaseExpenseAdapter<VH extends RecyclerView.ViewHolder> extends BaseExpenseRecyclerViewAdapter<BaseExpenseAdapter.BaseExpenseViewHolder> {
protected List<Expense> mExpensesList;
protected int lastPosition = -1;
protected int colorExpense;
protected int colorIncome;
protected String prefixExpense;
protected String prefixIncome;
private String titleTransitionName;
protected BaseViewHolder.RecyclerClickListener onRecyclerClickListener;
public BaseExpenseAdapter(Context context, BaseViewHolder.RecyclerClickListener onRecyclerClickListener) {
this.mExpensesList = ExpensesManager.getInstance().getExpensesList();
this.onRecyclerClickListener = onRecyclerClickListener;
this.colorExpense = ExpenseTrackerApp.getContext().getResources().getColor(R.color.colorAccentRed);
this.colorIncome = ExpenseTrackerApp.getContext().getResources().getColor(R.color.colorAccentGreen);
this.prefixExpense = ExpenseTrackerApp.getContext().getResources().getString(R.string.expense_prefix);
this.prefixIncome = ExpenseTrackerApp.getContext().getResources().getString(R.string.income_prefix);
this.titleTransitionName = ExpenseTrackerApp.getContext().getString(R.string.tv_title_transition);
}
#Override
public BaseExpenseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_expense_item, parent, false);
return new BaseExpenseViewHolder(v, onRecyclerClickListener);
}
#Override
public void onBindViewHolder(BaseExpenseViewHolder holder, int position) {
holder.itemView.setSelected(isSelected(position));
final Expense expense = mExpensesList.get(position);
Bitmap bitmaps = BitmapFactory.decodeByteArray(expense.getIconViewer(), 0, expense.getIconViewer().length);
holder.iconExpenses.setImageBitmap(bitmaps);
String prefix = "";
switch (expense.getType()) {
case IExpensesType.MODE_EXPENSES:
holder.tvTotal.setTextColor(colorExpense);
prefix = String.format(prefixExpense, Util.getFormattedCurrency(expense.getTotal()));
break;
case IExpensesType.MODE_INCOME:
holder.tvTotal.setTextColor(colorIncome);
prefix = String.format(prefixIncome, Util.getFormattedCurrency(expense.getTotal()));
break;
}
if (expense.getCategory() != null)holder.tvCategory.setText(expense.getCategory().getName());
if (expense.getDescription() != null && !expense.getDescription().isEmpty()) {
holder.tvDescription.setText(expense.getDescription());
holder.tvDescription.setVisibility(View.VISIBLE);
} else {
holder.tvDescription.setVisibility(View.GONE);
}
holder.tvTotal.setText(prefix);
holder.itemView.setTag(expense);
holder.iconExpenses.setImageBitmap(bitmaps);
ViewCompat.setTransitionName(holder.tvTotal, titleTransitionName);
}
#Override
public int getItemCount() {
return mExpensesList.size();
}
public void updateExpenses(List<Expense> mExpensesList) {
this.mExpensesList = mExpensesList;
notifyDataSetChanged();
}
protected void setAnimation(BaseExpenseViewHolder holder, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(ExpenseTrackerApp.getContext(), R.anim.push_left_in);
holder.itemView.startAnimation(animation);
lastPosition = position;
}
}
public static class BaseExpenseViewHolder extends BaseViewHolder {
public TextView tvCategory;
public TextView tvDescription;
public TextView tvTotal;
public ImageView iconExpenses;
public BaseExpenseViewHolder(View v, RecyclerClickListener onRecyclerClickListener) {
super(v, onRecyclerClickListener);
iconExpenses = (ImageView)v.findViewById(R.id.expenseico);
tvCategory = (TextView)v.findViewById(R.id.tv_category);
tvDescription = (TextView)v.findViewById(R.id.tv_description);
tvTotal = (TextView)v.findViewById(R.id.tv_total);
}
}
and here is my Expense entities
public class Expense extends RealmObject {
#PrimaryKey
private String id;
private byte[] iconViewer;
private String description;
private Date date;
private #IExpensesType int type;
private Category category;
private float total;
public Expense() {
}
public Expense(String description, Date date ,byte[] iconViewer, #IExpensesType int type, Category category, float total) {
this.description = description;
this.iconViewer = iconViewer;
this.date = date;
this.type = type;
this.category = category;
this.total = total;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public byte[] getIconViewer() {
return iconViewer;
}
public void setIconViewer(byte[] iconViewer) {
this.iconViewer = iconViewer;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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 have a recyclerview of tasks. When user will swipe an element I want to change one parameter(variable "isChecked" from false to true - that will mean the task is completed) in that task.
I created new ItemTouchHelper instance in my activity:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
Sorted current = adapter.getSortedAtPosition(viewHolder.getAdapterPosition());
int time = current.getSortedDuration() + current.getSortedTimeBegin();
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
if (hour > time/60){
//change
Toast.makeText(ShowSortedActivity.this, "check1", Toast.LENGTH_SHORT).show();
}
else if (hour == time/60){
if (minute > time % 60){
//change
Toast.makeText(ShowSortedActivity.this, "check2", Toast.LENGTH_SHORT).show();
}
else{
//do nothing
Toast.makeText(ShowSortedActivity.this, "uncheck1", Toast.LENGTH_SHORT).show();
}
}
else{
//do nothing
Toast.makeText(ShowSortedActivity.this, "uncheck2", Toast.LENGTH_SHORT).show();
}
}
}).attachToRecyclerView(showSorted);
}
Here I'm getting the task of class "Sorted" and check if the ending time of the task is less than the current time of the day. If so, I want to change the variable.
My adapter class:
public class SortedAdapter extends RecyclerView.Adapter<SortedAdapter.SortedViewHolder> {
private List<Sorted> list = new ArrayList<>();
#NonNull
#Override
public SortedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tasks2_layout , parent, false);
return new SortedAdapter.SortedViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SortedViewHolder holder, final int position) {
final Sorted data = list.get(position);
holder.title.setText(data.getSortedName());
holder.date.setText(data.getSortedDate());
holder.category.setText(String.valueOf(data.getSortedCategory()));
holder.attach.setText(String.valueOf(data.isSortedAttach()));
holder.to.setText(String.valueOf(toTime(data.getSortedDuration() + data.getSortedTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getSortedTimeBegin())));
holder.isChecked.setText(String.valueOf(data.isChecked()));
}
public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}
public Sorted getSortedAtPosition(int position){
return list.get(position);
}
public void setSorted(Sorted data){
}
#Override
public int getItemCount() {
return list.size();
}
static class SortedViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView title;
private TextView date;
private TextView from;
private TextView to;
private TextView category;
private TextView attach;
private TextView isChecked;
SortedViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title1);
date = itemView.findViewById(R.id.tv_date1);
from = itemView.findViewById(R.id.tv_from3);
to = itemView.findViewById(R.id.tv_to3);
category = itemView.findViewById(R.id.tv_category1);
attach = itemView.findViewById(R.id.tv_attach1);
isChecked = itemView.findViewById(R.id.tv_isChecked);
}
}
private static String toTime(int a) {
String s = "";
int b = a/60;
int c = a%60;
if (c < 10) {
s = b + " : " + 0 + c;
}
else {
s = b + " : " + c;
}
return s;
}
}
Sorted class:
#Entity
public class Sorted {
#PrimaryKey(autoGenerate = true)
public int id;
public String name;
public int timeBegin;
public int duration;
public int category;
public boolean attach;
public String date;
public String categoryChart;
public boolean checked;
public Sorted(String name, int timeBegin, int duration, int category, boolean attach, String date, String categoryChart, boolean checked) {
this.name = name;
this.timeBegin = timeBegin;
this.duration = duration;
this.category = category;
this.attach = attach;
this.date = date;
this.categoryChart = categoryChart;
this.checked = checked;
}
public void setSortedId(int id) {
this.id = id;
}
public String getSortedName() {
return name;
}
public int getSortedTimeBegin() {
return timeBegin;
}
public int getSortedDuration() {
return duration;
}
public int getSortedCategory() {
return category;
}
public boolean isSortedAttach() {
return attach;
}
public String getSortedDate() {
return date;
}
public String getSortedCategoryChart() {
return categoryChart;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
My problem is that I don't really understand how to do it. Is there any way to update the data, not create a new task? Or do I need to delete the task I got and insert a new one, with one parameter changed? Maybe I could do it the same way I update the list? :
public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}
Or maybe I don't need to deal with my adapter, only with database? (I'm using Room).
Thanks in advance for help. If it's needed, I will add more information to the question.
In method onSwipe to change UI you only need call some method to set for model current and call adapter.notifyItemChange(viewHolder.getAdapterPosition()) no need create new object or new list
I know you using Room don't forget update it to database. Additional if you using RxJava or Flow and LiveData one thing you need is update entity. Room auto update new list for you
I developed a vocabulary app that has a Recycler View in main activity and shows two column of database: unit number and Unit name.When I click on each item it goes to another activity called inner page that has 6 text views and it must show other items of that row like word definition unit number spell meaning and part of speech. But unfortunately text views are empty and it shows only one value which is unit number.Please take a look at my codes and tell me what I missed.
Here's my codes:
Main page:
public class TabWord extends Fragment {
private RecyclerView recyclerView;
private ArrayList<WordItem> items = new ArrayList<>();
private WordTab adapter;
private DatabaseHelper databaseHelper;
private Cursor cursor ;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.tab_word, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerview_word);
adapter = new WordTab(items, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
loadDatabase();
return viewGroup;
}
public void loadDatabase() {
databaseHelper = new DatabaseHelper(getActivity());
try {
databaseHelper.checkAndCopyDatabase();
databaseHelper.openDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
try {
cursor = databaseHelper.QueryData("select * from ielts");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
WordItem item = new WordItem();
item.setUnitName(cursor.getString(2));
item.setUnitNumber(cursor.getString(1));
items.add(item);
} while (cursor.moveToNext());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new WordTab(items, getActivity());
adapter.setOnTapListener(new OnTapListener() {
#Override
public void OnTapView(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class WordTab extends RecyclerView.Adapter<WordTab.ViewHolder> {
public static List<WordItem> wordItems;
private Context context;
private OnTapListener onTapListener;
public WordTab(List<WordItem> wordItems, Context context) {
this.wordItems = wordItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_word, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
WordItem wordItem = wordItems.get(position);
holder.unitNumber.setText(wordItem.getUnitNumber());
holder.unitName.setText(wordItem.getUnitName());
holder.cardView.setId(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onTapListener != null) {
onTapListener.OnTapView(position);
int position = v.getId();
Intent intent = new Intent(context, InnerPage.class);
intent.putExtra("name", "words");
intent.putExtra("id", position + "");
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return wordItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView unitName, unitNumber;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
unitName = itemView.findViewById(R.id.unit_name);
unitNumber = itemView.findViewById(R.id.unit_number);
cardView= itemView.findViewById(R.id.card_view_word);
}
}
public void setOnTapListener(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
}
Model:
public class WordItem {
private int id;
private String unitNumber;
private String unitName;
private String word;
private String phonetic,pos,persian,definition;
public WordItem() {
this.unitName = unitName;
this.unitNumber = unitNumber;
this.word = word;
this.phonetic = phonetic;
this.pos = pos;
this.persian = persian;
this.definition = definition;
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getPersian() {
return persian;
}
public void setPersian(String persian) {
this.persian = persian;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(String unitNumber) {
this.unitNumber = unitNumber;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
Inner Page:
public class InnerPage extends AppCompatActivity {
private int id;
private String unitNumber,word,phonetic,pos,persian,definition;
private TextView unitTxt,wordTxt,phoneticTxt,posTxt,persianTxt,definitionTxt;
private int layoutId;
private String pageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inner_page);
Bundle extras = getIntent().getExtras();
if (extras != null) {
layoutId = Integer.parseInt(extras.getString("id"));
pageName = extras.getString("name");
if (pageName.equals("words")){
id = WordTab.wordItems.get(layoutId).getId();
unitNumber = WordTab.wordItems.get(layoutId).getUnitNumber();
word = WordTab.wordItems.get(layoutId).getWord();
phonetic = WordTab.wordItems.get(layoutId).getPhonetic();
pos = WordTab.wordItems.get(layoutId).getPos();
persian = WordTab.wordItems.get(layoutId).getPersian();
definition = WordTab.wordItems.get(layoutId).getDefinition();
}
}
unitTxt = findViewById(R.id.unit);
wordTxt = findViewById(R.id.word);
phoneticTxt = findViewById(R.id.phonetic);
posTxt = findViewById(R.id.txtSpell);
persianTxt = findViewById(R.id.farMean);
definitionTxt = findViewById(R.id.definition);
unitTxt.setText(unitNumber);
wordTxt.setText(word);
phoneticTxt.setText(phonetic);
posTxt.setText(pos);
persianTxt.setText(persian);
definitionTxt.setText(definition);
}
}
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?!
I have Listview on MainActivity. On Listview must image and text. I write query and successfully texts are displaying. I make ListCategoryAdapter which extends BaseAdapter. All tutorials in Internet with arrays, none of them working with DB. Here is Adapter.
public class ListCategoryAdapter extends BaseAdapter{
LayoutInflater inflater;
List<Category> cats;
Context context;
DbHelper dbHelper;
String stt;
RecordHolder holder = null;
public ListCategoryAdapter(Context context1, List<Category> list){
if (list != null){
this.cats = list;
this.context = context1;
inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
#Override
public int getCount() {
return cats.size();
}
#Override
public Object getItem(int position) {
return cats.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
ImageView imageView2;
TextView txtCateg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = inflater.inflate(R.layout.list_cat_adapter, null);
}
holder = new RecordHolder();
final Category cat = cats.get(position);
holder.txtCateg = (TextView)convertView.findViewById(R.id.txtCateg);
holder.txtCateg.setText(cat.getTitle());
holder.imageView2 = (ImageView) convertView.findViewById(R.id.imageView2);
holder.imageView2.setImageResource(cat.getImage());
return convertView;
}
static class RecordHolder{
TextView txtCateg;
ImageView imageView2;
}
}
Here is Database where from calls text and image
public List<Category> categories(){
SQLiteDatabase db = this.getReadableDatabase();
List<Category> categoryList = new ArrayList<Category>();
String ss = "select * from category";
Cursor cursor = db.rawQuery(ss, null);
if (cursor.moveToFirst()) {
do {
Resources resources = mContext.getResources();
Category category = new Category();
category.setId(cursor.getInt(0));
category.setTitle(cursor.getString(1));
category.setImage(cursor.getInt(2));
categoryList.add(category);
} while (cursor.moveToNext());
} db.close();
return categoryList;
}
Here is Category class
public class Category {
int id;
int image;
String title;
public Category(int image, String title, int id) {
super();
this.id = id;
this.image = image;
this.title = title;
}
public Category() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}