Advanced search bar Crash [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to implement search in my app, and activity crashes when I click on search icon. The error is: https://i.imgur.com/CDOE9fT.png
Here is the code of Activity:
public class SearchActivity extends AppCompatActivity implements OnItemClickListener, AdapterView.OnItemClickListener {
DBHelper dbHelper;
SQLiteDatabase database;
ArrayList<Reminder> ReminderList = new ArrayList<>();
ListView listView;
MaterialSearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Material search");
toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));
dbHelper = new DBHelper(this);
database = dbHelper.getWritableDatabase();
//listView = (ListView) findViewById(R.id.ListOfReminders);
listView = (ListView)findViewById(R.id.ListOfReminders);
Cursor cursor = database.query(TABLE_REMINDERS, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
int idIndex = cursor.getInt(cursor.getColumnIndex(DBHelper.KEY_ID));
String nameIndex = cursor.getString(cursor.getColumnIndex(KEY_NAME));
String hourIndex = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_HOUR));
String dateIndex = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_DATE));
String name = nameIndex;
String hour = hourIndex;
String date = dateIndex;
ReminderList.add(new Reminder(idIndex, name, hour, date));
ReminderListAdapter2 adapter = new ReminderListAdapter2(this, R.layout.reminder_view2, ReminderList);
adapter.setListener(this);
listView.setAdapter(adapter);
} while (cursor.moveToNext());
} else
Log.d("mLog", "0 rows in db");
searchView = (MaterialSearchView)findViewById(R.id.search_view);
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
#Override
public void onSearchViewShown() {
}
#Override
public void onSearchViewClosed() {
listView = (ListView)findViewById(R.id.ListOfReminders);
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this, android.R.layout.simple_list_item_1,ReminderList);
listView.setAdapter(adapter);
}
}); searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText != null && !newText.isEmpty()){
ArrayList<Reminder> lstFound = new ArrayList<>();
for(Reminder item:ReminderList){
if(item.getName().contains(newText))
lstFound.add(new Reminder(item.getId(), item.getName(), item.getHour(), item.getDate()));
}
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this,android.R.layout.simple_list_item_1,lstFound);
listView.setAdapter(adapter);
} else {
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this,android.R.layout.simple_list_item_1,ReminderList);
listView.setAdapter(adapter);
}
return true;
}});
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_item,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void OnItemClick(View view, int position, int id, String name, String date, String hour) {
}}
Code of adapter:
public class ReminderListAdapter2 extends ArrayAdapter<Reminder> {
private Context mContext;
private int mResource;
OnItemClickListener listener;
public ReminderListAdapter2(#NonNull Context context, int resource, #NonNull ArrayList<Reminder> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
public void setListener(OnItemClickListener listener) {
this.listener = listener;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final int id = getItem(position).getId();
final String name = getItem(position).getName();
final String hour = getItem(position).getHour();
final String date = getItem(position).getDate();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
final TextView resId = convertView.findViewById(R.id.textId);
final TextView resName = convertView.findViewById(R.id.textName);
final TextView resHour = convertView.findViewById(R.id.textHour);
final TextView resDate = convertView.findViewById(R.id.textDate);
resId.setText(String.valueOf(id));
resName.setText(name);
resHour.setText(hour);
resDate.setText(date);
return convertView;
}}
Why object reference is null? Sorry if it is a stupid error, it's first app.
I tried to change lstFound.add(new Reminder(item.getId(), item.getName(), item.getHour(), item.getDate())); with lstFound.add(this);, but it is also null reference.

According to documentation:
To display a more custom view for each item in your dataset, implement a ListAdapter. For example, extend BaseAdapter and create and configure the view for each data item in
If so the first argument of layout inflater method should be layout instead of int
e.g convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
In your case you are trying to inflate int instead of layout
convertView = inflater.inflate(mResource, parent, false);

Closed.
The error was in ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this, android.R.layout.simple_list_item_1,ReminderList);
androidR.layout.simple_list_item_1 need to be changed to R.layout.reminderview2

Related

how to refresh listview on spinner selection in android

