how to refresh listview on spinner selection in android - 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.

Related

Advanced search bar Crash [duplicate]

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

I am new In android here is my CustomAdaptor for listview with search option to show three column without api only connected with server

I am new in android. I am connecting with server Mysql not using any API.
This is my MachineSearch code. In this list3.get(position) gives me previous list like without filter old data.
Everythings works perfect, but when I search, I got Previous List3 data.
On search, I got new filter data, but When I click I get old. And I have to pass two data id which hidden and name to be show.
Thanks in advance
public class MachineSearchList extends AppCompatActivity {
SearchView searchView;
CustomAdaptor adapter;
ArrayList<String> list1;
ArrayList<String> list2;
ArrayList<String> list3;
ListView listView;
String dataItemName;
String dataItemId;
ArrayList<SearchSetterandGetter> arrayList = new ArrayList<SearchSetterandGetter>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
setContentView(R.layout.employeelist_main);
super.onCreate(savedInstanceState);
listView = (ListView) findViewById(R.id.listemp);
searchList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dataItemName = list3.get(position);
dataItemId = list2.get(position);
openActivityOne();
}
});
searchView = (SearchView) findViewById(R.id.searchview_lay_act_xml);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return false;
}
});
}
public void searchList() {
try {
ArrayList<MachineSetterGetter> machineList = null;
MachineSearch emp = new MachineSearch();
machineList = emp.getmachineSearch();
list1 = new ArrayList<>();
list2 = new ArrayList<>();
list3 = new ArrayList<>();
for (MachineSetterGetter machine : machineList) {
list1.add(machine.getiTemId());
list2.add(machine.getiTemCode());
list3.add(machine.getiTemName());
}
for (int i = 0; i < list1.size(); i++) {
SearchSetterandGetter model = new SearchSetterandGetter(list1.get(i), list2.get(i), list3.get(i));
arrayList.add(model);
}
adapter = new CustomAdaptor(getApplicationContext(), arrayList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
} catch (Exception exh) {
Log.e("******************", "check" + exh);
}
}
public void openActivityOne() {
Intent resultIntend = new Intent();
resultIntend.putExtra("result", dataItemName);
resultIntend.putExtra("hideId", dataItemId);
setResult(RESULT_OK, resultIntend);
finish();
}
}
my custom Adaptor
public class CustomAdaptor extends BaseAdapter {
Context applicationContext;
LayoutInflater inflater;
ArrayList<String> dataa1;
ArrayList<String> dataa2;
ArrayList<String> dataa3;
ArrayList<String> dataa3Search;
ArrayList<SearchSetterandGetter> modelList;
ArrayList<SearchSetterandGetter> arrayList;
public String getId;
public String getCode;
public String getName;
public CustomAdaptor(Context pplicationContext, ArrayList<SearchSetterandGetter> model) {
applicationContext=pplicationContext;
this.modelList=model;
this.arrayList = new ArrayList<SearchSetterandGetter>();
this.arrayList.addAll(modelList);
inflater = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return modelList.size();
}
#Override
public Object getItem(int position) {
return modelList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.employeeview_no_name, null);
TextView emp1 = (TextView) convertView.findViewById(R.id.empname1);
TextView emp2 = (TextView) convertView.findViewById(R.id.empname2);
TextView emp3 = (TextView) convertView.findViewById(R.id.empname3);
emp1.setText(modelList.get(position).getSno());
emp2.setText(modelList.get(position).getScode());
emp3.setText(modelList.get(position).getSearchName());
return convertView;
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
if (charText.length()==0){
modelList.addAll(arrayList);
}
else {
for ( SearchSetterandGetter model : arrayList){
if (model.getSearchName().toLowerCase(Locale.getDefault()).contains(charText)||model.getSno().toLowerCase(Locale.getDefault()).contains(charText)){
modelList.add(model);
}
}
}
notifyDataSetChanged();
// modelList.clear();
}
}
As I understood your adapter is not updating, try this. try to debug and check whether its updating or not
if(adapter !=null){
adapter = null;
}
adapter = new CustomAdaptor(this, arrayList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.notifyDataSetChanged();

Getting an EditText data from a ListView Adapter?

I am actually new to Android Programming and I am developing an application in which I have a listView,which only comprises of EditTexts (i.e.TextInputEditText).
I have added hints to the EditTexts, but I want to get values from the EditText that the users enter.
Here is my code:
MyItems.java
public class MyItem {
public String TextTitle;
EditText Message;
public MyItem(String title)
{
this.TextTitle = title;
}
public EditText getEditText() {
return Message;
}`enter code here`
public void setEditText(EditText msg) {
this.Message = msg;
}
}
MyAdapter.java
public class MyAdapter extends BaseAdapter {
private ArrayList<MyItem> listItems;
private Context context;
public MyAdapter(Context context, ArrayList<MyItem> listItems)
{
this.context=context;
this.listItems=listItems;
}
#Override
public int getCount()
{
return listItems.size();
}
#Override
public MyItem getItem(int position)
{
return listItems.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent)
{
View row;
ListViewHolder listViewHolder;
if(view == null) {
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.my_adapter, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvname = row.findViewById(R.id.tvname);
row.setTag(listViewHolder);
}
else
{
row = view;
listViewHolder = (ListViewHolder) row.getTag();
}
try {
MyItem myItem = getItem(position);
String text = myItem.TextTitle;
listViewHolder.tvname.setHint(text);
}
catch (NullPointerException exec)
{
Log.e(TAG, "Execption ");
}
EditText etText = (EditText)row.findViewById(R.id.etText);
listItems.get(position).setEditText(etText);
return row;
}
}
MainFragment
public class ExistingStudentFragment extends Fragment {
Button btnExisting, btnNew;
Button btnShow, btnSubmit;
ArrayList<MyItem> myitems=new ArrayList<>();
ArrayList<MyItem> myitems2=new ArrayList<>();
ArrayList<MyItem> myitems3=new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.existing_student_fragment,
container, false);
getTextView();
getTextView2();
getTextView3();
ListView listView, listView2, listView3;
final MyAdapter myAdapter, myAdapter2, myAdapter3;
listView = (ListView)view.findViewById(R.id.list_items);
myAdapter = new MyAdapter(getContext(), myitems);
listView2 = (ListView)view.findViewById(R.id.list_items2);
myAdapter2 = new MyAdapter(getContext(), myitems2);
listView3 = (ListView)view.findViewById(R.id.list_items3);
myAdapter3 = new MyAdapter(getContext(), myitems3);
listView.setAdapter(myAdapter);
listView2.setAdapter(myAdapter2);
listView3.setAdapter(myAdapter3);
Spinner spinner_pass = (Spinner)view.findViewById(R.id.spin_passtype);
List<String> passtype = new ArrayList<String>();
passtype.add("Ist Class");
passtype.add("IInd Class");
ArrayAdapter<String> SpinnerAdapter = new ArrayAdapter<String>
(this.getActivity(), android.R.layout.simple_spinner_item, passtype);
SpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdownitem);
spinner_pass.setAdapter(SpinnerAdapter);
btnExisting = (Button)view.findViewById(R.id.btnExisting);
btnNew = (Button)view.findViewById(R.id.btnNew);
btnShow = (Button)view.findViewById(R.id.btnshow);
btnSubmit = (Button)view.findViewById(R.id.btnsubmit);
btnExisting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((UserConcessionActivity)getActivity()).setViewPager(0);
}
});
btnNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((UserConcessionActivity)getActivity()).setViewPager(1);
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = myAdapter.getItem(0).getEditText().toString();
}
});
return view;
}
private void getTextView()
{
myitems.add(new MyItem("Admission Number:"));
myitems.add(new MyItem("Roll Number:"));
myitems.add(new MyItem("Name Of Student:"));
myitems.add(new MyItem("Stream:"));
}
private void getTextView2()
{
myitems2.add(new MyItem("Last Certificate Number(VCH No):"));
myitems2.add(new MyItem("Last Ticket from(Station):"));
myitems2.add(new MyItem("Last Ticket Number(Last 4 digits):"));
myitems2.add(new MyItem("Last Ticket Period(Monthly/Quaterly):"));
myitems2.add(new MyItem("Last Issued Date:"));
}
private void getTextView3()
{
myitems3.add(new MyItem("From Station:"));
myitems3.add(new MyItem("Pass Type(I or II):"));
myitems3.add(new MyItem("Ticket Period:"));
}
}
TextInputEditText extends from AppCompatEditText and,
From the documentation:
A special sub-class of EditText designed for use as a child of
TextInputLayout.
Using this class allows us to display a hint in the IME when in
'extract' mode.
So you should be able to get text like following codes from TextInputEditText:
String retrievedText = textInputName.getText().toString();
Don't forget to define in java-kotlin side with a prefix of your Fragment view (view in your case):
TextInputEditText textInputName = view.findViewById(R.id.edittext_edit_word_1);
And also in Xml layout.
There is also a good sample in here which you can use.

