null pointer exception in OnOptionItemSelected - java

I am trying to delete multiple checked rows from listview when click on the delete icon on action bar. However i get these nullpointerexception, i think the problem would be on adapter and dbHelper as i only declare them, but i do not know how i can solve this.
public class MainActivity extends ActionBarActivity {
public static TaskerDbHelper dbHelper;
public static ListView listviewTasks;
public static List<Task> arrayTasks;
public static TaskAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new TaskerDbHelper(this);
arrayTasks = dbHelper.getAllTasks();
listviewTasks = (ListView) findViewById(R.id.Tasks_onDate);
adapter = new TaskAdapter(this,arrayTasks);
listviewTasks.setAdapter(adapter);
listviewTasks.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Intent detailIntent = new Intent(MainActivity.this, DetailTaskActivity.class);
detailIntent.putExtra("rowID", (int)id);
startActivity(detailIntent);
}
});
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId()){
case R.id.action_search:
return true;
case R.id.action_add:
Intent Addintent = new Intent(MainActivity.this, AddTaskActivity.class);
startActivity(Addintent);
return true;
case R.id.action_delete:
SparseBooleanArray checkedItems = listviewTasks.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++){
if(checkedItems.valueAt(i)){
dbHelper.deleteTask((int)adapter.getItemId(i));
}
}
listviewTasks.invalidateViews();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
and the log is
http://i.stack.imgur.com/OqLuN.png

My guess is to work with a extended ArrayAdapter. This worked like a charm for me for multiple click->delete listview.
I declared it all like this:
arrayAdapter = new ListAdapter(this,R.layout.list_item, **YOUR LIST**);
listview.setAdapter(arrayAdapter);
listview.setCacheColorHint(Color.TRANSPARENT);
selectedItems = new ArrayList<Integer>();
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
ArrayList<Integer> selectedIds = arrayAdapter.selectedid;
Integer pos = new Integer(position);
if(selectedIds.contains(pos)) {
selectedIds.remove(pos);
}
else {
selectedIds.add(pos);
}
arrayAdapter.notifyDataSetChanged();
}
});
The class I extended.
public class ListAdapter extends ArrayAdapter<ChartItem> {
Context context;
protected ArrayList<**YOUR LIST ITEM**> list;
LayoutInflater inflater;
ArrayList<Integer> selectedid;
public ListAdapter(Context context, int layoutResourceId ,ArrayList<ChartItem> ticket) {
super(context,layoutResourceId,ticket);
selectedid = new ArrayList<Integer>();
this.list = **ARRAY YOU WANT TO LIST**;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
public int getCount() {
return list.size();
}
public ChartItem getItem(int position) {
return list.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.list_item, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.rowTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ChartItem item = list.get(position);
TextView tv = (TextView) convertView.findViewById(R.id.rowTextView);
tv.setText(item.getName());
TextView tv2 = (TextView) convertView.findViewById(R.id.rowTextView2);
tv2.setText(String.valueOf(item.getPrice()));
if(selectedid.contains(position)){
tv.setBackgroundColor(Color.DKGRAY);
tv.setTextColor(Color.WHITE);
}
else{
tv.setBackgroundColor(Color.TRANSPARENT);
tv.setTextColor(Color.BLACK);
}
return convertView;
}
private class ViewHolder {
TextView name;
}
}
I really had allot of trouble with this aswell and I think this is the best way to do it so far.
If you need any more help or when you have questions about this code snippet let me know!

It is actually the checkedItems is null.
I actually wanna reach something like this. So when user checked the rows, they may delete or mark it as completed
http://i.stack.imgur.com/k4jKT.png
I solve it from another approaches like below.
case R.id.action_delete:
for(int i = 0; i < arrayTasks.size();i++){
if((CheckBox)listviewTasks.getChildAt(i).findViewById(R.id.selected) != null){
CheckBox cBox=(CheckBox)listviewTasks.getChildAt(i).findViewById(R.id.selected);
if(cBox.isChecked()){
dbHelper.deleteTask((int)adapter.getItemId(i));
}
}
}
adapter.notifyDataSetChanged();
return true;
I juz change the action_delete for the onoptionitemselected function.
[1]:

Related

Updating a GridView

I need to update my gridView when I click on an item. I've try a lot a things but nothing works.
I have the following code for my activity:
public class GameActivity extends AppCompatActivity implements IGameView{
public GridGame _gridGame = new GridGame();
public GamePresenter _presenter = new GamePresenter(this, _gridGame);
public ImageAdapter _imageAdapter = new ImageAdapter(this, _gridGame);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_help) {
Intent intent = new Intent(this, HelpActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final Context context = this;
final GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(_imageAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
_presenter.addPawn(position);
_imageAdapter.update(position, _presenter.actualPlayer);
Toast.makeText(context, "" + position,Toast.LENGTH_SHORT).show();
}
});
}
And imageAdapter's code :
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private GridGame _gridGame;
public ImageAdapter(Context c, GridGame grid) {
mContext = c;
_gridGame = grid;
}
public int getCount() {
return grid.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new ViewGroup.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
setGrid();
imageView.setImageResource(grid[position]);
return imageView;
}
private Integer[] grid = new Integer[42];
public void setGrid() {
for(int i = 0; i < 42; i++){
grid[i] = R.drawable.square;
}
}
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
}
When I click on a square (item on the gridview) i want that the view update a show an other image instead of the square. The update is done when I call update method on the ImageAdapter but the view don't update.
First you need to fix the methods to return the desired data for adapter to identify the item objects as
// return the new data from sourcein case of update
public Object getItem(int position) {
return grid[position];
}
// don't send 0 always
public long getItemId(int position) {
return position;
}
// invoke notifyDataSetChanged(); when there is a change in data source
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
notifyDataSetChanged();
}
You need to notify the adapter that a data element has changed. Try this update() method:
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
notifyDataSetChanged();
}
Ok, I've found the problem, I was setting the grid in the getView(int position, View convertView, ViewGroup parent); but it should be set in the constructor.
The problem was that it reset the value in the grid each time I click on an item, so the value didn't changed.