I'm trying to refresh my listview on spinner item selection. I know there have a lot of solution but i could not solve it.I have tried notifyDataSetChanged() but it's not working.
I'm new in android. Please help me i,m stuck on it.
Here is my Adapter class:
public class ListDataAdaptar extends ArrayAdapter {
List<DataProvider> mlist;
public ListDataAdaptar(Context context, int resource,List<DataProvider> list) {
super(context, resource);
mlist=list;
}
static class LayoutHandler{
TextView amount,date,title;
TextView total;
}
#Override
public int getCount() {
return mlist.size();
}
#Nullable
#Override
public Object getItem(int position) {
return mlist.get(position);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View mView= convertView;
LayoutHandler layoutHandler;
if (mView==null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView=layoutInflater.inflate(R.layout.display_income_row,parent,false);
layoutHandler=new LayoutHandler();
layoutHandler.title= (TextView) mView.findViewById(R.id.income );
layoutHandler.amount=(TextView)mView.findViewById(R.id.income_amount);
layoutHandler.date= (TextView) mView.findViewById(R.id.date);
mView.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) mView.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
Double s= new Double(dataProvider.getMoney());
layoutHandler.amount.setText(""+s);
layoutHandler.date.setText(dataProvider.getDate());
layoutHandler.title.setText(dataProvider.getName());
return mView;
}
}
And in this class i'm using Spinner:
public class IncomeReport extends AppCompatActivity {
ListView list;
Toolbar toolbar;
private DatabaseHandler handler;
private List<DataProvider> amountList;
private ListDataAdaptar listDataAdapter;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.income_report);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
list = (ListView)findViewById(R.id.listView);
amountList = new ArrayList<>();
handler = new DatabaseHandler(this);
}
public List getMonthItem() {
Cursor cursor = handler.displayIncomeMonthReport();
if (cursor.moveToFirst()) {
do {
double amount;
String payer;
String note;
String date;
amount = Double.parseDouble(cursor.getString(cursor.getColumnIndex(handler.AMOUNT)));
payer = cursor.getString(cursor.getColumnIndex(handler.PAYER_NAME));
note = cursor.getString(cursor.getColumnIndex(handler.NOTE));
date=cursor.getString(cursor.getColumnIndex(handler.DATE));
DataProvider provider = new DataProvider(amount, payer,note,date);
amountList.add(provider);
listDataAdapter = new ListDataAdaptar(this, R.layout.display_income_row, amountList);
list.setAdapter(listDataAdapter);
listDataAdapter.notifyDataSetChanged();
} while (cursor.moveToNext());
cursor.close();
handler.close();
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.spinner_menu, menu);
MenuItem item = menu.findItem(R.id.spinner);
spinner = (Spinner) MenuItemCompat.getActionView(item);
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.report, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final int number = getIntent().getExtras().getInt("pos1");
spinner.setSelection(number);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
switch (pos){
case (0):
getMonthItem();
listDataAdapter.notifyDataSetChanged();
break;
case (1):
getYearItem();
listDataAdapter.notifyDataSetChanged();
break;
default:
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return true;
}
}
First , I want to say that you should not new Adapter and setAdapter in getMonthItem() even in do...while ,do it in onCreate() is better. Then , when you select item , are you sure your data list has changed ? Check it again ,hope it helps.

ListView doesn`t filling

I faced with problem that I cant figure out. I have FragmentA and FragmentB. When I do first time transaction to FragmentB ListView doesn`t filling. If I press "back" and do transaction again, then ListView is filling.
Whats wrong with my code?
Here is my Fragment Code:
public class RegionListFrag extends android.support.v4.app.Fragment {
ArrayList<String> names = new ArrayList<>();
RegionAddAdapter regionAddAdapter;
ListView listView;
DBHelper dbHelper;
SQLiteDatabase db;
final String LOG_TAG = "myLogs";
RegionNameClass regionNameClass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((MainActivity)getActivity()).changeTbOn();
MainActivity.toolbar.setTitle("Regions");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.region_layout, container, false);
MainActivity.toolbar.setTitle("Regions");
listView = (ListView) rootView.findViewById(R.id.region_lv);
regionAddAdapter = new RegionAddAdapter(getActivity(),
setRv());
listView.setAdapter(regionAddAdapter);
listView.setPadding(0, 110, 0, 0);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_toolbar, menu);
super.onCreateOptionsMenu(menu,inflater);
Menu myMenu = menu;
MenuItem nextItem = myMenu.findItem(R.id.accept_category);
nextItem.setVisible(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
getFragmentManager().popBackStack();
getFragmentManager().beginTransaction().commit();
return true;
}
if (item.getItemId() == R.id.accept_category) {
}
return super.onOptionsItemSelected(item);
}
ArrayList<RegionNameClass> setRv(){
dbHelper = new DBHelper(getActivity());
db = dbHelper.getWritableDatabase();
Cursor c = db.query("regiontable", null, null, null, null, null,
null);
ArrayList<RegionNameClass> rvArray = new ArrayList<RegionNameClass>();
while(c.moveToNext()){
String name = c.getString(c.getColumnIndex("regNames"));
RegionNameClass regionObj = new RegionNameClass(name);
rvArray.add(regionObj);
}
Log.d(LOG_TAG, "array size - " + rvArray.size());
return rvArray;
}
}
Here is my Adapter:
public class RegionAddAdapter extends ArrayAdapter<RegionNameClass> {
private static ArrayList<RegionNameClass> list = new ArrayList<RegionNameClass>();
private final Activity context;
public ArrayList<RegionNameClass> selectedStrings = new ArrayList<RegionNameClass>();
final String LOG_TAG = "myLogs";
RegionNameClass regionNameClass;
public RegionAddAdapter(Activity context, ArrayList<RegionNameClass> top) {
super(context, R.layout.region_row, list);
this.context = context;
list = top;
}
static class ViewHolder {
protected TextView myTv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
RegionNameClass myClass = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.region_row, parent, false);
}
TextView tvName = (TextView) convertView.findViewById(R.id.region_tv);
tvName.setText(myClass.name);
return convertView;
}
}
Please check in RegionAddAdapter, update as below
public RegionAddAdapter(Activity context, ArrayList<RegionNameClass> top) {
super(context, R.layout.region_row, top);
this.context = context;
list = top;
}

