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.
Related
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;
}
}
I am trying to implement an ExpandableListView where each group has but one child under it. I have managed to populate the children correctly and implement a function to delete linked events from a calendar db. My problem is that each group displays the child i expect to see and one empty child fragment beneath it.
I tried hard coding to show only one child in my adapter but it just showed the blank child fragment instead of the populated data that i need.
I searched on here and did some tweaking to my xml files in regards to match_parent vs wrap_content but that didnt seem to make any difference at all.
I cant seem to figure out why its calling the blank fragment with each child item. When I run my delete code it will double my populated child as well until i refresh the list, if i run the delete code a third time it will add a third identically populated child until the list is refreshed, etc.
This is my Main Activity
public class MainActivityCalendarManager extends AppCompatActivity {
Context context;
View parentView;
ArrayList<String> titles;
ArrayList<Date> dates;
TreeMap<Date,ArrayList<CalendarManagerEvent>> dataSet;
ExpandableListEventAdapter eveAdpt;
ExpandableListView listView;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cal_mgr_activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Set the drawer icon
final ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_left);
actionBar.setDisplayHomeAsUpEnabled(true);
parentView = findViewById(android.R.id.content);
dates = new ArrayList<>();
titles = new ArrayList<>();
CoordinatorLayout layout = (CoordinatorLayout) findViewById(R.id.cal_mgr_activity_main);
getLayoutInflater().inflate(R.layout.cal_mgr_content_main, layout);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.cal_mgr_swipe_refresh);
context = this;
getDataFromCalendarTable();
listView = (ExpandableListView) findViewById(R.id.elv_main);
dataSet = new TreeMap<>();
dataSet = getDataFromEventTable();
eveAdpt = new ExpandableListEventAdapter(context,dates, dataSet,titles);
listView.setAdapter(eveAdpt);
listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
return false;
}
});
listView.setOnChildClickListener((ExpandableListView.OnChildClickListener) (parent, v, groupPosition, childPosition, id) -> {
TextView uid = (TextView) v.findViewById(R.id.tv_uid);
String mUid = uid.getText().toString();
deleteEvent(Long.parseLong(mUid));
// updateListView();
return true;
});
swipeRefreshLayout.setOnRefreshListener(() -> {
updateListView();
Log.i("refresh", "Layout Refreshed");
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
public void getSnackbar(View view, String text)
{
Snackbar.make(view, text, Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
public void updateListView()
{
dataSet = getDataFromEventTable();
eveAdpt.update(dates,dataSet);
eveAdpt.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(true);
}
// this reads the data from the calendar table
public void getDataFromCalendarTable() {
Cursor cur;
ContentResolver cr = getContentResolver();
String[] mProjection =
{
CalendarContract.Calendars.ALLOWED_ATTENDEE_TYPES,
CalendarContract.Calendars.ACCOUNT_NAME,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.CALENDAR_LOCATION,
CalendarContract.Calendars.CALENDAR_TIME_ZONE,
CalendarContract.Calendars._ID
};
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(context);
Uri uri = CalendarContract.Calendars.CONTENT_URI;
String selection = "((" + CalendarContract.Calendars.ACCOUNT_NAME + " = ?) AND ("
+ CalendarContract.Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ CalendarContract.Calendars.OWNER_ACCOUNT + " = ?))";
String[] selectionArgs = new String[]{mSharedPreference.getString("account_name",""), mSharedPreference.getString("account_type",""),
mSharedPreference.getString("owner_account","")};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR},0);
}
cur = cr.query(uri, mProjection, selection, selectionArgs, null);
while (cur.moveToNext()) {
String displayName = cur.getString(cur.getColumnIndex(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME));
String accountName = cur.getString(cur.getColumnIndex(CalendarContract.Calendars.ACCOUNT_NAME));
String ID = cur.getString(cur.getColumnIndex(CalendarContract.Calendars._ID));
}
cur.close();
}
// this is the main array for the information table contained in dataset
public TreeMap<Date,ArrayList<CalendarManagerEvent>> getDataFromEventTable() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR}, 0);
}
Cursor cur;
ContentResolver cr = getContentResolver();
String[] mProjection =
{
"_id",
CalendarContract.Events.CALENDAR_ID,
CalendarContract.Events.TITLE,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND,
CalendarContract.Events.DESCRIPTION,
CalendarContract.Events._ID
};
Uri uri = CalendarContract.Events.CONTENT_URI;
String selection = CalendarContract.Events.CALENDAR_ID + " = ? ";
// this sets every calendar to the same ID so I dont end up with 300
// individual calendars (Calendar In Use Is Local#16)
String[] selectionArgs = new String[]{"16"};
cur = cr.query(uri, mProjection, selection, selectionArgs, null);
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(CalendarContract.Events.CALENDAR_ID))) == 16) {
try {
int id = Integer.parseInt(cur.getString(cur.getColumnIndex(CalendarContract.Events.CALENDAR_ID)));
String title = cur.getString(cur.getColumnIndex(CalendarContract.Events.TITLE));
long dtstart = Long.parseLong(cur.getString(cur.getColumnIndex(CalendarContract.Events.DTSTART)));
long dtend = Long.parseLong(cur.getString(cur.getColumnIndex(CalendarContract.Events.DTEND)));
String desc = cur.getString(cur.getColumnIndex(CalendarContract.Events.DESCRIPTION));
String eventID = cur.getString(cur.getColumnIndex(CalendarContract.Events._ID));
// functions related to getting the date formatted correctly
Date testDate = new Date(dtstart);
Calendar cal = Calendar.getInstance();
cal.setTime(testDate);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
Date inputDate = cal.getTime();
// end date related code
CalendarManagerEvent calendarManagerEvent = new CalendarManagerEvent(id, title, desc, dtstart, dtend, eventID);
if(dataSet.get(inputDate)== null)
{
ArrayList<CalendarManagerEvent> calendarManagerEvents = new ArrayList<>();
calendarManagerEvents.add(calendarManagerEvent);
dataSet.put(inputDate, calendarManagerEvents);
dates.add(inputDate);
titles.add(title);
}
else
{
ArrayList<CalendarManagerEvent> datesArrayList = dataSet.get(inputDate);
boolean unique = true;
for(CalendarManagerEvent e : datesArrayList)
{
if (e.getUid().equals(calendarManagerEvent.getUid())) {
unique = false;
break;
}
}
if(unique) {
datesArrayList.add(calendarManagerEvent);
dataSet.remove(inputDate);
titles.remove(title);
dataSet.put(inputDate, datesArrayList);
titles.add(title);
}
}
}
// just error messages
catch(Exception e)
{
Log.e("Error", e.getMessage());
Log.e("start time",cur.getString(cur.getColumnIndex(CalendarContract.Events.DTSTART)));
Log.e("end time",cur.getString(cur.getColumnIndex(CalendarContract.Events.DTEND)));
}
}
}
cur.close();
// bundle everything up into the dataset
return dataSet;
}
private void deleteEvent(long eventID) {
Uri deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
int rows = getContentResolver().delete(deleteUri, null, null);
Log.i("Calendar", "Rows deleted: " + rows);
eveAdpt.notifyDataSetChanged();
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
This is my Adapter
public class ExpandableListEventAdapter extends BaseExpandableListAdapter {
private final Context context;
private ArrayList<Date> dates;
private ArrayList<String> titles;
private TreeMap<Date,ArrayList<CalendarManagerEvent>> dataSet;
private SparseBooleanArray mSelectedItemsIds;
LayoutInflater inflater;
private boolean isLastChild = true;
ListPopupWindow listPopupWindow;
String[] uid = {"Delete"};
ExpandableListEventAdapter(Context context) {
inflater = LayoutInflater.from(context);
this.context = context;
}
public ExpandableListEventAdapter(Context context, ArrayList<Date> dates, TreeMap<Date,ArrayList<CalendarManagerEvent>> events, ArrayList<String> titles)
{
this.context = context;
this.dates = dates;
this.dataSet = events;
this.titles = titles;
}
#Override
public int getGroupCount() {
return this.dates.size();
}
#Override
public int getChildrenCount(int listPosition) {
Date key = this.dates.get(listPosition);
return this.dataSet.get(key).size()+1;
}
#Override
public Object getGroup(int listPosition) {
return this.dates.get(listPosition);
}
#Override
public Object getChild(int listPosition, int expandedListPosition)
{
return this.dataSet.get(this.dates.get(listPosition)).get(expandedListPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int listPosition, int expandedListPostion) {
return expandedListPostion;
}
#Override
public boolean hasStableIds() {
return false;
}
// This is just for the first parent expandable list view item
#Override
public View getGroupView(int listPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Date date = dates.get(listPosition);
String title = titles.get(listPosition);
if(convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.cal_mgr_groupview_listitem,null);
}
TextView dateView = (TextView) convertView.findViewById(R.id.tv_groupView_date);
TextView titleView = (TextView) convertView.findViewById(R.id.tv_main_title);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateView.setText(dateFormat.format(date.getTime()));
titleView.setText(title);
return convertView;
}
// this sets the child items on expandable list view item
#Override
public View getChildView(int listPosition, int expandedListPosition, boolean isLastChild, View itemView, ViewGroup parent) {
TextView desc, uid;
//create the list item
if(itemView == null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
itemView = inflater.inflate(R.layout.cal_mgr_childview_listitem, parent, false);
}
if(expandedListPosition<getChildrenCount(listPosition)-1) {
final CalendarManagerEvent currentCalendarManagerEvent = (CalendarManagerEvent) getChild(listPosition,expandedListPosition);
// declare the textviews
desc = (TextView) itemView.findViewById(R.id.tv_groupView_desc);
uid = (TextView) itemView.findViewById(R.id.tv_uid);
// set the text in above views
desc.setText(currentCalendarManagerEvent.getDesc());
uid.setText(currentCalendarManagerEvent.getUid());
}
return itemView;
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public void update(ArrayList<Date> dates,TreeMap<Date,ArrayList<CalendarManagerEvent>> events){
this.dates = dates;
this.dataSet = events;
notifyDataSetChanged();
}
private class ViewHolder {
TextView title;
TextView date;
TextView desc;
TextView uid;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
}
And this is my event holder
public class CalendarManagerEvent {
private String eventID;
private String title;
private String desc;
public CalendarManagerEvent(int id, String title, String desc, long dtstart, long dtend, String eventID)
{ // This is the model for the array that is made for listview items
this.title = title;
this.desc = desc;
this.eventID = eventID;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDesc() {
return desc;
}
public String getUid()
{
return eventID;
}
}*
Any help would be greatly appreciated. A quick note, I'm relatively new to this so the dumber you can make it the easier it will be for me to follow.
Thank you in advance.
Why are you returning dataSet.get(key).size()+1 in public int
getChildrenCount(int listPosition) of ExpandableListEventAdapter when
dataSet.get(key).size() is enough to return size. I mean why +1 added.
Trying removing it.
when i remove the +1 it does then show only one child. (this is the goal)
The problem now being it does not populate that child with any information, just the generic text from my layout file. That was the same result as when I tried to hardcode it to just 1.
why would my child populate when there are 2 views but now that i have eliminated the extra view it does not populate?
Edit : I had to move the end of my if statement in getChildView of the adapter to the end of my getChildView code that sets the textviews.I also got rid of the if(expandedListPosition<getChildrenCount(listPosition)-1) line that was in the same statement.
Thank you for your timely reply. I will mark it correct.
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;
}
}
I am creating an list view inside fragment but it is not displaying i have stuck.I am passing data from mainActivity.java to OrderDetailsAdapter.java but getview() function is not getting called and getcount returning nonzero
Here is my code
OrderDetailsAdapter.java
public class OrderDetailsAdapter extends ArrayAdapter<OrderDetails> {
Context context;
int resource;
private List<OrderDetails> orderList = new ArrayList<OrderDetails>();
public OrderDetailsAdapter(Context context, int resource) {
super(context, resource);
this.context = context;
this.resource = resource;
}
#Override
public void add(OrderDetails object) {
orderList.add(object);
Log.v("getcount", "addItems " + getCount());
super.add(object);
}
#Override
public int getCount() {
int size = orderList.size();
Log.v("getcount","getcount "+ size);
return orderList.size();
}
#Override
public OrderDetails getItem(int index) {
return orderList.get(index);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.v("getcount","I am getting called");
View row = convertView;
OrderDetailsHolder holder = null;
if(row == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(context);
row = layoutInflater.inflate(resource,parent,false);
holder = new OrderDetailsHolder();
holder.patientName = (TextView)row.findViewById(R.id.order_list_view_patient_name);
holder.price = (TextView)row.findViewById(R.id.order_list_view_price);
holder.medicineList = (TextView)row.findViewById(R.id.order_list_view_medicine_list);
holder.expirationTime = (TextView)row.findViewById(R.id.order_list_view_expiration_time);
holder.expirationText = (TextView)row.findViewById(R.id.order_list_view_order_expire_text);
holder.cancelOrder = (TextView)row.findViewById(R.id.order_list_view_cancel_order);
holder.openOrder = (TextView)row.findViewById(R.id.order_list_view_open_order);
//Assigning custom fonts
Typeface typeface = Typeface.createFromAsset(context.getAssets(),"fonts/gothic.ttf");
holder.patientName.setTypeface(typeface);
holder.price.setTypeface(typeface);
holder.expirationTime.setTypeface(typeface);
holder.medicineList.setTypeface(typeface);
holder.expirationText.setTypeface(typeface);
holder.cancelOrder.setTypeface(typeface);
holder.openOrder.setTypeface(typeface);
row.setTag(holder);
}
else {
holder = (OrderDetailsHolder)row.getTag();
}
final OrderDetails details = getItem(position);
Log.v("AAAA",details.toString());
// OrderDetails orderDetails1 = orderList[position];
holder.patientName.setText(details.getPatientName());
holder.price.setText(String.valueOf(details.getPrice()) +" /-");
holder.medicineList.setText(Arrays.toString(details.getMedicineList()));
holder.expirationTime.setText(String.valueOf(details.expirationTime)+" mins");
return row;
}
static class OrderDetailsHolder {
TextView patientName;
TextView price;
TextView medicineList;
TextView expirationTime;
TextView expirationText;
TextView openOrder;
TextView cancelOrder;
}}
OrderDetails.java
public class OrderDetails {
public String patientName;
public float price;
public String medicineList[];
public int expirationTime;
public OrderDetails()
{
super();
}
public OrderDetails(String patientName,float price,String[] medicineList,int expirationTime)
{
this.patientName = patientName;
this.price = price;
this.medicineList = medicineList;
this.expirationTime = expirationTime;
}
public String getPatientName(){
return patientName;
}
public float getPrice() { return price; }
public String[] getMedicineList() { return medicineList; }
public int getExpirationTime() { return expirationTime; }}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap.ic_icon_home);
TextView userAddress = (TextView) findViewById(R.id.navigationDrawerHeaderTextView2);
userAddress.setText("52N 12, Pratap Nagar");
replaceFragment(R.layout.fragment_order_list, null);
//Set adapter for Order List
String medicineList[] = {"Paracetamol","Crocin","Azithomycin","Strepsils"};
orderDetails = new OrderDetails("Ravi Gupta",220,medicineList,20);
OrderDetailsAdapter orderDetailsAdapter = new OrderDetailsAdapter(this,R.layout.order_list_view_items);
orderDetailsAdapter.add(orderDetails);
orderDetailsAdapter.add(orderDetails);
orderDetailsAdapter.add(orderDetails);
orderDetailsAdapter.add(orderDetails); }
HELP PLZ
do this public OrderDetailsAdapter(Context context, int resource,List<OrderDetails> orderList) {
super(context, resource);
this.context = context;
this.resource = resource;
this.orderList = orderList;
} and this OrderDetailsAdapter orderDetailsAdapter = new OrderDetailsAdapter(this,R.layout.order_list_view_items,orderList);
I am trying to add check box and some text view (text view is getting value from database) in customized list view but it is giving error of NullPointerException. I don't know why and what is wrong with my code. Below is my code.
My MainActivity Class:
public class Classes extends Activity {
ImageView imageViewNewClass;
ListView mListView;
String[] stg1;
List<String[]> names2 = null;
DataManipulatorClass dataManipulator;
CustomAdapter customAdapter;
public Classes classes = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classes);
imageViewNewClass = (ImageView) findViewById(R.id.newclass);
mListView = (ListView) findViewById(R.id.displaydata);
imageViewNewClass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Classes.this, Class_Create.class);
startActivity(intent);
}
});
Resources res =getResources();
classes = this;
dataManipulator = new DataManipulatorClass(this);
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg = null;
for (String[] name : names2) {
stg = "Class Name : " + name[1];
stg1[x] = stg;
x++;
}
customAdapter= new CustomAdapter( classes, stg1,res );
mListView.setAdapter( customAdapter );
customAdapter.notifyDataSetChanged();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Listview item clicked", Toast.LENGTH_LONG).show();
}
});
}
}
CustomAdapterClass.java
public class CustomAdapter extends BaseAdapter {
/*********** Declare Used Variables *********/
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Resources res;
int i = 0;
String[] stg1;
List<String[]> names2 = null;
DataManipulatorClass dataManipulator;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, String[] stg1, Resources resLocal) {
/********** Take passed values **********/
activity = a;
data = stg1;
res = resLocal;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.length <= 0)
return 1;
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public CheckBox checkBox;
public TextView textView;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.check, null);
holder = new ViewHolder();
holder.checkBox = (CheckBox) vi.findViewById(R.id.checkBox1);
holder.textView = (TextView) vi.findViewById(R.id.selection);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
if (data.length <= 0) {
holder.textView.setText("No Data");
} else {
dataManipulator = new DataManipulatorClass(this);
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg = null;
for (String[] name : names2) {
stg = "Class Name : " + name[1];
stg1[x] = stg;
x++;
}
holder.textView.setText(stg1[x]);
}
return vi;
}
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked=====");
}
}
DataManipulator.Java
public class DataManipulatorClass {
private static final String DATABASE_NAME = "mydatabaseclass.db";
private static final int DATABASE_VERSION = 1;
static final String TABLE_NAME = "newtableclass";
private static Context context;
static SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME
+ "(classname) values (?)";
public DataManipulatorClass(Context context) {
DataManipulatorClass.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulatorClass.context);
DataManipulatorClass.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulatorClass.db.compileStatement(INSERT);
}
public DataManipulatorClass(CustomAdapter customAdapter) {
OpenHelper openHelper = new OpenHelper(DataManipulatorClass.context);
DataManipulatorClass.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulatorClass.db.compileStatement(INSERT);
}
public long insert(String classname) {
this.insertStmt.bindString(1, classname);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME,
new String[] { "id", "classname" }, null, null, null, null,
"classname asc");
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public void delete(int rowId) {
db.delete(TABLE_NAME, null, null);
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "
+ TABLE_NAME
+ " (id INTEGER PRIMARY KEY, classname TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
In Classes Class I have listview in which i want to show the data, My logcat is here http://i.share.pho.to/9739fdca_o.png
It is giving error on mListView.setAdapter( customAdapter ); this line while setting adapter in listview as a customadapter...
Thanks in advance...
public class Classes extends Activity {
ImageView imageViewNewClass;
ListView mListView;
String[] stg1; // Never Initialized in code before passing to Adapter
// stg1, this variable you have never initialized in your activity, you are passing it Null to your custom adapter, thats why listview while accessing count of data throwing NPE vai adapter.
public int getCount() { // Will always be Null, as data is null
if (data.length <= 0)
return 1;
return data.length;
}
Just pass a not null instance of variable in activity and your problem will be resolved.
You replace
if (data.length <= 0) return 1;
to
if (data == null || data.length == 0) return 1;