This is my code for retrieving the list of the songs on the device. I want to play the selected song. Couldn't figure out how to use the onItemClickListener to do it. How do I do that in another activity?
public class SongsFragment extends Fragment {
public SongsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_songs, container, false);
ListView audioView = (ListView)view.findViewById(R.id.songView);
ArrayList<String> audioList = new ArrayList<>();
String[] proj = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};
final Cursor audioCursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
int audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
audioList.add(audioCursor.getString(audioIndex));
} while (audioCursor.moveToNext());
}
}
audioCursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, audioList);
audioView.setAdapter(adapter);
return view;
}
Use audioView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Object song = list.getItemAtPosition(position);
//TODO play song
}
});
Basically, when you click a song item from the list view, you will just get the value of the selected song and then you can then play it.
Related
I have a ListFragment's list that contains complex layouts as items, these items contain custom spinners (MaterialSpinner).
MaterialSpinner chooseSubjectSpinner = adapter.getItem(position).findViewById(R.id.myCustomSpinner);
chooseSubjectSpinner.setAdapter(spinnerAdapter);
I've tried getChildAt(position), adapter.getItem(postition), adapter.getView(position, null, parent), and list.get(position) with the added prefix of .findViewById(R.id.myview), but it doesn't work. (It either returns NullPointerException at runtime or doesn't do anything at all!).
EDIT:
if you guys want the whole fragment code:
private ArrayList<View> listViews = new ArrayList<>();
private ViewAdapter adapter;
private List<String> spinnerItems = new ArrayList<>();
private MaterialSpinnerAdapter<String> spinnerAdapter;
public FragmentUnitTest() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_unit_test, container, false);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState){
spinnerItems.add("Hey!");
spinnerItems.add("Hello!");
spinnerItems.add("Hi!");
spinnerAdapter = new MaterialSpinnerAdapter<>(getContext(), spinnerItems);
adapter = new ViewAdapter(listViews, view.getContext());
setListAdapter(adapter);
addView(R.layout.cardview_with_spinner);
MaterialSpinner spinner = adapter.getItem(0).findViewById(R.id.custom_spinner);
RLogger.e("FragmentUnitTest", spinner);
spinner.setAdapter(spinnerAdapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Clicked: " + position + " .", Toast.LENGTH_SHORT).show();
}
Create a Custom spinner like this:
public class PTCustomSpinner extends ArrayAdapter {
public PTCustomSpinner(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
int count = super.getCount();
return count>0 ? count-1 : count ;
}
Handle it like below // BELOW XML LAYOUT CONTAINS ONLY TEXTVIEW WITH ID "temp"
PTCustomSpinner spinnerArrayAdapter = new PTCustomSpinner(PTExceptionMainPage.this, R.layout.xml_with_only_textview);
spinnerArrayAdapter.addAll(team_array);
spinnerArrayAdapter.add("Pick Team");
spinnerTeam.setAdapter(spinnerArrayAdapter);
spinnerTeam.setSelection(spinnerArrayAdapter.getCount());
spinnerTeam.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (spinnerTeam.getSelectedItem() != "Pick Team") {
teamIdSelected = apiResponseTeam.get(i).getTeamID();
}
else if( spinnerTeam.getSelectedItem().equals("Pick Team"))
{
View v = spinnerTeam.getSelectedView();
((TextView) v).setTextColor(getResources().getColor(R.color.ash));
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
I have created Spinner in my app and when I do something I'm changing my adapter. After the change when I open the spinner it should refresh the list of the names but it stays the same. When I check the adapter I can see that list is refreshed correctly but it doesn't shows in the spinner. Here is my code:
public void addItemsToSpinner(UserSettings settings) {
List<Recipient> list = settings.getRecipients();
Recipient selectedRecipient = settings.getSelectedRecipient();
List<String> nicks = new ArrayList<>();
if (selectedRecipient != null) {
Log.d("utolsó","selected name " + selectedRecipient.getNickname());
nicks.add(selectedRecipient.getNickname());
}
for (Recipient recipient: list) {
if (selectedRecipient == null || !recipient.getNickname().equals(selectedRecipient.getNickname())) {
nicks.add(recipient.getNickname());
}
}
for(int i = 0 ;i<nicks.size();i++){
Log.d("TAG","print the order = " + nicks.get(i));
}
dataAdapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item, nicks);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_recipient_chooser, container, false);
mSpinner = (Spinner) view.findViewById(R.id.spinnerChooser);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dataAdapter.notifyDataSetChanged();
if (mListener != null) {
mListener.onRecipientSelected(position);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
When I the order it's correct but in the spinner it's not. Can anyone tell me why?
have you tried using adapter.notifyDataSetChanged(); after list is changed
I want to make OnItemClickListener to a dynamic listview. The listview shouldn't have a fixed size. Instead it's the size of the rows in a database. But how do I create the listener concidering I can't use the current method I have since I don't know the size of the listview.
THE PROBLEM IS IN THE INNER CLASS if(position==0) { ... }
public class VisaUtgiftFragment extends Fragment {
private MainActivity ui;
private TextView tvDatabase;
private MyDBHandler dbHandler;
private ListView lvUtgift;
public VisaUtgiftFragment() {
// Required empty public constructor
}
public void setActivity(MainActivity ui){
this.ui = ui;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_visa_utgift, container, false);
tvDatabase = (TextView)view.findViewById(R.id.tvDatabaseTest);
dbHandler = new MyDBHandler(getActivity(), null, null, 1);
tvDatabase.setText(dbHandler.databaseToString());
lvUtgift = (ListView)view.findViewById(R.id.lvUtgift);
// lvUtgift.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, [the rows in the database]));
lvUtgift.setAdapter(new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1,
dbHandler.getAllItemsInCursor(),
new String[]{"_titel"},
new int[]{android.R.id.text1},
0));
lvUtgift.setOnItemClickListener(new ListViewClicked());
return view;
}
private class ListViewClicked implements android.widget.AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0) { //Should be the clicked listview and execute the code
Cursor cursor = (Cursor) lvUtgift.getItemAtPosition(position);
String string = cursor.getString(cursor.getColumnIndexOrThrow("_titel"));
Toast.makeText(getActivity().getApplicationContext(), string, Toast.LENGTH_SHORT).show();
ui.dVisaInkomst();
}
}
}
}
Remove if condition from onClickItem.
private class ListViewClicked implements android.widget.AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = (Cursor)lvUtgift.getItemAtPosition(position);
if(cursor != null){
String string = cursor.getString(cursor.getColumnIndexOrThrow("_titel"));
Toast.makeText(getActivity().getApplicationContext(), string, Toast.LENGTH_SHORT).show();
ui.dVisaInkomst();
}
}
}
I have a ListView that is within a Fragment. In the onCreateView section I have set a onItemClickListener for the list, which highlights the selected item in the ListView. I have set two ImageButtons that navigate up and down the list. On selection a new Row is inflated that has its TextView's set to the content of the select item (for the purpose of retaining the highlighted selected state). However I am having difficulty adding that item back to the list. The app will not compile due to the line routines.add(selectedPos-1, str); it wants wants int location, Routine object. I believe the issue is with my construction of my SelectedAdapter class, but I have been unable to determine what to change/pass with regard to the Object.
IE:
public SelectedAdapter(Context context, int textViewResourceId,List objects) {
super(getActivity(), R.layout.listview_routines, routines); }
I would greatly appreciate any input as how to correct this issue; as well as any advice if there is a better way to maintain a selected state. Thanks for your help.
Fragment:
public static class FragmentRoutine extends Fragment {
DatabaseHandler db;
private ListView routineListView;
private List<Routine> routines = new ArrayList<Routine>();
ArrayAdapter<Routine> routineAdapter;
Routine longClickedItemRoutines;
private SelectedAdapter selectedAdapter;
public FragmentRoutine() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.routines,
container, false);
db = new DatabaseHandler(getActivity().getApplicationContext());
routineListView = (ListView) rootView.findViewById(R.id.routineList);
registerForContextMenu(routineListView);
db.closeDB();
if (db.getExerciseCount() != 0)
routines.clear();
routines.addAll(db.getAllRoutines());
populateList();
selectedAdapter = new SelectedAdapter(this.getActivity(), 0, routines);
selectedAdapter.setNotifyOnChange(true);
routineListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemRoutines = routines.get(position);
return false;
}
});
routineListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view,
int position, long id) {
selectedAdapter.setSelectedPosition(position);
}
});
routineListView.post(new Runnable() {
#Override
public void run() {
routineListView.setItemChecked(0, true);
}
});
// move up event handler
ImageButton btnMoveUp = (ImageButton) rootView.findViewById(R.id.btnMoveUp);
btnMoveUp.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveUp();
}
});
// move down event handler
ImageButton btnMoveDown = (ImageButton) rootView.findViewById(R.id.btnMoveDown);
btnMoveDown.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveDown();
}
});
setHasOptionsMenu(true);
return rootView;
}
// Move selected item "up" in the ViewList.
private void moveUp(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos > 0 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
//Problem Line Below
routines.add(selectedPos-1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos-1);
}
}
// Move selected item "down" in the ViewList.
private void moveDown(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos < routines.size()-1 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
routines.add(selectedPos+1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos+1);
}
}
public class SelectedAdapter extends ArrayAdapter<Routine>{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(getActivity(), R.layout.listview_routines, routines);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.selected_row, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
return(v);
}
}
private void populateList() {
routineAdapter = new SaveListAdapterT();
routineListView.setAdapter(routineAdapter);
}
public class SaveListAdapterT extends ArrayAdapter<Routine> {
public SaveListAdapterT() {
super(getActivity(), R.layout.listview_routines, routines);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_routines, parent, false);
Routine currentToDoSave = routines.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(currentToDoSave.getTagName());
return view;
}
}
}
I want to make an e-learning android application.
I set the string data from database to a gridview item. But I want to set the onitemclick to play an audio from raw folder for every item, that contains about 40 data.
How to set that?
this is my code :
public class DaftarHuruf extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private GridView gv;
Cursor cursor;
DBHelper dbHelper;
ListAdapter list_adapter;
String audio;
MediaPlayer mp;
public DaftarHuruf() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater layoutInflater,
ViewGroup viewGroup, Bundle bundle) {
View view = layoutInflater.inflate(R.layout.fragment_daftarhuruf,
viewGroup, false);
gv = (GridView) view.findViewById(R.id.gridview);
dbHelper = new DBHelper(getActivity());
dbHelper.open();
cursor = dbHelper.getDataHuruf();
cursor.moveToFirst();
SimpleCursorAdapter list_adapter = new SimpleCursorAdapter(
getActivity(), R.layout.grid_item, cursor,
new String[] { "huruf", "romanisasi" }, new int[] {
R.id.hurufHangeul, R.id.romawi });
gv.setAdapter(list_adapter);
gv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
audio = getString(R.id.hurufHangeul);
audio.replaceAll(".MP3", "");
int i;
i = getResources().getIdentifier(audio, "raw", getActivity().getPackageName());
mp = MediaPlayer.create(getActivity(), i);
if (mp != null) {
mp.start();
} else {
Toast.makeText(getActivity(), "Data suara tidak ada",
Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
public static DaftarHuruf newInstance(int i) {
DaftarHuruf frag = new DaftarHuruf();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, i);
frag.setArguments(args);
return frag;
}
}
Replace
audio = getString(R.id.hurufHangeul);
audio.replaceAll(".MP3", "");
int i;
i = getResources().getIdentifier(audio, "raw", getActivity().getPackageName());
mp = MediaPlayer.create(getActivity(), i);
With:
mp = MediaPlayer.create(this, R.raw.*name of the audio file*);
to set up the media player to the specified sound.