SearchView doesn't work when searching rows in a custom listview

I have a project where I can add data,delete them and update them using SQLite. Of course I display them in a listview. The last thing I want to do is a use a searchView object,so the user can search the data he wants and check if they are there. However the SearchView object does nothing. I type on purpose something that exists in the listview and the matched row doesn't appear.
Here is my code.
public class DisplayForldersActivity extends AppCompatActivity {
DatabaseHandler dba;
private ArrayList<MyFolder> dbFolders = new ArrayList<>();
private FolderAdapter folderAdapter;
private ListView listView;
SearchView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_forlders);
listView = (ListView)findViewById(R.id.list);
inputSearch = (SearchView) findViewById(R.id.inputSearch);
fetchDataFromDB();
}
private void fetchDataFromDB() {
dbFolders.clear();
dba = new DatabaseHandler(getApplicationContext());
ArrayList<MyFolder> foldersFromDB = dba.getFolderDetails();
for(int i=0; i<foldersFromDB.size();i++){
String plateNo = foldersFromDB.get(i).getPlateNumber();
String owner = foldersFromDB.get(i).getOwnerName();
String cardId = foldersFromDB.get(i).getCardId();
String content = foldersFromDB.get(i).getContent();
String date = foldersFromDB.get(i).getRecordDate();
int mid = foldersFromDB.get(i).getItemId();
MyFolder f = new MyFolder();
f.setPlateNumber(plateNo);
f.setOwnerName(owner);
f.setCardId(cardId);
f.setContent(content);
f.setRecordDate(date);
f.setItemId(mid);
dbFolders.add(f);
folderAdapter = new FolderAdapter(DisplayForldersActivity.this,R.layout.folders_row,dbFolders);
listView.setAdapter(folderAdapter);
folderAdapter.notifyDataSetChanged();
inputSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
folderAdapter.getFilter().filter(newText);
return false;
}
});
}
dba.close();
}
And my adapter's code
private class FolderAdapter extends ArrayAdapter<MyFolder>{
Activity activity;
int layoutResource;
MyFolder myFolder;
ArrayList<MyFolder> mData = new ArrayList<>();
public FolderAdapter(Activity act, int resource, ArrayList<MyFolder> data) {
super(act, resource,data);
activity = act;
layoutResource = resource;
mData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MyFolder getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null || row.getTag()==null){
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource,null);
holder = new ViewHolder();
holder.mPlateNo = (TextView)row.findViewById(R.id.plateNumberList);
//holder.mOwner = (TextView)row.findViewById(R.id.ownerName);
holder.mcardId = (TextView)row.findViewById(R.id.idNumber);
//holder.mContent = (TextView)row.findViewById(R.id.processing);
holder.mDate = (TextView)row.findViewById(R.id.dateText);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
holder.myF = getItem(position);
holder.mPlateNo.setText(holder.myF.getPlateNumber());
//holder.mOwner.setText(holder.myF.getOwnerName());
//holder.mcardId.setText(holder.myF.getCardId());
//holder.mPlateNo.setText(holder.myF.getPlateNumber());
holder.mDate.setText(holder.myF.getRecordDate());
final ViewHolder finalHolder = holder;
holder.mPlateNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String dateText = finalHolder.myF.getRecordDate().toString();
String owner = finalHolder.myF.getOwnerName().toString();
String cardId = finalHolder.myF.getCardId().toString();
String plateNumber = finalHolder.myF.getCardId().toString();
String content = finalHolder.myF.getContent().toString();
int mid = finalHolder.myF.getItemId();
Intent i = new Intent(DisplayForldersActivity.this,DetailedFolderActivity.class);
i.putExtra("id",mid);
i.putExtra("owner",owner);
i.putExtra("cardId",cardId);
i.putExtra("plateNumber",plateNumber);
i.putExtra("content",content);
i.putExtra("dateText",dateText);
startActivity(i);
}
});
return row;
}
class ViewHolder{
MyFolder myF;
int mid;
TextView mPlateNo;
TextView mOwner;
TextView mcardId;
TextView mContent;
TextView mDate;
}
}
Did I do something wrong? Thanks
You need to call notifyDataSetChanged in the adapter attached to the listView to invalidate the ListView and make it draw the changed/removed/inserted lines.
Your array adapter needs to implement Filterable interface, which will override getFilter() method. Then in your getFilter() method you can perform your filtering opertion.
Check out this stackoverflow link, this code might help you out
No results with custom ArrayAdapter Filter
The SerchView doesn't handle any search, it is just a widget. You have to implement the search logic by your own. Try the solution described here:
http://developer.android.com/guide/topics/search/search-dialog.html
You can also do this by calling SearchView.setOnQueryTextListener(SearchView.OnQueryTextListener listener) and pass in a custom implementation of the listener.