i have an issue with checked textview

i have used checked textview with base adapter to fill listview it's working fine but when i try to scroll CheckedTextView lost the selection.please find the code bellow and help me.
public class AttendancePage extends AppCompatActivity {
List<String> studentNames = new ArrayList<String>();
String[] sNames;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
databaseHelper = new DatabaseHelper(getApplicationContext());
Cursor res = databaseHelper.getStudentNames();
setTitle("Attendance Sheet");
ListView listView = (ListView) findViewById(R.id.listView);
while (res.moveToNext()) {
studentNames.add(res.getString(0));
}
sNames = new String[studentNames.size()];
sNames = studentNames.toArray(sNames);
Student_Attandence_Addapter customAdapter = new Student_Attandence_Addapter(getApplicationContext(), sNames);
listView.setAdapter(customAdapter);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
My custom Adapter class:
public class Student_Attandence_Adapter extends BaseAdapter {
String[] names;
Context context;
LayoutInflater inflter;
String value;
public Student_Attandence_Adapter(Context context, String[] names) {
this.context = context;
this.names = names;
inflter = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return names.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(names[position]);
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
value = "un-Checked";
simpleCheckedTextView.setCheckMarkDrawable(0);
simpleCheckedTextView.setChecked(false);
} else {
value = "Checked";
simpleCheckedTextView.setCheckMarkDrawable(R.drawable.checked);
simpleCheckedTextView.setChecked(true);
}
}
});
return view;
}
}
Basically what happens is the state of the ChekedTextView will be reset whenever the getView method will be called according to the previous cached state of the list item. So in short you need to store the checked state of an item and when the getView method will be called you need to set it again. For example you need an object containing name and checked state
public class Student {
private String name;
private boolean checked;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
}
and your getView method will be like this,
#Override
public View getView(int position, View view, ViewGroup parent) {
/*
* ListView caches the view so only inflate when there
* is no cached view aka null
*/
if (view == null) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
}
Student aStudent = students[position];
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(aStudent.getName());
simpleCheckedTextView.setCheckMarkDrawable(aStudent.isChecked() ? R.drawable.checked : 0);
simpleCheckedTextView.setChecked(aStudent.isChecked());
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
aStudent.setChecked(false);
notifyDataSetChanged();
} else {
aStudent.setChecked(true);
notifyDataSetChanged();
}
}
});
return view;
}
That's the theme. Modify it as you need.