How to pass value from listview to the next activity

I'm new to android studios and am currently about to finish up on my first project. However, I'm stuck at the part where I have to pass the value selected from the listview to the next activity. I have tried researching on the codes but none seem to be able to work. Any help would be greatly appreciated.
DisplayProduct.java
public class DisplayProduct extends AppCompatActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseHelper databaseHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_product);
listView = (ListView)findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.display_product_row);
listView.setAdapter(listDataAdapter);
databaseHelper = new DatabaseHelper(getApplicationContext());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Object data = parent.getItemAtPosition(position);
//String value = data.toString();
}
});
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
if(cursor.moveToFirst())
{
do {
String contact,location,issue;
contact = cursor.getString(0);
location = cursor.getString(1);
issue = cursor.getString(2);
Information information = new Information(contact,location,issue);
listDataAdapter.add(information);
} while (cursor.moveToNext());
}
}
}
ListDataAdapter.java
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView Contact,Location,Issue;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.display_product_row, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.Contact = (TextView) row.findViewById(R.id.textView8);
layoutHandler.Location = (TextView) row.findViewById(R.id.textView18);
layoutHandler.Issue = (TextView) row.findViewById(R.id.textView90);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
Information information = (Information) this.getItem(position);
layoutHandler.Contact.setText(information.getContact());
layoutHandler.Location.setText(information.getLocation());
layoutHandler.Issue.setText(information.getIssue());
return row;
}
}
LocationDetail.java
public class LocationDetail extends AppCompatActivity {
private TextView Textv;
DatabaseHelper databaseHelper;
SQLiteDatabase sqlitedatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_detail);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_location_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
From DisplayProduct.java :
Intent intent = new Intent(this, LocationDetail.class);
Object data = parent.getItemAtPosition(position);
String message = data.toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
From LocationDetail.java:
Intent intent = getIntent();
String value = intent.getStringExtra(EXTRA_MESSAGE);

How to add data from a database to a recycler view using a cursor adapter?