Refresh ListView after deletion

I checked a lot of stack overflow question, and none of them helped.
How to refresh my listView after deleting item with onLongClickListener?
As you'll see nor adapter.notifyDataSetChanged(), nor listView.invalidateViews() don't work.
This is implementation with just necessary methods to figure out idea.
public class MainActivity extends AppCompatActivity {
public FloatingActionButton fabAddWord;
public Toolbar toolbar;
public ListView listView;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabAddWord = (FloatingActionButton) findViewById(R.id.fabAddWord);
listView = (ListView) findViewById(R.id.listView);
dbRjecnik = new RjecnikDB(this);
db = dbRjecnik.getWritableDatabase();
String query = "SELECT * FROM " + RjecnikDB.TABLE;
cursor = db.rawQuery(query, null);
adapter = new RjecnikCursorAdapter(this, cursor);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
deleteOnLongClick(cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC)));
adapter.notifyDataSetChanged();
listView.invalidateViews();
return true;
}
});
}
public void deleteOnLongClick(String rijec) {
SQLiteDatabase db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_RIJEC + " = ?", new String[] {rijec} );
this.adapter.notifyDataSetChanged();
this.listView.invalidateViews();
db.close();
}
CustomAdapter
public class RjecnikCursorAdapter extends CursorAdapter {
public RjecnikCursorAdapter (Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_word, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tvSingleLineWord = (TextView) view.findViewById(R.id.tvSingleLineWord);
// Extract properties from cursor
String rijec = cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC));
// Populate fields with extracted properties
tvSingleLineWord.setText(rijec);
}
}
The Adapter have a data cache, so data in ListView will not change when data in database changed. You should change the cursor.
#Override
public void changeCursor(Cursor cursor) {
mIndexer.setCursor(cursor);
super.changeCursor(cursor);
}
put code below to your OnItemLongClickListener
cursor = db.rawQuery(query, null);
adapter.changeCurosr(cursor);
You have to use just notifyDataSetChanged() to refresh your listView data, invalidateViews() will only redraw the visible items yet nothing on them has changed (changing font for example).
Note that is recommanded to run your notifyDataSetChanged() on UI thread.
EDIT 2 : you can use BaseAdapter instead of CursorAdapter like below
public class RjecnikCursorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<String> rjecnikList;
public RjecnikCursorAdapter(Activity activity, List<String> rjecnikList) {
this.activity = activity;
this.rjecnikList = rjecnikList;
}
#Override
public int getCount() {
return rjecnikList.size();
}
#Override
public Object getItem(int location) {
return rjecnikList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.item_word, null);
TextView tvSingleLineWord = (TextView) view.findViewById(R.id.tvSingleLineWord);
tvSingleLineWord.setText(String.valueOf(rjecnikList.get(position)));
return convertView;
}
}
And in your activity :
public class MainActivity extends AppCompatActivity {
public FloatingActionButton fabAddWord;
public Toolbar toolbar;
public ListView listView;
public List<String> mylist;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabAddWord = (FloatingActionButton) findViewById(R.id.fabAddWord);
listView = (ListView) findViewById(R.id.listView);
dbRjecnik = new RjecnikDB(this);
db = dbRjecnik.getWritableDatabase();
String query = "SELECT * FROM " + RjecnikDB.TABLE;
cursor = db.rawQuery(query, null);
mylist = new ArrayList<>();
if (cursor.moveToFirst()){
do{
//change this with your column data
String data = cursor.getString(cursor.getColumnIndex("data");
mylist.add(data);
}while(cursor.moveToNext());
}
cursor.close();
adapter = new RjecnikCursorAdapter(this, mylist);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
deleteOnLongClick(cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC)));
mylist.remove(position);
adapter.notifyDataSetChanged();
listView.invalidateViews();
return true;
}
});
}
public void deleteOnLongClick(String rijec) {
SQLiteDatabase db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_RIJEC + " = ?", new String[] {rijec} );
this.adapter.notifyDataSetChanged();
this.listView.invalidateViews();
db.close();
}

