I would like to automatically play music in the background when I enter this Fragment page. I believe the commented out section is how you implement it, but I might be typing the first parameter incorrectly?
public class AlphabetFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//MediaPlayer mysong;
//mysong = MediaPlayer.create(AlphabetFragment.this, R.raw.alphabetlist);
//mysong.start();
return inflater.inflate(R.layout.fragment_alphabet, container, false);
}
Or am I coding this in the wrong spot, should it be part of the MainActivity.java?
case R.id.nav_alphabet:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AlphabetFragment()).commit();
//mysong = MediaPlayer.create(AlphabetFragment., R.raw.alphabetlistm4a);
//mysong.start();
Use getActivity(). It gives the Media Player the context it needs. Try to use this code:
MediaPlayer mp = MediaPlayer.create( getActivity() , R.raw.alphabetlist );
Your fragment code should look like this:
MediaPlayer mp;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mp=MediaPlayer.create(getActivity(), R.raw.alphabetlist);
mp.start():
return inflater.inflate(R.layout.fragment_alphabet, container, false);
}
Try this. Hope it helps!
You could just use getActivity to get the context of activity from fragment class.
As below.
public class AlphabetFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
MediaPlayer mysong;
mysong = MediaPlayer.create(this.getActivity(), R.raw.alphabetlist);
mysong.start();
return inflater.inflate(R.layout.fragment_alphabet, container, false);
}
Related
I have a single activity which replaces a fragment containing a recycler view with a fragment containing details of the selected viewholder item. When the back button is pressed the fragment containing the recycler view is restored but the recycler view items are no longer displayed. However, views are restored upon device rotation. All model data is stored in a SQLite database and the adapter list is updated on resume of its fragment .
CrimeListFragment.Java
public class CrimeListFragment extends Fragment {
private Callbacks callbacks;
public interface Callbacks {
public void onItemSelected(UUID id);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
callbacks = (Callbacks) context;
}
#Override
public void onDetach() {
super.onDetach();
callbacks = null;
}
private RecyclerView crimeListRecycler;
private CrimeListAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
crimeListRecycler = view.findViewById(R.id.crime_list);
crimeListRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.show_subtitle);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
/*Intent intent = CrimeActivity.createIntent(getActivity(), crime.getId());
startActivity(intent);*/
callbacks.onItemSelected(crime.getId());
return true;
default:
return onOptionsItemSelected(item);
}
}
private void updateUI() {
List<Crime> crimes = CrimeLab.get(getActivity()).getCrimes();
if (adapter == null) {
adapter = new CrimeListAdapter(crimes);
crimeListRecycler.setAdapter(adapter);
} else {
adapter.setCrimesList(crimes);
adapter.notifyDataSetChanged();
}
}
public class CrimeListAdapter extends RecyclerView.Adapter<CrimeListAdapter.CrimeHolder> {
private List<Crime> crimeList;
public CrimeListAdapter(List<Crime> crimes) {
crimeList = crimes;
}
#NonNull
#Override
public CrimeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_crime, parent, false);
return new CrimeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CrimeHolder holder, int position) {
Crime crime = crimeList.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return crimeList.size();
}
public void setCrimesList(List<Crime> crimes) {
crimeList = crimes;
}
public class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Crime crime;
private TextView crimeTitleTextView;
private TextView crimeDateTextView;
public CrimeHolder(#NonNull View itemView) {
super(itemView);
crimeTitleTextView = itemView.findViewById(R.id.crime_title);
crimeDateTextView = itemView.findViewById(R.id.crime_date);
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
this.crime = crime;
crimeTitleTextView.setText(crime.getTitle());
crimeDateTextView.setText(crime.getDate().toString());
}
#Override
public void onClick(View v) {
callbacks.onItemSelected(crime.getId());
/*Intent intent = CrimeActivity.createIntent(getActivity(), crime.getId());
startActivity(intent);*/
}
}
}
}
MasterActivity
public class MasterActivity extends AppCompatActivity implements CrimeListFragment.Callbacks {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new CrimeListFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
#Override
public void onItemSelected(UUID id) {
Fragment fragment = CrimeFragment.newInstance(id);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
}
Please share your code. Something to check when you replace/add your fragment on top of recyclerview fragment.
I am using recycler view in a fragment. Now I want to open a new fragment on recycler view item click. I have used the following code in my recycler view adapter. Please solve my problem.
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.img.setImageResource(mData.get(position).getPhoto());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) v.getContext();
MiscellaneousFragment miscellaneousfragment = new MiscellaneousFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.linerr, MiscellaneousFragment).addToBackStack(null).commit();
}
});
But I am getting this error in Logcat.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at androidx.fragment.app.FragmentTransaction.doAddOp.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MiscellaneousFragment miscellaneousfragment = new MiscellaneousFragment();
FragmentManager fragmentManager =currentfragment.getFragmentManager()
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction()
fragmentTransaction.add(R.id.linerr, miscellaneousfragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
});
I want to start a dialogFragment on recycler view item click in RecyclerView Adapter
I tried
FragmentManager fr = ((Activity)context).getFragmentManager();
AnswersDialogFragment msgDialog = new AnswersDialogFragment();
msgDialog.show(fr, "Dialog");
but i get casting error
java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to android.support.v4.app.FragmentActivity
I want to start the dialog fragment on item click
#Override
public AnswersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.answercard, parent, false);
AnswersViewHolder evh = new AnswersViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(AnswersViewHolder holder, int position) {
int viewType = getItemViewType(position);
if(viewType==COMMENT_TYPE){
final Comments item = (Comments) commentsList.get(position);
holder.UserName.setText(Html.fromHtml(item.getUserName()));
holder.CommentText.setText(Html.fromHtml(item.getCommentText()));
}else{
final Replys replyitem = (Replys) commentsList.get(position);
holder.UserName.setText(Html.fromHtml(replyitem.getReplyAuthor()));
holder.CommentText.setText(Html.fromHtml(replyitem.getReplyBody()));
}
}
imgLikeComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fr = ((Activity)context).getFragmentManager();
AnswersDialogFragment msgDialog = new AnswersDialogFragment();
msgDialog.show(fr, "Dialog");
});
AnswersDialogFragment.java
public class AnswersDialogFragment extends DialogFragment {
ArrayList<Object> answersList;
RecyclerView recyclerView;
AnswersAdapter recyclerViewadapter;
RecyclerView.LayoutManager recyclerViewlayoutManager;
ImageView sendReply ;
EditText commentInput;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogStyle);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.nestedcomments, container, false);
..... etc
The Item click is working fine , i just can't start the fragment
try to use SupportFragmentManager instead
FragmentManager manager = ((AppCompatActivity)context).getSupportFragmentManager();
I'm getting NullPointerException while using setText() inside OnBindViewHolder() while implementing recyclerview. I've debugged the entire code but not getting the solution. Please Explain why the 'holder.articleName' is thrown as null object?
Adapter Class:
public class ArticleListAdapter extends RecyclerView.Adapter<ArticleItemViewHolder> {
String[] articles = {
"article1",
"article2",
"article3",
"article4",
"article5"
};
#NonNull
#Override
public ArticleItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_article_list, parent, false);
return new ArticleItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ArticleItemViewHolder holder, final int position) {
holder.articleName.setText(articles[position]);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ArticleListActivity.this, "Article Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return articles.length;
}
}
ViewHolder Class:
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ArticleItemViewHolder extends RecyclerView.ViewHolder{
TextView articleName;
CardView cardView;
public ArticleItemViewHolder(View itemView) {
super(itemView);
this.articleName = itemView.findViewById(R.id.articleName);
this.cardView = itemView.findViewById(R.id.cardView);
}
}
Make sure the layout which has the TextView articleName is in the Layout page referenced here R.layout.activity_article_list and not any other layout page!
I am creating a music app and I have listed my songs in RecyclerView. What I want is when I click any song(inside the red marked area), the song should play, just like in modern music players. I don't want any play, stop buttons on my RecyclerView. Any help would be appreciated! Thanks in advance!
Songs.java
public class Songs extends Fragment {
private static final String TAG = "Songs";
RecyclerView recyclerView;
private ArrayList<SongInfoModel> SongList = new ArrayList<SongInfoModel>();
SongAdapter songAdapter;
SongInfoModel s;
private MediaPlayer mediaPlayer;
ScaleInAnimationAdapter alphaAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs_activity, container, false);
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
mediaPlayer = new MediaPlayer();
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
SongInfoModel s= new SongInfoModel("Cheap Thrills","Sia",null, null,
"http://mp3fb.com/wp-includes/inc/down.php?
id=hyCQomZzosfGBvVON0tRV7xfiL2GdtKXbTsBrZh_3NM&t=Sia%2B-
%2BCheap%2BThrils%2B%D0%A0%D0%B5%D0%BC%D0%B8%D0%BA%D1%81.mp3
&hash=true",null,null);
SongList.add(s);
songAdapter = new SongAdapter(getContext(),SongList);
alphaAdapter = new ScaleInAnimationAdapter(songAdapter);
alphaAdapter.setDuration(1000);
alphaAdapter.setInterpolator(new OvershootInterpolator());
alphaAdapter.setFirstOnly(false);
recyclerView.setAdapter(alphaAdapter);
Collections.sort(SongList, new Comparator<SongInfoModel>(){
public int compare(SongInfoModel a, SongInfoModel b){
return a.getSongName().compareTo(b.getSongName());
}
});
return view;
}
SongAdapter.java:
public class SongAdapter extends
RecyclerView.Adapter<SongAdapter.SongHolder>
{
ArrayList<SongInfoModel> SongList = new ArrayList<>();
Context context;
MediaPlayer mediaPlayer;
SongInfoModel obj;
public SongAdapter(Context context, ArrayList<SongInfoModel> SongList) {
this.context = context;
this.SongList = SongList;
}
#Override
public SongAdapter.SongHolder onCreateViewHolder(ViewGroup parent, int
viewType)
{
View view = LayoutInflater.from(context).inflate(R.layout.row_song,
parent, false);
return new SongHolder(view);
}
#Override
public void onBindViewHolder(final SongAdapter.SongHolder holder, final
int
position) {
final SongInfoModel songInfoModel = SongList.get(position);
holder.songName.setText(songInfoModel.SongName);
holder.artistName.setText(songInfoModel.ArtistName);
}
#Override
public int getItemCount() {
return SongList.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView songName;
TextView artistName;
TextView duration;
public SongHolder(View itemView) {
super(itemView);
songName = (TextView)itemView.findViewById(R.id.SongName);
artistName= (TextView)itemView.findViewById(R.id.ArtistName);
duration = itemView.findViewById(R.id.duration);
}
}
}
First, Create an Interface in Adapter class like this -
private CustomOnClickListener customOnClickListener;
public interface CustomOnClickListener{
void onClick(int position);
}
After that Implement View.OnClickListener in View holder class
class TracksViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TracksViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
customOnClickListener.onClick(getAdapterPosition());
}
After that Implement CustomOnClickListener in your Fragment or Activity class.