So I have tried implementing my database with a recycler view and cursoradapter, but I am getting errors. I can not understand them well so I dont know if I did not implement the adapter right or if it is something else. Here are the java files:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.nick.mowen.receiptmanager.LOCATION";
public String Places[];
public RecyclerView RV;
private RVAdapter adapter;
Cursor mCursor;
ManagerDatabaseAdapter managerDatabaseAdapter;
List<MainInfo> mainInfo = new ArrayList<MainInfo>();
RecyclerView.LayoutManager layoutManager;
private Context activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
managerDatabaseAdapter = new ManagerDatabaseAdapter(this);
setContentView(R.layout.activity_main);
adapter = new RVAdapter(getActivity(), managerDatabaseAdapter.getTheCursor());
RV = (RecyclerView) findViewById(R.id.mainV);
layoutManager = new LinearLayoutManager(getActivity());
RV.setLayoutManager(layoutManager);
RV.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// getMenuInflater().inflate(R.menu.menu_main, li)
return true;
}
public static void getData () {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this,SettingsActivity.class);
intent.putExtra(EXTRA_MESSAGE,true);
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
return true;
}
return super.onOptionsItemSelected(item);
}
/*#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView userText= (TextView) view;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}*/
public void addInstance(View view) {
Intent intent = new Intent(this,LocationAdder.class);
intent.putExtra(EXTRA_MESSAGE,true);
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
}
public Context getActivity() {
return activity;
}
}
Here is the recycler view adapter:
public class RVAdapter extends Adapter<RVAdapter.MyViewHolder> {
private LayoutInflater inflater;
CursorAdapter mCursorAdapter;
Context mContext;
//Cursor cursor;
//public Cursor mCursor;
MainInfo mainInfo;
ManagerDatabaseAdapter.ManagerHelper managerHelper;
public ManagerDatabaseAdapter managerDatabaseAdapter;
// public List<MainInfo> mainInfoList = Collections.emptyList();
public RVAdapter (Context context, Cursor cursor) {
mContext = context;
mCursorAdapter = new CursorAdapter(mContext, cursor, 0) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//Cursor mCursor = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.custom_row, parent, false);
int nameCol = cursor.getColumnIndex("Codes");
String name = cursor.getString(nameCol);
TextView nameText = (TextView) view.findViewById(R.id.mainV);
if (nameText != null) {
nameText.setText(name);
}
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
int nameCol = cursor.getColumnIndex("Code");
String name = cursor.getString(nameCol);
TextView nameText = (TextView) view.findViewById(R.id.mainV);
if (nameText != null) {
nameText.setText(name);
}
}
};
//this.mainInfoList = mainInfoList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int i) {
/*MainInfo mainInfo = mainInfoList.get(i);
holder.Title.setText(mainInfo.get_Title());
holder.Body.setText(mainInfo.get_SubT());*/
mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
}
#Override
public int getItemCount() {
//return mainInfoList.size();
return mCursorAdapter.getCount();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView Title;
MyViewHolder(View itemView) {
super(itemView);
Title = (TextView) itemView.findViewById(R.id.Row_Header);
//Body = (TextView) itemView.findViewById(R.id.Row_Footer);
}
}
}
Here is the method to get the cursor:
public Cursor getTheCursor() {
String[] columns = {ManagerHelper.UID,ManagerHelper.NAME,ManagerHelper.CODE};
SQLiteDatabase db = helper.getWritableDatabase();
Cursor mCursor = db.query(ManagerHelper.TABLE_NAME, columns, null, null, null, null, null);
return mCursor;
}
And finally here is the error I am getting:
The problem is that in onCreate you're using the method getActivity() but you're never initializing the activity object.
Please try to change your onCreate to something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
managerDatabaseAdapter = new ManagerDatabaseAdapter(this);
setContentView(R.layout.activity_main);
adapter = new RVAdapter(this, managerDatabaseAdapter.getTheCursor());
RV = (RecyclerView) findViewById(R.id.mainV);
layoutManager = new LinearLayoutManager(this);
RV.setLayoutManager(layoutManager);
RV.setAdapter(adapter);
}
That should fix your NPE and you can see what other parts are missing. And remove the getActivity() method, you don't need that in an Activity it is used on a Fragment, so I supposed you copied that code from a Fragment implementation.
If you are running a query with a CursorLoader and you want RecyclerView instead of ListView.
You can try my CursorRecyclerViewAdapter CursorAdapter in RecyclerView
And also visit this reference link link