Cannot see listview in fragment

I am currently modifying an android app that I need to add a listview to an existing fragment. As I am new to android, I am just imitating the code from the apps. I created a new arrayadapter, a new class of data and made some modifies to the existing fragment class. The problem is I cannot see my list in the app. Below are my codes.
Adapter
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRec;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRec)
{
super(context, resourceId, checkInRec);
this.resourceId = resourceId;
this.context = context;
this.checkInRec = checkInRec;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_name);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkindate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_points);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
CheckInRecord.CheckInRec checkInrec = checkInRec.get(position);
textViewName.setText(checkInrec.providerName);
textViewCheckInDate.setText(checkInrec.checkInDate);
textViewPoints.setText(checkInrec.providerPoints);
ImageLoader.getInstance().displayImage(checkInrec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRec.get(position).isPrize);}
}
Data type
public class CheckInRecord {
public int userPoints;
public String userName;
public String gender;
public String birthDate;
public String location;
public String userIcon;
public List<CheckInRec> checkInRecList = new ArrayList<CheckInRec>();
public void addCheckInRec(String providerName, String providerLocation, String providerIcon,
String checkInDate, int providerPoints, int isPrize){
CheckInRec checkInRec = new CheckInRec();
checkInRec.providerName = providerName;
checkInRec.providerLocation = providerLocation;
checkInRec.providerIcon = providerIcon;
checkInRec.checkInDate = checkInDate;
checkInRec.providerPoints = providerPoints;
checkInRec.isPrize = isPrize;
checkInRecList.add(checkInRec);
}
public List<String> recImages(){
List<String> resultList = new ArrayList<String>();
if (this.checkInRecList == null){
return resultList;
}
for (CheckInRec rec : this.checkInRecList){
resultList.add(rec.providerIcon);
}
return resultList;
}
public class CheckInRec{
public String providerName;
public String providerLocation;
public String providerIcon;
public String checkInDate;
public int providerPoints;
public int isPrize;
}
}
Fragment
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRec = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppDataManager.getInstance().setAllowCheckIn(true);
progressDialog = ProgressDialog.show(getActivity(), "", "");
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) view.findViewById(R.id.tv_name);
textViewPoints = (TextView) view.findViewById(R.id.tv_points);
ListView listViewCheckInRec = (ListView) view.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity().getApplicationContext(), R.layout.row_record, checkInRec);
listViewCheckInRec.setAdapter(recordArrayAdapter);
return view;
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
refreshName();
}
}
public void refreshName() {
progressDialog = ProgressDialog.show(getActivity(), "", "");
AppDataManager dataManager = AppDataManager.getInstance();
ApiManager.getInstance().checkInHistories(dataManager.getUserToken(), dataManager.getUserPhone(), Utility.getPictureSize(), this);
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
// this.checkInRec.clear();
// this.checkInRec.addAll(checkInRecord.checkInRecList);
//
// recordArrayAdapter.notifyDataSetChanged();
}
}
}
The problem is I cannot see my list in the app.
That is because checkInRec does now have any elements inside of it.
I can really tell that it is empty because you commented this out:
// this.checkInRec.clear(); //clear the old data from the list
// this.checkInRec.addAll(checkInRecord.checkInRecList); //add all the data inside the checkInRecord.checkInRecList
//
// recordArrayAdapter.notifyDataSetChanged(); //refreshing the ListView to display the new data
now what are those doing is that clearing the old list array and adding the new set of data from checkInRecord.checkInRecList and refreshing the ListView so those new data are implemented/shown in your ListView.

Categories

Resources