Delete an item from Array List contact to Custom List View always delteing the latest one

I have a custom list view, contains delete button and spinner (the spinner contain A-E characters).
And I have an issue with deleting the true row from my custom list view.
Custom list view code:
public class customListView extends BaseAdapter
{
public Activity context;
ArrayList<MyActivity.UserProperties> userPropertieses;
public String[] spinnerValues;
public LayoutInflater inflater;
public customListView(Activity context, ArrayList<MyActivity.UserProperties> userPropertieses, String[] spinnerArray)
{
super();
this.context = context;
this.userPropertieses = userPropertieses;
spinnerValues = spinnerArray;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() { return userPropertieses.size(); }
#Override
public Object getItem(int i) { return null; }
#Override
public long getItemId(int i) { return 0; }
class ViewHolder
{
Button btnRemove;
Spinner spinner;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup)
{
final ViewHolder holder;
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.custom_layout, null);
holder.spinner = (Spinner) view.findViewById(R.id.spinner);
holder.btnRemove = (Button) view.findViewById(R.id.bu_Remove);
// populate spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(view.getContext(), android.R.layout.simple_spinner_item, spinnerValues);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setFocusable(true);
holder.spinner.requestFocus();
holder.spinner.setAdapter(dataAdapter);
view.setTag(holder);
// remove user implementation
holder.btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("custom list view debug", "i = " + i); // debug. verify i value is correct
((MyActivity) context).deleteUser(i);
}
});
}
else
holder = (ViewHolder) view.getTag();
return view;
}
}
And my main activity code looks like this:
public class MyActivity extends Activity
{
ListView listView;
ArrayList<UserProperties> userProperties = new ArrayList<UserProperties>();
customListView adapter;
SensorManager sensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
for (int i = 0; i<5; i++) {
userProperties.add(new UserProperties());
}
listView = (ListView) findViewById(R.id.listView);
String[] spinnerValues = new String[] {"A", "B", "C", "D", "E"};
adapter = new customListView(MyActivity.this, userProperties, spinnerValues);
listView.setAdapter(adapter);
}
public void deleteUser (int index)
{
Log.i("debug", "Removing item " + index); // the index is really true and the true node deleting from the ArrayList but somehow the latest delete from the UI
userProperties.remove(index);
adapter.notifyDataSetChanged();
}
}
When I click on the Remove button deleteUser method called with the right index. but although the right node deleting from userProperties ArrayList somehow after notiftDataSetChanged is still alive
and the latest node delete.
So, How can I delete the right node/row (from the ArrayList and UI...)
Thank you!
EDIT:
Just to be clear, i variable contain true index. The true node deleted from the ArrayList. but something append after I called notify method.
I prefer to stay with BaseAdapter and not implement ArrayAdapter. Thank you!
EDIT 2:
After more debugging I found out my question was wrong. the true row really deleted just spinner values somehow update their values. I cannot close the question because it already answered. Thanks.
((MyActivity) context).deleteUser(i);
This line will always delete the first value from the ListView
You can use CAB (contextual action bar)
See if the code helps you(it's basically a ListActivity with a custom adapter to hold the status of checked items(+ different background)):
public class CABSelection extends ListActivity {
private ArrayList<String> mItems = new ArrayList<String>();
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i = 0; i < 24; i++) {
mItems.add("Name" + i);
}
// R.layout.adapters_cabselection_row is a LinearLayout(with green
// background(#99cc00)) that wraps an ImageView and a TextView
mAdapter = new SelectionAdapter(this,
R.layout.adapters_cabselection_row, R.id.the_text, mItems);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.cabselection_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
StringBuilder sb = new StringBuilder();
Set<Integer> positions = mAdapter.getCurrentCheckedPosition();
for (Integer pos : positions) {
sb.append(" " + pos + ",");
}
switch (item.getItemId()) {
case R.id.edit_entry:
Toast.makeText(CABSelection.this, "Edited entries: " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.delete_entry:
Toast.makeText(CABSelection.this, "Deleted entries : " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.finish_it:
nr = 0;
mAdapter.clearSelection();
Toast.makeText(CABSelection.this, "Finish the CAB!",
Toast.LENGTH_SHORT).show();
mode.finish();
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
nr = 0;
mAdapter.clearSelection();
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " rows selected!");
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
l.setItemChecked(position, !mAdapter.isPositionChecked(position));
}
private class SelectionAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
public SelectionAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
v.setBackgroundColor(Color.parseColor("#99cc00")); //default color
if (mSelection.get(position) != null) {
v.setBackgroundColor(Color.RED);// this is a selected position so make it red
}
return v;
}
}
}
Another way
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
getView(final int i,
Do not make i final. You did that to use i in onClick(). But that is not possible. So remove the final. Add:
holder.btnRemove.setTag(i);
And in onClick:
int position = v.getTag();
..deleteUser(position);
Maybe you have to cast something somewhere..
Remark: You have to set the tag always. So do it just before return view;.
Please do not use an i for position.

Categories

Resources