Delete Multiple Selected Items in ListView (cab) in android

I want to delete multiple selected items (row) in my listview (Gmail style).
If I select (with longClick) a row, nothing happens.
I've found this code on internet, and i've tried to insert it in my project.
MainActivity
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(Lista.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menu) {
switch (menu.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selectedItem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selectedItem);
}
}
actionMode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.delete_menu, menu);
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position,
long arg2, boolean arg3) {
final int checkedOut = Lista.getCheckedItemCount();
actionMode.setTitle(checkedOut + " selezionato");
adapter.toggleSelection(position);
}
and this is the adapter
public class ListaAdapter extends ArrayAdapter<ListViewItem> {
private Context context;
private ArrayList<ListViewItem> items;
private SparseBooleanArray mSelectedItemsIds;
public ListaAdapter(Context context, int resourceId,
ArrayList<ListViewItem> items) {
super(context, resourceId, items);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.items = items;
}
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtSubTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_view_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView
.findViewById(R.id.TitoloPrincipale);
holder.txtSubTitle = (TextView) convertView
.findViewById(R.id.Sottotitolo);
holder.imageView = (ImageView) convertView.findViewById(R.id.Image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListViewItem list = getItem(position);
holder.txtTitle.setText(list.getNomeFarmaco());
holder.txtSubTitle.setText(list.getFasceOrarie());
holder.imageView.setImageResource(list.getIcon());
// convertView
// .setBackgroundColor(mSelectedItemsIds.get(position)
// : Color.TRANSPARENT);
return convertView;
}
public void remove(ListViewItem item) {
items.remove(item);
notifyDataSetChanged();
}
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 int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
have you got any idea?
tks
That code has nothing to do with long-clicks. The only occurrence of "long" is for a long parameter to a method. :-)
This sample project demonstrates an action mode starting up based upon a long-click of a list row. The key is onItemLongClick():
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setItemChecked(position, true);
return(true);
}
Here (courtesy of registering the activity as the OnItemLongClickListener for the ListView), we toggle on CHOICE_MODE_MULTIPLE_MODAL and check the item that was long-clicked, thereby activating the action mode.
The major problem you have not setMultiChoiceModeListener for listview like below
(Plz, see carefully onCreateActionMode and the loop in onActionItemClicked)
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
mode.getMenuInflater().inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
// TODO Auto-generated method stub
switch (menuItem.getItemId()) {
case R.id.mnDelete:
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for(int i = sparseBooleanArray.size() -1; i >= 0; i--)
items.remove(sparseBooleanArray.keyAt(i));
adapter.notifyDataSetChanged();
mode.finish();
break;
default:
break;
}
return true;
}
});
}
I've solved. thank you all.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch (arg1.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selecteditem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selecteditem);
}
}
// Close CAB
arg0.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
arg0.getMenuInflater().inflate(R.menu.delete_menu, arg1);
return true;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode arg0, int arg1, long arg2,
boolean arg3) {
final int checkedCount = Lista.getCheckedItemCount();
arg0.setTitle(checkedCount + " Selected");
adapter.toggleSelection(arg1);
}
}

How do i call a context menu on longclick in a ListView Item?

HomeFragment
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
I just need 3 items on the context menu: Like, Comment and Favorite. I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.
Here´s my adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Are the changes supposed to go in the adapter or the fragment? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick. Any help would be appreciated.
I managed to get one context menu working, right here:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
adapter = new ListViewAdapter(getActivity(), arraylist);
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Opções");
menu.add(0, v.getId(), 0, "Like");
menu.add(1, v.getId(), 0, "Comment");
menu.add(2, v.getId(), 0, "Favorite");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
addLike(item.getItemId());
} else if (item.getTitle() == "Comment") {
} else if (item.getTitle() == "Favorite") {
// code
} else {
return false;
}
return true;
}
public void addLike(int id){
}
Right after the return rootView in the HomeFragment. Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case).
first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setAdapter(adapter);
then register for MultiChoiceModeListener and override his methods in your liking :)
myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// here you will inflate your CAB
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Here is the link

Categories