How to write query to display images in Listview? - java

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;
}
}

Related

How do I introduce an OnItemClick method to show pictures from a sql database (gridview) in a fullscreen Activity (Android Studio)

I have a code, witch shows all the pictures from a sql database in a gridview and now i try to introduce a OnItemClick method to show this pictures in a new Activity over the full screen. I am coding in Java. Pls help me. Thanks
This is the code from thr list activity (the sqldatabase is called aood)
(there are some other things in this activity so do not wonder)
public class AoodList extends AppCompatActivity {
GridView gridView;
ArrayList<Aood> list;
AoodAdapter adapter = null;
GridView grid;
public static Bitmap bmp = null;
private String[] FilePathStrings;
ImageView imageview;
private File[] listFile;
File file;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aood_list_activity);
gridView = (GridView) findViewById(R.id.gridview1);
list = new ArrayList<>();
adapter = new AoodAdapter(this, R.layout.aood_items, list);
gridView.setAdapter(adapter);
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM AOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
String date = cursor.getString(4);
byte[] image = cursor.getBlob(3);
list.add(new Aood(id, name, price, image, date));
}
adapter.notifyDataSetChanged();
public class Aood {
private int id;
private String name;
private String price;
private String date;
private byte[] image;
public Aood(int id, String name, String price, byte[] image, String date) {
this.id = id;
this.name = name;
this.price = price;
this.date = date;
this.image = image;
}
public int getId() { return id; }
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDate() {return date;}
public void setDate(String date) {this.date = date;}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
public class AoodAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Aood> aoodList;
public AoodAdapter(Context context, int layout, ArrayList<Aood> aoodList) {
this.context = context;
this.layout = layout;
this.aoodList = aoodList;
}
#Override
public int getCount() {
return aoodList.size();
}
#Override
public Object getItem(int position) {
return aoodList.get (position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
ImageView imageView;
TextView txtName, txtPrice, txtDate;
}
#Override
public View getView(int position, View view, ViewGroup ViewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row == null){
LayoutInflater inflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
holder.txtDate = (TextView) row.findViewById(R.id.txtDate);
holder.imageView = (ImageView) row.findViewById(R.id.imgAood);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
Aood aood = aoodList.get(position);
holder.txtName.setText(aood.getName());
holder.txtPrice.setText(aood.getPrice());
holder.txtDate.setText(aood.getDate());
byte[] aoodImage = aood.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(aoodImage, 0, aoodImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
You need to create an interface that'll handle your onClick event:
public interface IClickListener {
<T> void onClick(T model);
}
Then change your adapter to the following, receive IClickListener in the constructor and setOnClickLister on your imageView and trigger onClick event:
public class AoodAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Aood> aoodList;
private IClickListener clickListener //register clickListener to trigger onClick event
public AoodAdapter(Context context, int layout, ArrayList<Aood> aoodList, IClickListener clickListener) {
this.context = context;
this.layout = layout;
this.aoodList = aoodList;
this.clickListener = clickListener;
}
#Override
public int getCount() {
return aoodList.size();
}
#Override
public Object getItem(int position) {
return aoodList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
ImageView imageView;
TextView txtName, txtPrice, txtDate;
}
#Override
public View getView(int position, View view, ViewGroup ViewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
holder.txtDate = (TextView) row.findViewById(R.id.txtDate);
holder.imageView = (ImageView) row.findViewById(R.id.imgAood);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Aood aood = aoodList.get(position);
holder.txtName.setText(aood.getName());
holder.txtPrice.setText(aood.getPrice());
holder.txtDate.setText(aood.getDate());
//setOnClickListener on imageView to trigger your interface and pass clicked object
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickListener.onClick(aood);
}
});
byte[] aoodImage = aood.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(aoodImage, 0, aoodImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
Then implement your interface in your Activity and override onClick as shown below:
public class AoodList extends AppCompatActivity implements IClickListener {
GridView gridView;
ArrayList<Aood> list;
AoodAdapter adapter = null;
GridView grid;
public static Bitmap bmp = null;
private String[] FilePathStrings;
ImageView imageview;
private File[] listFile;
File file;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aood_list_activity);
gridView = (GridView) findViewById(R.id.gridview1);
list = new ArrayList<>();
adapter = new AoodAdapter(this, R.layout.aood_items, list, this); //pass IClickListener
gridView.setAdapter(adapter);
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM AOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
String date = cursor.getString(4);
byte[] image = cursor.getBlob(3);
list.add(new Aood(id, name, price, image, date));
}
adapter.notifyDataSetChanged();
}
#Override
public <T> void onClick(T data) {
//then cast data onto your obj
Aood aood = (Aood) data;
}
}

