I'm trying to convert my entire ListFragment class into a Fragment class with a ListView added to it.
Call this class HomeworkListFragment. I changed the extension from ListFragment to Fragment:
As a result I have created the following:
public class HomeworkListFragment extends Fragment{
public static final String TAG = "HomeworkListFragment";
public ListView mListView;
public HomeworkAdapter mAdapter;
private ArrayList<HomeworkObject> mCrimes;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.homework_title);
mCrimes = HomeworkLab.get(getActivity()).getHomework();
mAdapter = new HomeworkAdapter(mCrimes);
mListView.setAdapter(mAdapter);
setRetainInstance(true);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = super.onCreateView(inflater,parent,savedInstanceState);
mListView = (ListView)v.findViewById(android.R.id.list);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListView.setMultiChoiceModeListener(new MultiChoiceModeListener(){
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.menu_item_delete_homework:
HomeworkLab homeworkLab = HomeworkLab.get(getActivity());
for (int i = mAdapter.getCount() - 1;i>=0;i--){
//if (mListView.getListView().isItemChecked(i)){
//homeworkLab.deleteHomework(mAdapter.getItem(i));
//}
}
mode.finish();
mAdapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//ActionMode.callback Methods
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.homework_list_item_context, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
//not used here
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
//not used here
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode arg0,
int arg1, long arg2, boolean arg3) {
//not used here
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
HomeworkObject c = mAdapter.getItem(position);
//Start CrimeActivity
//Intent i = new Intent(getActivity(), CrimeActivity.class);
Intent i = new Intent(getActivity(), HomeworkPagerActivity.class);
i.putExtra(HomeworkFragment.EXTRA_HOMEWORK_ID, c.getId());
startActivity(i);
}
});
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu,inflater);
inflater.inflate(R.menu.fragment_homework_list, menu);
}
#TargetApi(11)
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu_item_new_homework:
HomeworkObject homework = new HomeworkObject();
homework.setTitle("");
HomeworkLab.get(getActivity()).addHomework(homework);
Intent i = new Intent(getActivity(),HomeworkPagerActivity.class);
i.putExtra(HomeworkFragment.EXTRA_HOMEWORK_ID, homework.getId());
startActivityForResult(i,0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.homework_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
HomeworkObject h = mAdapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_homework:
HomeworkLab.get(getActivity()).deleteHomework(h);
mAdapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
mCrimes = HomeworkLab.get(getActivity()).getHomework();//update list
}
#Override
public void onPause(){
super.onPause();
HomeworkLab.get(getActivity()).saveHomework();
}
/*#Override
public void onListItemClick(ListView l, View v, int position, long id){
HomeworkObject c = ((HomeworkAdapter)getListAdapter()).getItem(position);
//Start CrimeActivity
//Intent i = new Intent(getActivity(), CrimeActivity.class);
Intent i = new Intent(getActivity(), HomeworkPagerActivity.class);
i.putExtra(HomeworkFragment.EXTRA_HOMEWORK_ID, c.getId());
startActivity(i);
}*/
private class HomeworkAdapter extends ArrayAdapter<HomeworkObject>{
public HomeworkAdapter(ArrayList<HomeworkObject> crimes){
super(getActivity(), 0, crimes);
}
#SuppressLint("SimpleDateFormat")
#Override
public View getView(int position, View convertView, ViewGroup parent){
if (convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_homework, null);
}
HomeworkObject c = getItem(position);
TextView titleTextView = (TextView)convertView.findViewById(R.id.homework_list_item_titleTextView);
titleTextView.setText(c.getTitle());
TextView dateTextView = (TextView)convertView.findViewById(R.id.homework_list_item_dateTextView);
DateFormat df = new SimpleDateFormat("EEEE, d MMMM yyyy");
String reportDate = df.format(c.getDate());
dateTextView.setText(reportDate);
//dateTextView.setText(c.getDate().toString());
CheckBox solvedCheckBox = (CheckBox)convertView.findViewById(R.id.homework_list_item_solvedCheckBox);
solvedCheckBox.setChecked(c.isSolved());
return convertView;
}
}
}
As far as I can tell there's an error in the onCreateView method with some null pointer error but I can't make heads or tails of this issue.
I recently picked up Android after moving from iOS so I'm pretty new to this. Any explanation could help a lot!
problem:
mListView = (ListView)v.findViewById(android.R.id.list);
The android.R.id.list is only bounded to the ListFragment not in Fragment and that is why it is null.
as the documentation for ListFragment:
ListFragment has a default layout that consists of a single list view.
However, if you desire, you can customize the fragment layout by returning
your own view hierarchy from onCreateView(LayoutInflater, ViewGroup, Bundle).
To do this, your view hierarchy must contain a ListView object with the
id "#android:id/list" (or list if it's in code)
Solution:
You need to inflate a view in your fragment and create a layout with ListView and use the created ID of the ListView instead of android.R.id.list
Use this instead:
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
super.onCreateView(inflater,parent,savedInstanceState);
View v = inflater.inflate(R.layout.my_fragment_layout, parent, false);
mListView = (ListView)v.findViewById(android.R.id.list);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListView.setMultiChoiceModeListener(new MultiChoiceModeListener(){
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.menu_item_delete_homework:
HomeworkLab homeworkLab = HomeworkLab.get(getActivity());
for (int i = mAdapter.getCount() - 1;i>=0;i--){
//if (mListView.getListView().isItemChecked(i)){
//homeworkLab.deleteHomework(mAdapter.getItem(i));
//}
}
mode.finish();
mAdapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//ActionMode.callback Methods
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.homework_list_item_context, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
//not used here
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
//not used here
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode arg0,
int arg1, long arg2, boolean arg3) {
//not used here
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
HomeworkObject c = mAdapter.getItem(position);
//Start CrimeActivity
//Intent i = new Intent(getActivity(), CrimeActivity.class);
Intent i = new Intent(getActivity(), HomeworkPagerActivity.class);
i.putExtra(HomeworkFragment.EXTRA_HOMEWORK_ID, c.getId());
startActivity(i);
}
});
return v;
}
Related
In this position of the switch does not match with list view after search/filter, how to get real position of list view after filter it.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position)
Array 2
But The Contents is Array 1
public class CariTroubleActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener {
ListView listView;
Intent intent;
ArrayAdapter adapter;
String[] daftar = {"1","2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cari_trouble);
listView = findViewById(R.id.cariTrouble);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, daftar);
listView.setAdapter(adapter);
intent = new Intent(CariTroubleActivity.this, MasalahActivity.class);
listView.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_cari, menu);
final MenuItem item = menu.findItem(R.id.menuCari);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String list) {
adapter.getFilter().filter(list);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0 :
intent.putExtra("Tit", "Error Code");
intent.putExtra("text1","Title 1");
intent.putExtra("text2","Error 1ccccc");
startActivity(intent);
break;
case 1 :
intent.putExtra("Tit", "Error Code");
intent.putExtra("text1","Title 2");
intent.putExtra("text2","Error 2cccc");
startActivity(intent);
break;
default:
break;
}
}
}
Listview does not match the content, after the filter listview. then how to adjust the position of listview with the position of the switch?
After your list is filtered, you can not directly use position anymore (because the first item position==0 is now the first item of your filter etc.
So, you can override the BaseAdapter and create a logic to handle that list, or, since you are using basic adapters, you can just try to figure out the position in a different way:
Here:
String[] daftar = {"1","2"};
So, the text "1" and "2" will be used as content of your ListView. That list is using android.R.layout.simple_list_item_activated_1 which is just a TextView.
This way, you can just read the TextView content instead of position:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String textDisplayedByCurrentItem = ((TextView) view).getText();
if(textDisplayedByCurrentItem.equals(daftar[0]) { // or .equals("1")
intent.putExtra("Tit", "Error Code");
intent.putExtra("text1","Title 1");
intent.putExtra("text2","Error 1ccccc");
startActivity(intent);
} else if (textDisplayedByCurrentItem.equals(daftar[1]) { // or .equals("2")
intent.putExtra("Tit", "Error Code");
intent.putExtra("text1","Title 2");
intent.putExtra("text2","Error 2cccc");
startActivity(intent);
}
}
I am trying to implement MultiChoiceModeListener for select multiple item from a ListView. My current progress is shown below. But it doesn't working. It has no action on even long press. is any thing missed in my code or anything wrong? Any help will be greatly appreciated.
public class FragmentFavorite extends Fragment {
ListView lvFavoriteItems;
Activity mActivity = null;
Context mContext;
ArrayList<String> names = new ArrayList<>(Arrays.asList("My name is a", "My name is b",
"My name is c", "My name is d", "My name is e", "My name is f"));
ArrayList<String> phone = new ArrayList<>(Arrays.asList("9895653263", "9895653264", "9895653265",
"9895653266", "9895653267", "9895653267"));
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(mActivity == null) {
this.mActivity = getActivity();
}
this.mContext = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.favorite_list, container, false);
lvFavoriteItems = (ListView) root.findViewById(R.id.lv_item_list);
FavoriteAdapter fav = new FavoriteAdapter();
lvFavoriteItems.setAdapter(fav);
lvFavoriteItems.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
lvFavoriteItems.setMultiChoiceModeListener(new FavMultiChoiceModeListener());
return root;
}
private class FavoriteAdapter extends BaseAdapter {
#Override
public int getCount() {
return names.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View listItem;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
listItem = inflater.inflate(R.layout.contact_item_2_line, null);
} else {
listItem = convertView;
}
TextView tv1 = (TextView) listItem.findViewById(R.id.tv_item_name);
tv1.setText(names.get(position));
TextView tv2 = (TextView) listItem.findViewById(R.id.tv_phone);
tv2.setText(phone.get(position));
listItem.setId(position);
return listItem;
} }
private class FavMultiChoiceModeListener implements ListView.MultiChoiceModeListener {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int i, long l, boolean b) {
final int checkedCount = lvFavoriteItems.getCheckedItemCount();
mode.setSubtitle("" + checkedCount + " items selected ");
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.selection_menu, menu);
actionMode.setTitle("Select Items");
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return true;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
Toast.makeText(mActivity, "Clicked " + menuItem.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
}
}
Since you're extending from BaseAdapter, you might need to call convertView.setLongClickable(true) in your getView method.
I am implementing a music player app. I am able to fetch the songs from the sd card. But stuck in something from hours i.e. I am unable to make the songs play inside the fragment.
Here is the MainActivity class which is having 3 tab fragments.
public class MainActivity extends AppCompatActivity {
private final String[] TITLES = {"Now playing", "Library", "Groups"};
private static boolean isInForeground = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if (savedInstanceState == null) {}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Initialize the ViewPager and set an adapter
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new PagerAdapter(getSupportFragmentManager(), getBaseContext()));
// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setShouldExpand(true);
tabs.setViewPager(pager);
//Whenever the user changes tab, we want the title to change too
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int position) {
setTitle(TITLES[position]);
}
});
//We want to have the library as default view
pager.setCurrentItem(1);
setTitle(TITLES[1]);
}
#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);
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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_song_library, container, false);
return view;
}
}
public class PagerAdapter extends FragmentPagerAdapter
implements PagerSlidingTabStrip.CustomTabProvider {
private ArrayList<Integer> tab_icon = new ArrayList<Integer>();
Context myContext;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
myContext = context;
tab_icon.add(context.getResources().getIdentifier("ic_play_arrow_white_36dp", "drawable", context.getPackageName()));
tab_icon.add(context.getResources().getIdentifier("ic_list_white_36dp", "drawable", context.getPackageName()));
tab_icon.add(context.getResources().getIdentifier("ic_group_white_36dp", "drawable", context.getPackageName()));
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
if(position == 0){
return SongNowPlayingFragment.newInstance();
} else if (position == 1){
return SongLibraryFragment.newInstance();
} else if(position == 2){
return GroupFragment.newInstance();
}
System.err.println("Invalid tab fragment!");
return new Fragment();
}
#Override
public View getCustomTabView(ViewGroup viewGroup, int position) {
LinearLayout imageView = (LinearLayout) LayoutInflater.from(myContext)
.inflate(R.layout.tab_layout, null, false);
ImageView tabImage = (ImageView) imageView.findViewById(R.id.tabImage);
tabImage.setImageResource(tab_icon.get(position));
return imageView;
}
}
#Override
protected void onResume()
{
super.onResume();
isInForeground = true;
}
#Override
protected void onPause()
{
super.onPause();
isInForeground = false;
}
static boolean isInForeground(){
return isInForeground;
}
}
This is the SongLibraryFragment in which I have added the songs from the user device. Now I want to play those songs.
public class SongLibraryFragment extends Fragment implements MediaPlayerControl {
private ArrayList<SongItem> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private MusicController controller;
private boolean paused=false, playbackPaused=false;
private MainActivity mainActivity = null;
public static SongLibraryFragment newInstance() {
SongLibraryFragment f = new SongLibraryFragment();
Bundle b = new Bundle();
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_song_library, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainActivity = (MainActivity) SongLibraryFragment.this.getActivity();
songView = (ListView) getView().findViewById(R.id.library_song_list);
songList = new ArrayList<SongItem>();
getSongList();
SongAdapter songAdt = new SongAdapter(getActivity(), songList);
songView.setAdapter(songAdt);
Collections.sort(songList, new Comparator<SongItem>() {
public int compare(SongItem a, SongItem b) {
return a.getTitle().compareTo(b.getTitle());
}
});
setController();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
public void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(getActivity(), MusicService.class);
this.getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
this.getActivity().startService(playIntent);
}
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new SongItem(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public void start() {
musicSrv.go();
}
private void setController(){
//set the controller up
controller = new MusicController(getActivity());
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(getActivity().findViewById(R.id.library_song_list));
controller.setEnabled(true);
}
//play next
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
public void onPause(){
super.onPause();
paused=true;
}
#Override
public void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
public void onStop() {
controller.hide();
super.onStop();
}
#Override
public void onDestroy() {
this.getActivity().stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
SongAdapter class
public class SongAdapter extends BaseAdapter {
private ArrayList<SongItem> songs;
private LayoutInflater songInf;
public SongAdapter(Context c, ArrayList<SongItem> theSongs){
songs=theSongs;
songInf=LayoutInflater.from(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return songs.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//map to song layout
LinearLayout songLay = (LinearLayout)songInf.inflate
(R.layout.song, parent, false);
//get title and artist views
TextView songView = (TextView)songLay.findViewById(R.id.song_title);
TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
//ImageView imageView = (ImageView)songLay.findViewById(R.id.song_image);
//get song using position
SongItem currSong = songs.get(position);
//get title and artist strings
songView.setText(currSong.getTitle());
artistView.setText(currSong.getArtist());
//imageView.setImage(currSong.getImage());
//set position as tag
songLay.setTag(position);
return songLay;
}
Song.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:onClick="songPicked">
<TextView
android:id="#+id/song_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
style="#style/Base.TextAppearance.AppCompat.Title"
android:textColor="#color/primary_text_default_material_light"/>
<TextView
android:id="#+id/song_artist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
style="#style/Base.TextAppearance.AppCompat.Subhead"
android:textColor="#color/secondary_text_default_material_light"/>
</LinearLayout>
Error
java.lang.IllegalStateException: Could not find a method
songPicked(View) in the activity class
co.adrianblan.noraoke.MainActivity for onClick handler on view class
android.widget.LinearLayout
So the main problem is with the songPicked method inside SongFragmentLibrary. I have added the onClick: songPicked in the song.xml file but it is searching for the songPicked method inside the MainActivity. I am not getting what is the problem.
Please can anyone help me with this?
You are trying to set onclick listener from your fragment xml android:onClick="songPicked", you can't set onclick listener for a view which is part of fragment, in your getView() setOnClickListener:
LinearLayout songLay = (LinearLayout)songInf.inflate
(R.layout.song, parent, false);
songLay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Handle click event
}
})
OR
You can simply set OnItemClickListener on your listview
list.setOnItemClickListener(this);// implement OnItemClickListener in your fragment class
I haven't found similar questions, so I'm writing a new one.
I'm developing a little Android app and I have some problems with an interface. The app consists of 3 fragments and a ViewPager. Clicking a button, I show a custom dialog (made my extending the AlertDialog.Builder class). To retrieve data back from the target fragment, I made an interface that I implement in the fragment.
Everything seems to work, but when I try to access fragment class variables inside the overridden methods, they are null! Class variables are initialized in onCreateView fragment method.
Thanks
import android.content.DialogInterface;
public interface BandDialogInterface{
public void onActionCreate(DialogInterface dialog, String name, MyColor color);
public void onActionEdit(DialogInterface dialog, int id, String name, MyColor color);
}
It's a bit messy because I was trying something:
public class EditBandDialog extends AlertDialog.Builder {
private final Band band;
private Spinner listColor;
private EditText inputName;
private DatabaseHelper dbHelper;
private BandDialogInterface bandDialogInterface;
public EditBandDialog(Context context, final Band band){
super(context);
this.band = band;
try{
bandDialogInterface = ((MercenAppActivity)context).getBandsFragment();
Log.d("CONTEXT", ((MercenAppActivity)context).getBandsFragment().toString());
}catch (Exception e){
e.printStackTrace();
}
View dialogView = ((Activity)context).getLayoutInflater().inflate(R.layout.dialog_edit_band, null);
setView(dialogView);
setCancelable(false);
dbHelper = new DatabaseHelper(context);
listColor = (Spinner)dialogView.findViewById(R.id.dialog_edit_band_color);
inputName = (EditText)dialogView.findViewById(R.id.dialog_edit_band_name);
BandColorAdapter adapter = new BandColorAdapter(context);
listColor.setAdapter(adapter);
if(isNewBand()) {
setTitle(R.string.title_new_band);
setPositiveButton("Crea", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//bandAdapter.insert(new Band(-1, inputName.getText().toString(), ((MyColor) listColor.getSelectedItem())));
//Toast.makeText(getContext(), R.string.toast_band_added, Toast.LENGTH_SHORT).show();
bandDialogInterface.onActionCreate(dialog, inputName.getText().toString(), (MyColor)listColor.getSelectedItem());
}
});
}else{
setTitle(R.string.title_edit_band);
inputName.setText(band.getName());
int pos = 0;
while(((MyColor)listColor.getAdapter().getItem(pos)).getColor() != band.getColor())
pos++;
listColor.setSelection(pos);
setPositiveButton("Modifica", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//dbHelper.updateBand(dbHelper.getWritableDatabase(), band.getId(), inputName.getText().toString(), ((MyColor) listColor.getSelectedItem()).getColor());
//bandAdapter.update(new Band(band.getId(), inputName.getText().toString(), ((MyColor) listColor.getSelectedItem())));
//Toast.makeText(getContext(), R.string.toast_band_edited, Toast.LENGTH_SHORT).show();
bandDialogInterface.onActionEdit(dialog, band.getId(), inputName.getText().toString(), (MyColor)listColor.getSelectedItem());
}
});
}
setNegativeButton("Annulla", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
private boolean isNewBand(){
return band == null;
}
}
class MyColor{
int color;
public MyColor(int color){
this.color = color;
}
public static MyColor fromString(String s){
return new MyColor(Color.parseColor(s));
}
public int getColor(){
return color;
}
}
class BandColorAdapter extends ArrayAdapter<MyColor> implements SpinnerAdapter {
private static final MyColor[] colors = {MyColor.fromString("#D60000"), //ROSSO
MyColor.fromString("#0080FF"), //AZZURRO
MyColor.fromString("#00AD37"), //VERDE
MyColor.fromString("#FFF700"), //GIALLO
MyColor.fromString("#FF8400"), //ARANCIO
MyColor.fromString("#10009C")}; //BLU
public BandColorAdapter(Context context) {
super(context, R.layout.row_band_color, colors);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band_color, parent, false);
}
View bandColor = convertView.findViewById(R.id.band_color_item);
bandColor.setBackgroundColor(getItem(position).getColor());
return convertView;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band_color, parent, false);
}
View bandColor = convertView.findViewById(R.id.band_color_item);
bandColor.setBackgroundColor(getItem(position).getColor());
return convertView;
}
}
And this is the class where I implement the interface:
public class BandsFragment extends Fragment implements BandDialogInterface{
private static final String TAG = "BandsFragment";
private static final boolean D = true;
private DatabaseHelper dbHelper;
private BandAdapter bandAdapter;
private String s;
public BandsFragment(){
}
#Override
public void onActionCreate(DialogInterface dialog, String name, MyColor color) {
//Toast.makeText(getActivity(), "CREATE", Toast.LENGTH_SHORT).show();
//bandAdapter.insert(new Band(0, name, color));
Log.d("CREATE", s);
}
#Override
public void onActionEdit(DialogInterface dialog, int id, String name, MyColor color) {
Toast.makeText(getActivity(), "EDITED", Toast.LENGTH_SHORT).show();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static BandsFragment newInstance() {
BandsFragment fragment = new BandsFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bands, container, false);
if (D) Log.d(TAG, "--- onCreateView ---");
dbHelper = new DatabaseHelper(getActivity());
ListView listBands = (ListView)rootView.findViewById(R.id.list_bands);
TextView noBands = (TextView)rootView.findViewById(R.id.no_bands);
bandAdapter = new BandAdapter(getActivity(), noBands);
listBands.setAdapter(bandAdapter);
// if(dbList.size() == 0){
// noBands.setVisibility(View.VISIBLE);
// }else{
// noBands.setVisibility(View.GONE);
// }
listBands.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO something
}
});
registerForContextMenu(listBands);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (D) Log.d(TAG, "--- onAttach ---");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (D) Log.d(TAG, "--- onCreate ---");
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (D) Log.d(TAG, "--- onViewCreated ---");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (D) Log.d(TAG, "--- onActivityCreated ---");
}
#Override
public void onStart() {
super.onStart();
if (D) Log.d(TAG, "--- onStart ---");
}
#Override
public void onResume() {
super.onResume();
if (D) Log.d(TAG, "--- onResume ---");
}
#Override
public void onPause() {
super.onPause();
if (D) Log.d(TAG, "--- onPause ---");
}
#Override
public void onStop() {
super.onStop();
if (D) Log.d(TAG, "--- onStop ---");
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (D) Log.d(TAG, "--- onDestroyView ---");
}
#Override
public void onDestroy() {
super.onDestroy();
if (D) Log.d(TAG, "--- onDestroy ---");
}
#Override
public void onDetach() {
super.onDetach();
if (D) Log.d(TAG, "--- onDetach ---");
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(bandAdapter.getItem(info.position).getName());
getActivity().getMenuInflater().inflate(R.menu.context_band, menu);
MenuItem.OnMenuItemClickListener l = new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
onContextItemSelected(item);
return true;
}
};
for(int i = 0; i < menu.size(); ++i){
menu.getItem(i).setOnMenuItemClickListener(l);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()){
case R.id.context_band_edit:
new EditBandDialog(getActivity(), bandAdapter.getItem(info.position)).show();
//Log.d("D",bandAdapter.getItem(info.position).getName());
break;
case R.id.context_band_delete:
/*dbHelper.deleteBand(dbHelper.getWritableDatabase(), bandAdapter.getItem(info.position).getId());
bandAdapter.remove(bandAdapter.getItem(info.position));
bandAdapter.notifyDataSetChanged();*/
bandAdapter.delete(bandAdapter.getItem(info.position));
Toast.makeText(getActivity(), R.string.toast_band_deleted, Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
class BandAdapter extends ArrayAdapter<Band> implements SpinnerAdapter{
private DatabaseHelper dbHelper;
private TextView noBands;
public BandAdapter(Context context, TextView noBands) {
super(context, R.layout.row_band);
this.noBands = noBands;
dbHelper = new DatabaseHelper(context);
updateAdapter();
}
private void updateAdapter(){
clear();
addAll(dbHelper.getAllBands());
if(noBands != null) {
if (isEmpty()) {
noBands.setVisibility(View.VISIBLE);
} else {
noBands.setVisibility(View.GONE);
}
}
notifyDataSetChanged();
}
public void insert(Band band){
//dbHelper.insertBand(dbHelper.getWritableDatabase(), band.getName(), band.getColor());
Toast.makeText(getContext(), "ADDED", Toast.LENGTH_SHORT).show();
updateAdapter();
}
public void update(Band band){
dbHelper.updateBand(dbHelper.getWritableDatabase(), band.getId(), band.getName(), band.getColor());
updateAdapter();
}
public void delete(Band band){
dbHelper.deleteBand(dbHelper.getWritableDatabase(), band.getId());
updateAdapter();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Band band = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band, parent, false);
}
// Lookup view for data population
TextView bandName = (TextView) convertView.findViewById(R.id.band_name);
View bandColor = (View) convertView.findViewById(R.id.band_color);
bandColor.setBackgroundColor(band.getColor());
// Populate the data into the template view using the data object
bandName.setText(band.getName());
// Return the completed view to render on screen
return convertView;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band, parent, false);
}
Band band = getItem(position);
TextView bandName = (TextView) convertView.findViewById(R.id.band_name);
View bandColor = (View) convertView.findViewById(R.id.band_color);
bandColor.setBackgroundColor(band.getColor());
// Populate the data into the template view using the data object
bandName.setText(band.getName());
return convertView;
}
}
I'm working on a homework planner app, and I'm looking for a way to display only certain elements in an ArrayList that holds Task objects. After the user clicks on a course from a list of course titles, the list of tasks that pertain to that course should be displayed. Currently, it shows a list of all tasks, no matter which course has been selected. Each Task object stores the course that it belongs to, in a field called mBelongsToCourse. I would like to be able to filter the ArrayList of all tasks that is used in my TaskAdapter to only show the tasks which belong to a specific course, but all my attempts have been fruitless.
Below is my TaskListFragment Class, which includes the TaskAdapter:
public class TaskListFragment extends ListFragment {
private ArrayList<Task> mTasks;
private static String courseName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
courseName = getActivity().getIntent().getStringExtra("name");
getActivity().setTitle(courseName);
mTasks = TaskLab.get(getActivity()).getTasks();
TaskAdapter adapter = new TaskAdapter(mTasks);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//Get the Task from the adapter
Task t = ((TaskAdapter)getListAdapter()).getItem(position);
// Start TaskActivity for this task
Intent i = new Intent(getActivity(), TaskActivity.class);
i.putExtra(TaskFragment.EXTRA_TASK_ID, t.getId());
startActivity(i);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_task_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_task:
Task task = new Task();
task.setBelongsToCourse(courseName);
TaskLab.get(getActivity()).addTask(task);
Intent i = new Intent(getActivity(), TaskActivity.class);
i.putExtra(TaskFragment.EXTRA_TASK_ID, task.getId());
//i.putExtra("cn", task.getBelongsToCourse());
startActivityForResult(i, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.task_list_item_context, menu);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
ListView listView = (ListView)v.findViewById(android.R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// Required, but not used in this implementation
}
// ActionMode.Callback methods
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.task_list_item_context, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
// Required, but not used in this implementation
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_task:
TaskAdapter adapter = (TaskAdapter)getListAdapter();
TaskLab taskLab = TaskLab.get(getActivity());
for (int i = adapter.getCount() - 1; i >= 0; i--) {
if (getListView().isItemChecked(i)) {
taskLab.deleteTask(adapter.getItem(i));
}
}
mode.finish();
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
// Required, but not used in this implementation
}
});
return v;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
TaskAdapter adapter = (TaskAdapter)getListAdapter();
Task task = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_task:
TaskLab.get(getActivity()).deleteTask(task);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
((TaskAdapter)getListAdapter()).notifyDataSetChanged();
}
private class TaskAdapter extends ArrayAdapter<Task> {
public TaskAdapter(ArrayList<Task> tasks) {
super(getActivity(), 0, tasks);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_task, null);
}
// Configure the view for this Task
Task t = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.task_list_item_titleTextView);
titleTextView.setText(t.getTitle());
TextView dateTextView =
(TextView)convertView.findViewById(R.id.task_list_item_dateTextView);
dateTextView.setText(t.getDate().toString());
CheckBox completedCheckBox =
(CheckBox)convertView.findViewById(R.id.task_list_item_completedCheckBox);
completedCheckBox.setChecked(t.isCompleted());
return convertView;
}
}
}
Any help would be greatly appreciated.
EDIT: I've followed the advice of Ravind Maurya and Embattled Swag and updated my TaskAdapter:
private class TaskAdapter extends ArrayAdapter<Task> implements Filterable {
private ArrayList<Task> taskList;
private Filter taskFilter;
public TaskAdapter(ArrayList<Task> tasks) {
super(getActivity(), 0, tasks);
this.taskList = tasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_task, null);
}
// Configure the view for this Task
Task t = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.task_list_item_titleTextView);
titleTextView.setText(t.getTitle());
TextView dateTextView =
(TextView)convertView.findViewById(R.id.task_list_item_dateTextView);
dateTextView.setText(t.getDate().toString());
CheckBox completedCheckBox =
(CheckBox)convertView.findViewById(R.id.task_list_item_completedCheckBox);
completedCheckBox.setChecked(t.isCompleted());
return convertView;
}
#Override
public Filter getFilter() {
if (taskFilter == null)
taskFilter = new TaskFilter();
return taskFilter;
}
private class TaskFilter extends Filter {
#Override
protected FilterResults performFiltering (CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null | constraint.length() == 0) {
results.values = taskList;
results.count = taskList.size();
} else {
ArrayList<Task> newTaskList = new ArrayList<Task>();
for (Task t : taskList) {
if (t.getBelongsToCourse().toUpperCase().startsWith(constraint.toString().toUpperCase())) {
newTaskList.add(t);
}
}
results.values = newTaskList;
results.count = newTaskList.size();
} return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
taskList = (ArrayList<Task>)results.values;
notifyDataSetChanged();
}
}
}
}
Now the problem I have is I don't know where to call .getFilter().filter(courseName) in order to filter the ArrayList.
I followed this example literally yesterday to come up with a solid filter: http://www.survivingwithandroid.com/2012/10/android-listview-custom-filter-and.html
However; this example doesn't cover the case where you use the backspace and therefore the listview has to repopulate. You can follow the actual source code for the generic Filter here (it's at the bottom...essentially you'll just create a copy and then reduce the items of one of the lists): http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/widget/ArrayAdapter.java#ArrayAdapter.0mOriginalValues