Call notifyDataSetChanged() on adapter from menu - android

I have an app that creates custom array adapter called StabelArrayAdapter which based on the ArrayAdapter class. It is created in the onCreate() method of the activity and I want to refresh it from a menu when the view changes. I can't access the adapter from the menu and I can't make it public.
How can I refresh the list view from a menu?
Greg
public void onCreate(Bundle savedInstanceState) {
final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, listNames);
listview.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.list_add:
Toast.makeText(getApplicationContext(), "Add new list" , Toast.LENGTH_LONG)
.show();
return true;
case R.id.list_delete:
//change data here
final ListView listview = (ListView) findViewById(R.id.ListLists);
//--> Cannot resolve symbol 'adapter'
adapter.notifyDataSetChanged();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

You need to make the adapter a class member and then you can reference it.
private StableArrayAdapter adapter;
public void onCreate(Bundle savedInstanceState) {
adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, listNames);
listview.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.list_add:
Toast.makeText(getApplicationContext(), "Add new list" , Toast.LENGTH_LONG)
.show();
return true;
case R.id.list_delete:
//change data here
final ListView listview = (ListView) findViewById(R.id.ListLists);
adapter.notifyDataSetChanged();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Related

Same Options Menu Over Activities, Invalid method declaration; return type required

I have multiple activities in my project which use the same options menu. Because of this I'm trying to use a single class for the option menu fuctions, however when I try call the functions I get this error:
Invalid method declaration; return type required
When I assign the function to a variable I get this error from:
Error -- Expression expected
boolean optionCreate = super.onCreateOptionsMenu(menu);
and:
Error -- Cannot resolve symbol 'item'
boolean optionSelect = super.onOptionsItemSelected(item);
Creating these fields causes the activity that is using the options menu to not load.
The code I'm using is:
MainActivity.java
public class mainActivity extends OptionsMenu {
ListView listView;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("Pick A Room");
listView = (ListView) findViewById(R.id.listview);
Intent intent = getIntent();
String name = intent.getStringExtra("NAME");
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Big Fish");
arrayList.add("Little Fish");
arrayList.add("Cardboard Box");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
openDialog();
}
});
}
public void openDialog(){
TryAgainErrDialog errDialog = new TryAgainErrDialog();
errDialog.show(getSupportFragmentManager(), "error dialog");
}
boolean optionCreate = super.onCreateOptionsMenu(menu);
boolean optionSelect = super.onOptionsItemSelected(item);
}
OptionsMenu.java
public class OptionsMenu extends AppCompatActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.appbar, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_back:
return true;
case R.id.action_songQueue:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
No need to call those method. It will invoke automatically by the system. Remove those from your code.
//boolean optionCreate = super.onCreateOptionsMenu(menu);
//boolean optionSelect = super.onOptionsItemSelected(item);

put Activity into Tablayout

I have this activity with some adapters , I would put it in tableLayout I already try some methods ,
unfortunately they didn't work , ( extends FragmentActivity , Convert Activity to Fragment with using onCreateView() )
`public class MainActivity_Delete extends AppCompatActivity` {
private SwipeMenuListView listView;
private ArrayList<Data> dataArrayList;
private ListAdapter listAdapter;
private Data data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete);
listView = (SwipeMenuListView) findViewById(R.id.listview);
dataArrayList = new ArrayList<>();
listAdapter = new ListAdapter(this, dataArrayList);
listView.setAdapter(listAdapter);
listView.setMenuCreator(creator);
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
Toast.makeText(MainActivity_Delete.this, "Delete", Toast.LENGTH_SHORT).show();
Log.e("item", String.valueOf(listView.getAdapter().getItem(position)));
Log.e("name", String.valueOf(dataArrayList.get(position).getName()));
dataArrayList.remove(position);
listAdapter.notifyDataSetChanged();
break;
case 1:
// delete
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
}
SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getApplicationContext());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.parseColor("#F45557")));
// set item width
deleteItem.setWidth(150);
deleteItem.setTitle("Delete");
deleteItem.setTitleColor(Color.WHITE);
deleteItem.setTitleSize(15);
// add to menu
menu.addMenuItem(deleteItem);
}
};
}
There is android.app.ActivityGroup but this class has been deprecated since API level 13. So, in essence you cannot embed an activity in another activity. You can reuse layout files, however. See Re-using Layouts with <include/> The best option is, of course, to make use of fragments. They are the standard for such things.

saving items in Parse query adapter in main activity to favorites adapter by click