Attempt to invoke virtual method 'java.lang.String on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I working with an app but I have a problem. When I press the back button my app crashes and gives me Null Pointer Exception error.
I have a list view with some data from api where I used retrofit2 to call them. Everything works fine except the back button.
Here is what I did:
My adapter
private Context context;
private Industry industries;
public IndustryAdapter(Context context, Industry industries) {
this.industries = industries;
this.context = context;
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return 1;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.row_item, parent, false);
}
TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);
String name = industries.getName();
//industries.setName(name);
String descr = industries.getDescription();
//industries.setDescription(descr);
tvName.setText(name);
tvDescription.setText(descr);
return convertView;
}
and in my activity I have this
CompaniesRetriver companiesRetriver = new CompaniesRetriver();
this.recyclerView = (RecyclerView) findViewById(R.id.companies_list);
SharedPreferences editor = getSharedPreferences(MY_PREFERENCE, MODE_PRIVATE);
String token = editor.getString("token", "");
final Context sfdsf = this;
Callback<Companies> callback = new Callback<Companies>() {
#Override
public void onResponse(Call<Companies> call, Response<Companies> response) {
progressBar.dismiss();
if(response.isSuccessful()) {
progressBar.dismiss();
Companies companies = response.body();
CompanyAdapter adapter = new CompanyAdapter(CompaniesListActivity.this, companies);
recyclerView.setLayoutManager(new LinearLayoutManager(CompaniesListActivity.this));
recyclerView.setAdapter(adapter);
System.out.println(companies);
} else {
System.out.println(response.body());
}
}
#Override
public void onFailure(Call<Companies> call, Throwable t) {
progressBar.dismiss();
System.out.println(t.getLocalizedMessage());
}
};
companiesRetriver.getCompanies(callback, token);
My Log:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String al.sqmo.model.Industry.getName()' on a null object reference
my POJO class
#SerializedName("name")
private String name;
#SerializedName("id")
private int id;
#SerializedName("description")
private String description;
public Industry(String description, String name, int id) {
this.description = description;
this.name = name;
this.id = id;
}
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 int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
Any help is appreciated!
Try to check below line
String name = industries.getName();
Here industries object might be null that's why you are getting this error.
and if you have to show just one item then you don't need to use adapter , But if there are more then you can use it like below :-
private Context context;
private ArrayList<Industry> industryList;
public IndustryAdapter(Context context, Industry industry) {
industryList = new ArrayList();
industryList.add(industry);
this.context = context;
}
public IndustryAdapter(Context context, ArrayList<Industry> industryList) {
this.industryList=this.industryList;
this.context = context;
}
#Override
public int getCount() {
return industryList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.row_item, parent, false);
}
TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);
String name = industryList.get(position).getName();
String descr = industryList.get(position).getDescription();
tvName.setText(name);
tvDescription.setText(descr);
return convertView;
}

Saved ImageView not appearing after saving it as byte[]

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;
}

problem with getting items from database through intent

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);
}
}

Android Custom ArrayAdapter from SQLite results

I want to make a custom adapter out of my SQLite results, however, I'm stuck doing so :( How would I make a custom adapter out of this code?
I'm getting my Database records through my DbHelper.java
Here's my ListAdapter Class
public class ListAdapter extends ArrayAdapter<Note> {
Context mContext;
int layoutResourceId;
Note notes[] = null;
public ListAdapter(Context context, int layoutResourceId, Note[] notes) {
super(context, layoutResourceId, notes);
this.mContext = context;
this.layoutResourceId = layoutResourceId;
this.notes = notes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
NoteHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new NoteHolder();
holder.noteSubject = (TextView)row.findViewById(R.id.editTextSubject);
holder.noteDesc = (TextView)row.findViewById(R.id.editTextTODO);
row.setTag(holder);
}
else
{
holder = (NoteHolder)row.getTag();
}
Note note = notes[position];
holder.noteSubject.setText(note.noteSubject);
holder.noteDesc.setText(note.noteDescription);
return row;
}
static class NoteHolder
{
TextView noteSubject;
TextView noteDesc;
}
}
Here's my Note.java Class
public class Note {
int id;
String noteSubject;
String noteDescription;
public Note(){}
public Note(String note_subject, String note_desc){
super();
this.noteSubject = note_subject;
this.noteDescription= note_desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNoteSubject() {
return noteSubject;
}
public void setNoteSubject(String noteSubject) {
this.noteSubject = noteSubject;
}
public String getNoteDescription() {
return noteDescription;
}
public void setNoteDescription(String noteDescription) {
this.noteDescription = noteDescription;
}
}
MY DbHelper.java
This is what returns the data, i want to get these results into a Listview.
public List<Note> getAllNotes() {
List<Note> notes = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
int id = Integer.parseInt(cursor.getString(0));
String noteSubject = cursor.getString(1);
String noteDesc = cursor.getString(2);
Note note = new Note();
note.id = id;
note.noteSubject = noteSubject;
note.noteDescription = noteDesc;
notes.add(note);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
Log.d("getAllNotes()", notes.toString());
return notes;
}
Don't quite caught your question.
You just need to pass your data items inside the adapter and fill your custom views inside the getView(). I can't really see the problem. Here you have a nice tutorial about Usage of ArrayAdapter:https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView Hope this will help.

Categories