I show items from my SQLite database in a Listview. For adding Items I use a AlertDialog. In the ALertDialog I save the item in my database and refresh the List (userLists) with the data from the database. Then I use notifyDataSetChanged but the view does't change.
public class MediUserListsFragment extends Fragment {
private MediDAO mediDAO;
private ListView listView;
private List<UserList> userLists;
private ArrayAdapter<UserList> adapter;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Medikamenten Listen");
final View view = inflater.inflate(R.layout.fragment_medi_user_list, container, false);
setHasOptionsMenu(true);
mediDAO = new MediDAO(getContext());
userLists = mediDAO.getAllUserList();
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1, userLists);
listView.setAdapter(adapter);
Button newLstBtn = (Button) view.findViewById(R.id.new_list_button);
newLstBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View alertLayout = inflater.inflate(R.layout.dialog_medi_list_new, null);
final EditText newLstName = (EditText) alertLayout.findViewById(R.id.newListName);
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Neue Liste");
alert.setView(alertLayout);
alert.setCancelable(false);
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setPositiveButton("Erstellen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mediDAO.newUserList(newLstName.getText().toString());
userLists = mediDAO.getAllUserList();
adapter.notifyDataSetChanged();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
});
return view;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_medi_abc, menu);
}
}
In your setPositiveButton, try the following.
userLists.clear();
userLists.addAll(mediDAO.getAllUserList());
adapter.notifyDataSetChanged();
When you were doing userLists = mediDAO.getAllUserList(); the adapter looses the original data object's reference (which is userLists). With userLists.addAll(), the adapter knows the data object it created with has changed hence, notifyDataSetChanged finds changes to notify.
Related
I am passing an integer array-list that hold the selection and retrieve it based on selection but when I remove the item from check selection it is not remove from array list displayed in text. Here is my logic to handle multiple check.
public class MainFragment extends Fragment {
private Button buttonUser;
String[] listItems;
boolean[] checkedItems;
ArrayList<Integer> mUserItems = new ArrayList<>();
private Context context;
private AppCompatTextView compatTextView;
public static MainFragment newInstance() {
return new MainFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listItems = getResources().getStringArray(R.array.person_array);
checkedItems = new boolean[listItems.length];
context = getActivity();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
buttonUser = (Button) view.findViewById(R.id.buttonUser);
compatTextView = (AppCompatTextView) view.findViewById(R.id.text_view_selection);
buttonUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Select Person");
alert.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(which)) {
mUserItems.add(which);
}
} else if (!mUserItems.contains(which)){
mUserItems.remove(which);
}
}
});
alert.setCancelable(false);
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String items = "";
for (int i = 0; i < mUserItems.size(); i++) {
items = items.concat(listItems[mUserItems.get(i)]);
if (i != mUserItems.size() - 1) {
items = items + ", ";
}
compatTextView.setText(items);
}
}
});
alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
});
return view;
}
}
And I am not getting this part of logic how to handle
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(which)) {
mUserItems.add(which);
}
} else if (!mUserItems.contains(which)){
mUserItems.remove(which);
}
}
It's somewhat correct but when I deselects the choice from alert dialog the list is not update and display the previous check data.
I think the else if part would yield false if isChecked is false. May be it should be like this?: else if (mUserItems.contains(which))
I have MainActivity, which holds fragment. One of my fragments (Participants) checks if there's anything in database. If no, shows fragment(EmptyParticipantsList) with message to add data. If yes, it shows fragment with TabHost with 2 tabs, one of them holds fragment (ParticipantsList) with ListView with database entries. There's a FAB button to add more records. How can I refresh ListView after adding another record? I'm not sure since TabHost is not working with FragmentManager which I'm using in app.
//TODO refresh ListView is the place where I need to put my code.
EDIT 6.5.2017
I modify the code and add 'myCursorAdapter.notifyDataSetChanged();' after adding/editting items in SQLite but List still not refresh it self. Any help?
Participants.java
myDB = new DBAdapter(getActivity());
myDB.open();
Class S;
if (myDB.isEmptyParticipants()) {
S = EmptyParticipantsList.class;
} else {
S = ParticipantsList.class;
}
myDB.close();
mTabHost = (FragmentTabHost) root.findViewById(R.id.tabHost);
mTabHost.setup(getContext(), getChildFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("List of participants"),
S, bundle1);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Event information"),
EventInfo.class, bundle1);
ParticipantsList.java
public class ParticipantsList extends DialogFragment {
DBAdapter myDB;
ListView participantList;
long id_eventu;
EditText participantName;
EditText participantSurname;
SimpleCursorAdapter myCursorAdapter;
public ParticipantsList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View root = inflater.inflate(R.layout.fragment_participants_list, container, false);
myDB = new DBAdapter(getContext());
participantList = (ListView) root.findViewById(R.id.list_participants);
myDB.open();
FloatingActionButton fab1 = (FloatingActionButton) root.findViewById(R.id.fab_participant);
Bundle bundle = getArguments();
if (bundle != null) {
id_eventu = bundle.getLong("key");
}
myDB.open();
Cursor cursor = myDB.getAllRowsParticipant(id_eventu);
String[] fromParticipantNames = new String[] {DBAdapter.PARTICIPANTS_NAME, DBAdapter.PARTICIPANTS_SURNAME};
int[] toViewIDs = new int[] {R.id.name_of_participant, R.id.surname_of_participant};
myCursorAdapter = new SimpleCursorAdapter(getActivity(),R.layout.row_participant, cursor, fromParticipantNames, toViewIDs,0 );
participantList.setAdapter(myCursorAdapter);
myCursorAdapter.notifyDataSetChanged();
myDB.close();
registerForContextMenu(participantList);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder addParticipantDialog = new AlertDialog.Builder(getContext());
addParticipantDialog.setTitle("Add new Participant");
final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
addParticipantDialog.setView(viewInflated);
participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
addParticipantDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//TODO zde se načtou data z polí a uloží do databáze
String name = participantName.getText().toString();
String surname = participantSurname.getText().toString();
myDB.open();
myDB.insertRowParticipant(name,surname, id_eventu);
Toast.makeText(getActivity(),"Participant added", Toast.LENGTH_LONG).show();
myDB.close();
myCursorAdapter.notifyDataSetChanged();
}
});
addParticipantDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
addParticipantDialog.show();
}
});
return root;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.event_popup, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final long id = info.id;
switch(item.getItemId()) {
case R.id.edit_event_popup:
final android.app.AlertDialog.Builder addEventDialog = new android.app.AlertDialog.Builder(getContext());
addEventDialog.setTitle("Edit participant");
final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
addEventDialog.setView(viewInflated);
participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
myDB.open();
Cursor c = myDB.db.rawQuery("SELECT * FROM participants WHERE _id=="+id, null);
c.close();
c.moveToFirst();
String name_par = c.getString(c.getColumnIndex("name"));
String surname_par = c.getString(c.getColumnIndex("surname"));
participantName.setText(name_par); //tady se musí načíst data z db
participantSurname.setText(surname_par);
addEventDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//TODO zde se načtou data z polí a uloží do databáze
String str = participantName.getText().toString();
String str1 = participantSurname.getText().toString();
ContentValues cv = new ContentValues();
cv.put("name",str);
cv.put("surname",str1);
myDB.db.update("participants", cv, "_id="+id, null);
Toast.makeText(getActivity(),"participant changed", Toast.LENGTH_LONG).show();
myDB.close();
myCursorAdapter.notifyDataSetChanged();
//TODO refresh listview
}
});
addEventDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
addEventDialog.show();
return true;
case R.id.delete_event_popup:
myDB.open();
myDB.deleteRowParticipant(id);
Toast.makeText(getActivity(),"participant deleted", Toast.LENGTH_LONG).show();
myCursorAdapter.notifyDataSetChanged();
//TODO když je to poslední záznam, tak nahodit empty frag
return true;
default:
return super.onContextItemSelected(item);
}
}
}
You should call notifyDataSetChanged after setAdapter
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.
participantList.setAdapter(myCursorAdapter);
myCursorAdapter.notifyDataSetChanged(); // this
myDB.close();
here is my code for ArrayAdapter. When i click on LinearLayout "cat" it gives error on dialog.show(). I don't know how to create custom dialog within ArrayAdapter class.
Everything work fine when i remove creating dialog part.
Thanks in advance
CategoryAdapter.java
public class CategoryAdapter extends ArrayAdapter<String> {
private final Context context;
String[] menu = new String[25] ;
String[] menu2 = new String[25];
String[] menu3 = new String[25];
private LayoutInflater inflater;
viewholder vh;
public CategoryAdapter(Context context, String [] menu,String [] menu2,String [] menu3) {
super(context, R.layout.categoryadapter, menu);
this.context = context;
this.menu = menu;
this.menu2=menu2;
this.menu3=menu3;
}
public View getView(final int position, View convertView, ViewGroup parent) {
{
vh=new viewholder();
if (inflater == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.categoryadapter, parent, false);
vh.cat=(LinearLayout) convertView.findViewById(R.id.category);
convertView.setTag(vh);
}
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
public class viewholder
{
LinearLayout cat;
}
}
Use context instead getContext()
final Dialog dialog = new Dialog(context);
Finally, Just pass context
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_LONG).show();
}
});
Try-
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
try this below link, hope you like it.
OrderDetailListAdatper adapter = new OrderDetailListAdatper(Yourclass.this,Resource,
listorderlistInfo);
//set your adapter..
in your adapter getview, paste that code and it works fine for me.
holder.btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder((Activity)_context);
alert.setMessage("Do you want to delete?");
alert.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int whichButton) {
OrderDetailListAdatper.this._listOrderListInfoAdapter
.remove(position); OrderDetailListAdatper.thisnotifyDataSetChanged();
}
});
alert.create().show(); // btw show() creates and shows it..
}
});
In your getView() method, Replace getContext() with your context variable.
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
//remaining code...
}
});
And in your initialization of CateogoryAdapter don't pass getApplicationContext(), instead pass in the context (Activity.this) like this.
CategoryAdapter adapter = CategoryAdapter(YourActivity.this, menu, menu2, menu3)
I have been working and messing with my code from last two days.
I have a List View in a Fragment and a Button .
On clicking a button i add the data to List View entered through Dialog
What I am unable to do is refresh the ListView after clicking Ok Button.
Here is my Code
However it loads when i exit the app and resume again
Any Help will be appreciated
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
final EditText input = new EditText(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
return new AlertDialog.Builder(getActivity())
.setView(input)
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String Value = input.getText().toString();
String normalizednumber = NormalizePhoneUtilities
.normalizePhoneNumber(Value);
ContactModel contactModel = new ContactModel(
"Hitesh", normalizednumber, String
.valueOf(3));
ContactsDatabaseWorker sm = new ContactsDatabaseWorker(
getActivity());
sm.AddSmartContact(contactModel);
databaseWorker = new ContactsDatabaseWorker(
getActivity());
// LinkedList<Cursor> list = new
// LinkedList<Cursor>();
// list=databaseWorker.getAllData();
run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
customAdapter = new CustomCursorAdapter(
getActivity(), databaseWorker
.getAllData());
customAdapter.notifyDataSetChanged();
listview.invalidateViews();
listview.refreshDrawableState();
listview.setAdapter(customAdapter);
}
};
getActivity().runOnUiThread(run);
isModal = false;
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (isModal) // AVOID REQUEST FEATURE CRASH
{
View view = inflater.inflate(R.layout.smartalert_fragment,
container, false);
listview = (ListView) view.findViewById(R.id.lvSmartAlert);
return super.onCreateView(inflater, container, savedInstanceState);
}
View view = inflater.inflate(R.layout.smartalert_fragment, container,
false);
Button bAdd = (Button) view.findViewById(R.id.bAddContact);
bAdd.setOnClickListener(this);
listview = (ListView) view.findViewById(R.id.lvSmartAlert);
new Handler().post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
customAdapter = new CustomCursorAdapter(getActivity(),
databaseWorker.getAllData());
listview.setAdapter(customAdapter);
}
});
return view;
}
Call notifyDataSetChanged (); in adapter.
Your CursorAdapter has a swapCursor() method, which you can use each time you get an updated cursor.
This is my MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
ArrayList<Product> products = new ArrayList<Product>();
final Context context = this;
ListAdapter boxAdapter;
String[] dataArray;
EditText editText;
//name that get back through the dialog
private String getName;
private String selectedItem;
private ArrayAdapter<String> adapter; // The list adapter
/** Called when the activity is first created. */
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
fillData();
boxAdapter = new ListAdapter(this, products);
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
Button btn = (Button) findViewById(R.id.AddItem);
//the add item button function
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
//get the dialog view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.insert);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
getName=userInput.getText().toString();
products.add(new Product(getName,false));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
// Create the listener for normal item clicks
OnItemClickListener itemListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long rowid) {
Toast.makeText(
getApplicationContext(),
"You have clicked on " + parent.getItemAtPosition(position).toString() + ".",
Toast.LENGTH_SHORT).show();
}
};
//the long press to delete function
OnItemLongClickListener itemLongListener = new OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Store selected item in global variable
selectedItem = parent.getItemAtPosition(position).toString();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Do you want to remove " + selectedItem + "?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
products.remove(selectedItem);
boxAdapter.notifyDataSetChanged();
Toast.makeText(
getApplicationContext(),
selectedItem + " has been removed.",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
// Signal OK to avoid further processing of the long click
return true;
}
};
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
}
void fillData() {
dataArray = getResources().getStringArray(R.array.ChecklistData);
for(String productName : dataArray)
{
products.add(new Product(productName,false));
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
This is ListAdapter.java
public class ListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
ListAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
/*((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);*/
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.box);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> box = new ArrayList<Product>();
for (Product p : objects) {
if (p.box)
box.add(p);
}
return box;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
}
};
}
OnItemClickListener and OnItemLongClickListener didn't function at all. Anyone help me out here.. I did diagnose the problem but it still doesn't have function
OnItemClickListener itemListener = new OnItemClickListener() {
OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {
You just define those variables but you don't assign them to your ListView.
You should call these lines somewhere:
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
UPDATE:
You also miss to register the list for context menu.
registerForContextMenu(lvMain);
implement View.OnItemClickListener and AdapterView.OnItemLongClickListener and their corresponding methods in your class.
initialize your views correctly (findViewById...)
set click listeners to your views (button.setOnClickListener(this) / button.setOnLongClickListener(this)
react to the push events in the implemented methods like:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
this.doSomething();
}
}
and
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//react to the view or react to the position
switch (view.getId()) {
case R.id.button:
this.doSomething();
}
return true;
}
You need to register listeners. Add following lines to the end of your onCreate() method.
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
I had the exact same problem. When onclick or onlongclick are enabled in the Layout; onitemclickListener wont work. Just remove the tags android:clickable and android:longclickable from your Layout XML resource and it will all work.