I want to be able to touch the items in the main activity and once touch the item will save to the favorites class. I'm assuming I need to implement and OnItemClickListener but I am having trouble implementing it correctly. please help
Also do I need to add another intent code and place the onclicklistener inside of there? If more information is needed please let me know, I have been stuck on this issue for awhile now. Thank you
This is my main activity code
import com.parse.ParseQueryAdapter;
public class WingmanListActivity extends ListActivity {
private ParseQueryAdapter<Tip> mainAdapter;
private FavoriteTipAdapter favoritesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setClickable(true);
mainAdapter = new ParseQueryAdapter<Tip>(this, Tip.class);
mainAdapter.setTextKey("title");
mainAdapter.setImageKey("photo");
//Subclass ParseQueryAdapter
favoritesAdapter = new FavoriteTipAdapter(this);
//Default view is all wingman tips
setListAdapter(mainAdapter);
/* String url = "http://twitter.com/";
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url); */
}
#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_wingman_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh: {
updateTipList();
break;
}
case R.id.action_favorites: {
showFavorites();
break;
}
case R.id.action_new: {
newTip();
break;
}
case R.id.twitter: {
twitter();
break;
}
}
return super.onOptionsItemSelected(item);
}
private void twitter() {
Intent a = new Intent(this, Twitter.class);
startActivityForResult(a, 0);
}
private void updateTipList() {
mainAdapter.loadObjects();
setListAdapter(mainAdapter);
}
private void showFavorites() {
favoritesAdapter.loadObjects();
setListAdapter(favoritesAdapter);
}
private void newTip() {
Intent i = new Intent(this, NewTipActivity.class);
startActivityForResult(i, 0);

How to use SwipeActionAdapter and display app - [ANDROID]

I found a code from here
it is like
public class MainActivity extends ListActivity implements
SwipeActionAdapter.SwipeActionListener
{
protected SwipeActionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] content = new String[20];
for (int i=0;i<20;i++) content[i] = "Row "+(i+1);
ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(
this,
R.layout.row_bg,
R.id.text,
new ArrayList<String>(Arrays.asList(content))
);
mAdapter = new SwipeActionAdapter(stringAdapter);
mAdapter.setSwipeActionListener(this)
.setListView(getListView());
setListAdapter(mAdapter);
mAdapter.addBackground(SwipeDirections.DIRECTION_FAR_LEFT,R.layout.row_bg_left_far)
.addBackground(SwipeDirections.DIRECTION_NORMAL_LEFT,R.layout.row_bg_left)
.addBackground(SwipeDirections.DIRECTION_FAR_RIGHT,R.layout.row_bg_right_far)
.addBackground(SwipeDirections.DIRECTION_NORMAL_RIGHT,R.layout.row_bg_right);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id){
Toast.makeText(
this,
"Clicked "+mAdapter.getItem(position),
Toast.LENGTH_SHORT
).show();
}
#Override
public boolean hasActions(int position){
return true;
}
#Override
public boolean shouldDismiss(int position, int direction){
return direction == SwipeDirections.DIRECTION_NORMAL_LEFT;
}
#Override
public void onSwipe(int[] positionList, int[] directionList){
for(int i=0;i<positionList.length;i++) {
int direction = directionList[i];
int position = positionList[i];
String dir = "";
switch (direction) {
case SwipeDirections.DIRECTION_FAR_LEFT:
dir = "Far left";
break;
case SwipeDirections.DIRECTION_NORMAL_LEFT:
dir = "Left";
break;
case SwipeDirections.DIRECTION_FAR_RIGHT:
dir = "Far right";
break;
case SwipeDirections.DIRECTION_NORMAL_RIGHT:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test Dialog").setMessage("You swiped right").create().show();
dir = "Right";
break;
}
Toast.makeText(
this,
dir + " swipe Action triggered on " + mAdapter.getItem(position),
Toast.LENGTH_SHORT
).show();
mAdapter.notifyDataSetChanged();
}
}
}
I want to remove the string section and want to display apps.
I want to use SwipeActionAdapter to replace listview from my app which i used earlier to show app packages but unable to understand how to do that with this..
Go a bit easy on me if this is a very noob-ish question. I m a begginer.
I think you are misunderstanding the purpose of the Adapter.
The Adapter is the component that feeds the data into your ListView.
The SwipeActionAdapter is meant to wrap around your existing implementation of Adapter and provide callbacks that you can use to perform actions when someone swipes an item in your ListView.
You should probably go through a bit more tutorials. I can greatly recommend the Busy Coders guide to Android development by Commonsware.
I'm certain you'll find what you need there.

Android Listview - can not select multiple items when using a cursor

I have a listview populated with data from a cursor using SimpleCursorAdapter. I want to make it so I can select multiple items with a checkbox against each item but I can only get it to check a single item at a time i.e. each time I select an item, it will clear the currently selected item.
It works fine if I populate the listview using an ArrayAdapter. I can select multiple items. So I dont know why it doesn't work with the SimpleCursorAdapter.
This is being created in a DialogFragment if that matters.
Really pulling my hair out on this, pleae help!!
Here's the code:
Cursor attributesCursor = mDBHelper.getItemAttributesbyType(menuID, itemID, "M");
getActivity().startManagingCursor(attributesCursor);
ListView lv = new ListView(this.getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
lv.setLayoutParams(params);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getActivity(), android.R.layout.simple_list_item_multiple_choice,
attributesCursor, new String[] { "AttributeDescription" },
new int[] { android.R.id.text1 },0);
attributesLinearLayout.addView(lv);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Edit :
Just to add some extra info, the multi choice listview works if i use this code, where "items" is a simple String array:
lv.setAdapter(new ArrayAdapter(this.getActivity(),
android.R.layout.simple_list_item_multiple_choice, items));
Also, this listview is being dynamically added to an existing Linearlayout (attributesLinearLayout) in a dialogfragment which contains other controls. I also tried extending other adapters, including the array adapter and customer item layouts but that again didnt allow me to select multiple items.
Please help!!
I would use the Contextual Action mode in this project if you wish to select multiple items in a listview. This is how it is done.
First of all, the code must extend a ListActivity and implement an ActionMode.Callback
In the onCreate medthod you need to code the following:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "data list goes here" };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
setListAdapter(adapter);
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
return false;
}
selectedItem = position;
// Start the CAB using the ActionMode.Callback defined above
mActionMode = MyListActivityActionbar.this.startActionMode(MyListActivityActionbar.this);
view.setSelected(true);
return true;
}
});
}
The you need to call the show method:
private void show() {
Toast.makeText(MyListActivityActionbar.this, String.valueOf(selectedItem), Toast.LENGTH_LONG).show();
}
The following needs to be called each time the action mode is shown. It is always called after onCreateActionMode, but may be called multiple times if the mode is invalidated:
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
Then when the user selects a list item, the following method needs to be called:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1_show:
show();
// Action picked, so close the CAB
mode.finish();
return true;
default:
return false;
}
}
Finally when the user exits the selection:
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
selectedItem = -1;
}

Categories

Resources