i m trying to get genre in list from below code.in the same way i got songs and albums bu t not getting genres.when app runs it nothing shows any error but shows blank activity.i have no idea what is wrong in this code.please give me some solution.let me know if you want another details.
genreActivity
public class BlankFragment3 extends Fragment {
ArrayList<genreInfo> genreList = new ArrayList<>();
RecyclerView recyclerView2;
private genreAdapter genreAdapter1;
String id;
Cursor cursor;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BlankFragment3() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.genrere, container, false);
recyclerView2 = rootView. findViewById(R.id.recyclerView2);
genreAdapter1 = new genreAdapter(genreList, getActivity());
recyclerView2.setAdapter(genreAdapter1);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView2.getContext(),
linearLayoutManager.getOrientation());
recyclerView2.setLayoutManager(linearLayoutManager);
recyclerView2.addItemDecoration(dividerItemDecoration);
getGenreList();
return rootView;
}
public void getGenreList() {
String[] proj1 = new String[]{
MediaStore.Audio.Genres.NAME,
MediaStore.Audio.Genres._ID
};
ContentResolver cr = getContext().getContentResolver();
cursor = cr.query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
int index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
String genre = cursor.getString(index);
index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
long genreId = Long.parseLong(cursor.getString(index));
Uri uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
Cursor tempCursor = cr.query(uri, null, null, null, null);
if (tempCursor.moveToFirst()) {
while (tempCursor.moveToNext()) {
index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
String title = tempCursor.getString(index);
index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST);
String artist = tempCursor.getString(index);
index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM);
String album = tempCursor.getString(index);
genreInfo g = new genreInfo(artist, title, album, genre);
genreList.add(g);
}
tempCursor.close();
}
}
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
genreAdapter
public class genreAdapter extends RecyclerView.Adapter<genreAdapter.GenreHolder> {
ArrayList<genreInfo> genreList=new ArrayList<>();
Context context;
MediaMetadataRetriever metaRetriver;
byte[] art;
public genreAdapter(ArrayList<genreInfo> genreList, Context context) {
this.genreList = genreList;
this.context = context;
}
#Override
public genreAdapter.GenreHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View myView = LayoutInflater.from(context).inflate(R.layout.genre,parent,false);
return new GenreHolder(myView);
}
#Override
public void onBindViewHolder(GenreHolder holder, int position) {
final genreInfo a = genreList.get(position);
holder.album.setText(genreList.get(position).getAlbum());
holder.title.setText(genreList.get(position).getTitle());
holder.artist.setText(genreList.get(position).getArtist());
/*
holder.artist.setText(genreList.get(position).getdName());
holder.album_art.setImageDrawable(Drawable.createFromPath(String.valueOf(albumList.get(position).getAlbumImg())));
*/
/* metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(String.valueOf(genreList.get(position).getID()));
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art,0,art.length);
holder.album_art.setImageBitmap(songImage);
} catch (Exception e)
{
holder.album_art.setBackgroundColor(Color.GRAY);
}*/
}
#Override
public int getItemCount()
{
return genreList.size();
}
public class GenreHolder extends RecyclerView.ViewHolder {
public TextView album;
public TextView artist;
public TextView title;
// public ImageView album_art;
public GenreHolder(View itemView) {
super(itemView);
// album_art = (ImageView) itemView.findViewById(R.id.albumArt);
artist = (TextView) itemView.findViewById(R.id.artistName);
title = (TextView) itemView.findViewById(R.id.titleName);
album = (TextView) itemView.findViewById(R.id.songName);
}
}
}
you are filling your ArrayList after creating adapter but at that time ArrayList is empty,
call getGenreList(); before creating adapter.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.genrere, container, false);
recyclerView2 = rootView. findViewById(R.id.recyclerView2);
getGenreList();
genreAdapter1 = new genreAdapter(genreList, getActivity());
recyclerView2.setAdapter(genreAdapter1);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView2.getContext(),
linearLayoutManager.getOrientation());
recyclerView2.setLayoutManager(linearLayoutManager);
recyclerView2.addItemDecoration(dividerItemDecoration);
return rootView;
}
Related
I basically want to display the data from firestore when the user selects an item from the second spinner and display it in a CardView inside RedcyclerView.
The code doesnt throw any errors but doesn't display the data either i.e nothing happens when an item is selected from the second spinner.
My Firestore Database schema is something like:
Tests > 7th (standard/grade) > Physics (subject) > QuestionNum > 1 > Document Auto-ID > qName,op1,op2,op3,op4,cop (fields).
This is QuestionListFragment.java where I want to display data
public class QuestionListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
Spinner spin1,spin2;
String sub,std,TAG="QuestionListFragment";
private FirebaseFirestore db;
private CollectionReference ref;
private QuestionItemAdapter adapter;
RecyclerView recyclerView;
public QuestionListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment QuestionListFragment.
*/
// TODO: Rename and change types and number of parameters
public static QuestionListFragment newInstance(String param1, String param2) {
QuestionListFragment fragment = new QuestionListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_question_list, container, false);
db=FirebaseFirestore.getInstance();
spin1=(Spinner)view.findViewById(R.id.list_standard_spinner);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_expandable_list_item_1, getResources().getStringArray(R.array.standard));
arrayAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin1.setAdapter(arrayAdapter1);
spin2= (Spinner) view.findViewById(R.id.list_subject_spinner);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.subjects));
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin2.setAdapter(arrayAdapter2);
spin2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//sub=spin2.getSelectedItem().toString().trim();
setUpRecylerView();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
recyclerView= view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
public void setUpRecylerView(){
for (int i=1;i<=50;i++){
Log.d(TAG, "setUpRecylerView: In setuprecylerview");
std=spin1.getSelectedItem().toString().trim();
sub=spin2.getSelectedItem().toString().trim();
CollectionReference cref;
ref=db.collection("Tests").document(std).collection(sub).document("QuestionNum").collection(String.valueOf(i));
Query query = ref.orderBy("qName",Query.Direction.ASCENDING);
FirestoreRecyclerOptions<QuestionItem> options = new FirestoreRecyclerOptions.Builder<QuestionItem>()
.setQuery(query,QuestionItem.class)
.build();
adapter=new QuestionItemAdapter(options);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
adapter.startListening();
}
}
}
This is QuestionItem.java
public class QuestionItem {
private String qName;
private String op1;
private String op2;
private String op3;
private String op4;
private String cop;
public QuestionItem(){
// Empty Constructor
}
public QuestionItem(String qName, String op1, String op2, String op3, String op4, String cop){
this.qName=qName;
this.op1=op1;
this.op2=op2;
this.op3=op3;
this.op4=op4;
this.cop=cop;
}
public String getqName() {
return qName;
}
public String getOp1() {
return op1;
}
public String getOp2() {
return op2;
}
public String getOp3() {
return op3;
}
public String getOp4() {
return op4;
}
public String getCop() {
return cop;
}
}
This is the adapater class QuestionItemAdapter.java
public class QuestionItemAdapter extends FirestoreRecyclerAdapter<QuestionItem,
QuestionItemAdapter.NoteHolder> {
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public QuestionItemAdapter(#NonNull FirestoreRecyclerOptions<QuestionItem> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull QuestionItemAdapter.NoteHolder holder, int position,
#NonNull QuestionItem model) {
holder.qname_textview.setText(model.getqName());
holder.op1_textview.setText(model.getOp1());
holder.op2_textview.setText(model.getOp2());
holder.op3_textview.setText(model.getOp3());
holder.op4_textview.setText(model.getOp4());
holder.cop_textview.setText(model.getCop());
}
#NonNull
#Override
public QuestionItemAdapter.NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.question_item,parent,false);
return new NoteHolder(v);
}
class NoteHolder extends RecyclerView.ViewHolder{
TextView qname_textview,op1_textview,op2_textview,op3_textview,op4_textview,cop_textview;
public NoteHolder(#NonNull View itemView) {
super(itemView);
qname_textview=itemView.findViewById(R.id.qName_display);
op1_textview=itemView.findViewById(R.id.op1_display);
op2_textview=itemView.findViewById(R.id.op2_display);
op3_textview=itemView.findViewById(R.id.op3_display);
op4_textview=itemView.findViewById(R.id.op4_display);
cop_textview=itemView.findViewById(R.id.correct_op_display);
}
}
}
And I followed this tutorial for reference.
I am having trouble with RecyclerView and cuscom Apdapter and I don't know why. My code isn't throwing error when I'm building but a
E/RecyclerView: No adapter attached; skipping layout
is showing at Run Logs.
I already watch a lot youtube tutorials and read other answers here at stockoverflow but still I am not able to fix my problem.
Here are my codes:
AccountFragment.java
public class AccountFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: MY VARIABLES
private RecyclerView listAccounts;
private ArrayList<Account> arrayAccount = new ArrayList<>();
private AdapterAccount adapterAccount;
private RecyclerView.LayoutManager layoutAccount;
private Context context;
private static final String accountURL = "LINK";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public AccountFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static AccountFragment newInstance(String param1, String param2) {
AccountFragment fragment = new AccountFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public void loadJSON(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, accountURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray accounts = new JSONArray(response);
for (int i = 0; i < accounts.length(); i++) {
JSONObject accountsObject = accounts.getJSONObject(i);
int id = accountsObject.optInt("accntID");
String username = accountsObject.optString("accntName");
String type = accountsObject.optString("accntType");
int station = accountsObject.optInt("statID");
String name = accountsObject.optString("lastName");
String address = accountsObject.optString("homeAddress");
String email = accountsObject.optString("emailAddress");
int contact = accountsObject.optInt("contactNumber");
Account account = new Account();
account.accountEntry(id, username, type, station, name, address, email, contact);
arrayAccount.add(account);
}
adapterAccount = new AdapterAccount(getContext());
listAccounts.setAdapter(adapterAccount);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
listAccounts = view.findViewById(R.id.accountRV);
layoutAccount = new LinearLayoutManager(getActivity());
listAccounts.setLayoutManager(layoutAccount);
loadJSON();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
AdapterAccount.java:
public class AdapterAccount extends RecyclerView.Adapter<AdapterAccount.ViewHolderAdapterAccount> {
private ArrayList<Account> arrayAccount = new ArrayList<>();
private LayoutInflater layoutInflater;
private Context context;
public AdapterAccount(Context context) {
this.context = context;
}
public AdapterAccount(ArrayList<Account> arrayAccount) {
this.arrayAccount = arrayAccount;
}
#Override
public ViewHolderAdapterAccount onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.profile_item, parent, false);
ViewHolderAdapterAccount viewHolder = new ViewHolderAdapterAccount(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderAdapterAccount holder, int position) {
Account currentAccount = arrayAccount.get(position);
holder.accountID.setText(currentAccount.getId());
holder.accountUsername.setText((currentAccount.getUsername()));
holder.accountType.setText(currentAccount.getType());
holder.accountStation.setText((currentAccount.getStation()));
holder.accountName.setText(currentAccount.getName());
holder.accountAddress.setText(currentAccount.getAddress());
holder.accountEmail.setText((currentAccount.getEmail()));
holder.accountContact.setText(currentAccount.getContact());
}
#Override
public int getItemCount() {
return arrayAccount.size();
}
static class ViewHolderAdapterAccount extends RecyclerView.ViewHolder {
private TextView accountID;
private TextView accountUsername;
private TextView accountType;
private TextView accountStation;
private TextView accountName;
private TextView accountAddress;
private TextView accountEmail;
private TextView accountContact;
public ViewHolderAdapterAccount(View accountView) {
super(accountView);
accountID = (TextView) itemView.findViewById(R.id.idPlaceXML);
accountUsername = (TextView) itemView.findViewById(R.id.usernamePlaceXML);
accountType = (TextView) itemView.findViewById(R.id.typePlaceXML);
accountStation = (TextView) itemView.findViewById(R.id.stationPlaceXML);
accountName = (TextView) itemView.findViewById(R.id.namePlaceXML);
accountAddress = (TextView) itemView.findViewById(R.id.addressPlaceXML);
accountEmail = (TextView) itemView.findViewById(R.id.emailPlaceXML);
accountContact = (TextView) itemView.findViewById(R.id.contactPlaceXML);
}
}
}
Account.java:
public class Account {
private int id;
private String username;
private String type;
private int station;
private String name;
private String address;
private String email;
private int contact;
public void accountEntry(int id,String username,String type,int station,String name,String address,String email,int contact){
this.id = id;
this.username = username;
this.type = type;
this.station = station;
this.name = name;
this.address = address;
this.email = email;
this.contact = contact;
}
public int getId(){
return id;
}
public String getUsername(){
return username;
}
public String getType() {
return type;
}
public int getStation() {
return station;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getEmail() {
return email;
}
public int getContact() {
return contact;
}
}
Add following method in AdapterAccount:
public setAccountList(ArrayList<Account> arrayAccount) {
this.arrayAccount = arrayAccount;
}
Change onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
listAccounts = view.findViewById(R.id.accountRV);
layoutAccount = new LinearLayoutManager(getActivity());
listAccounts.setLayoutManager(layoutAccount);
adapterAccount = new AdapterAccount(getContext());
listAccounts.setAdapter(adapterAccount);
loadJSON();
return view;
}
Change onResponse
public void onResponse(String response) {
try {
...
for (int i = 0; i < accounts.length(); i++) {
...
arrayAccount.add(account);
}
adapterAccount.setAccountList(arrayAccount);
adapterAccount.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
i want to show genre in my music app but when app runs and when i switch the tabs my app crashes and app stops working and give below logcat error.i dont know what that error is.please help.
this is the logcat
android.database.sqlite.SQLiteException: no such column: _display_name
(code 1): , while compiling: SELECT name, 0, _display_name FROM
audio_genres
at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:179)
at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at
android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
at android.content.ContentResolver.query(ContentResolver.java:754)
at android.content.ContentResolver.query(ContentResolver.java:704)
at android.content.ContentResolver.query(ContentResolver.java:662)
at layout.BlankFragment3.getGenreList(BlankFragment3.java:97)
at layout.BlankFragment3.onCreateView(BlankFragment3.java:77)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at
android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1984)
at
android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
at
android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
at
android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:668)
at
android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at
android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:611)
at
android.support.design.widget.TabLayout$ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2191)
at
android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1164)
at
android.support.design.widget.TabLayout.selectTab(TabLayout.java:1157)
at
android.support.design.widget.TabLayout.selectTab(TabLayout.java:1127)
at
android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1426)
at
android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1536)
at android.view.View.onKeyUp(View.java:12222)
at android.view.KeyEvent.dispatch(KeyEvent.java:2712)
at android.view.View.dispatchKeyEvent(View.java:11465)
main activity
public class BlankFragment3 extends Fragment {
ArrayList<genreInfo> genreList = new ArrayList<>();
RecyclerView recyclerView2;
private genreAdapter genreAdapter1;
long id;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BlankFragment3() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.genrere, container, false);
recyclerView2 = rootView. findViewById(R.id.recyclerView2);
genreAdapter1 = new genreAdapter(genreList, getActivity());
recyclerView2.setAdapter(genreAdapter1);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView2.getContext(),
linearLayoutManager.getOrientation());
recyclerView2.setLayoutManager(linearLayoutManager);
recyclerView2.addItemDecoration(dividerItemDecoration);
getGenreList();
return rootView;
}
public void getGenreList(){
final Uri uri = MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI;
String name=MediaStore.Audio.Genres.NAME;
try {
id = Long.parseLong(MediaStore.Audio.Genres._ID);
}catch (Exception e)
{
e.printStackTrace();
}
String dName=MediaStore.Audio.Media.DISPLAY_NAME;
// final String tracks = MediaStore.Audio.Albums.NUMBER_OF_SONGS;
final String[] columns = { name, String.valueOf(id), dName };
Cursor cursor = getContext().getContentResolver().query(uri, columns, null, null, null);
if(cursor!=null && cursor.moveToFirst()) do {
id = cursor.getLong(cursor.getColumnIndex(String.valueOf(id)));
name = cursor.getString(cursor.getColumnIndex(name));
dName = cursor.getString(cursor.getColumnIndex(dName));
//String artPath = cursor.getString(cursor.getColumnIndex(albumart));
//Bitmap art = BitmapFactory.decodeFile(artPath);
// int nr = Integer.parseInt(cursor.getString(cursor.getColumnIndex(tracks)));
genreInfo g = new genreInfo(id, name,dName);
genreList.add(g);
} while (cursor.moveToNext());
if (cursor != null) {
cursor.close();
}
recyclerView2.setAdapter(genreAdapter1);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
genreAdapter
public class genreAdapter extends RecyclerView.Adapter<genreAdapter.AlbumHolder> {
ArrayList<genreInfo> genreList=new ArrayList<>();
Context context;
public genreAdapter(ArrayList<genreInfo> genreList, Context context) {
this.genreList = genreList;
this.context = context;
}
#Override
public genreAdapter.AlbumHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View myView = LayoutInflater.from(context).inflate(R.layout.genre,parent,false);
return new AlbumHolder(myView);
}
#Override
public void onBindViewHolder(AlbumHolder holder, int position) {
final genreInfo a = genreList.get(position);
holder.album.setText(genreList.get(position).getName());
holder.artist.setText(genreList.get(position).getdName());
// holder.album_art.setImageDrawable(Drawable.createFromPath(String.valueOf(albumList.get(position).getAlbumImg())));
}
#Override
public int getItemCount() {
return genreList.size();
}
public class AlbumHolder extends RecyclerView.ViewHolder {
public TextView album;
public TextView artist;
//public ImageView album_art;
public AlbumHolder(View itemView) {
super(itemView);
// album_art = (ImageView) itemView.findViewById(R.id.albumArt);
artist = (TextView) itemView.findViewById(R.id.artistName);
album = (TextView) itemView.findViewById(R.id.songName);
}
}
}
The problem is with the column named _display_name .Check the spelling of this column. Also check whether this column is created when creating audio_genres table.
The pager returns the 1st object in the array list, and keeps returning the 1st object even if i swing left and right, did a lot of debugging, and for some reason when the pager get's to getItem(int position) it start's going crazy, it FINDS the corresponding object , then looks a the previous object(pos-1) then does some other weird things and returns the 1st obj in arrayList.
This method is called within the ViewHolder of RecyclerViewAdapter
#Override
public void onClick(View v) {
Intent i = ProductPageActivity.newIntent(v.getContext(),mProduct.getId());
v.getContext().startActivity(i);
}
}
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private static final String ARGUMENT_PROD_ID = "prod_id";
private TextView mTitle,mDesc,mImgUrl,mPrice;
private List<Product> mProducts;
private Product product;
public static Fragment newInstance(UUID productID) {
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_PROD_ID,productID);
ProductFragment frag = new ProductFragment();
frag.setArguments(args);
return frag;
}
public ProductFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
UUID id = (UUID) getArguments().getSerializable(ARGUMENT_PROD_ID);
product = ProductHolder.get(getContext()).getProduct(id);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_fragment,container,false);
setWidgets(v);
setDataOnText();
return v;
}
private void setDataOnText(){
mTitle.setText(product.getTitle());
mDesc.setText(product.getDesc());
mPrice.setText(product.getPrice());
}
private void setWidgets(View v) {
mTitle = (TextView) v.findViewById(R.id.title);
mDesc = (TextView) v.findViewById(R.id.desc);
mPrice = (TextView) v.findViewById(R.id.price);
}
}
public class ProductPageActivity extends AppCompatActivity {
private static final String PRODUCT_ID = "com.example.cmd.testproject.Activitys.ProductPageActivity.product_id";
private UUID productId;
private ViewPager mPager;
private List<Product> mProducts;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_page_activity);
productId = (UUID) getIntent().getSerializableExtra(PRODUCT_ID);
mPager = (ViewPager) findViewById(R.id.viewPager);
mProducts = ProductHolder.get(this).getProducts();
FragmentManager fragmentManager = getSupportFragmentManager();
mPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Product pr = mProducts.get(position);
return ProductFragment.newInstance(pr.getId());
}
#Override
public int getCount() {
return mProducts.size();
}
});
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(productId)) {
mPager.setCurrentItem(i);
break;
}
}
}
public static Intent newIntent(Context packageContext, UUID productID) {
Intent intent = new Intent(packageContext, ProductPageActivity.class);
intent.putExtra(PRODUCT_ID, productID);
return intent;
}
}
public class ProductHolder {
private static final String TAG = "ProductHolder";
private static ProductHolder sProductHolder;
private List<Product> mProducts;
public static ProductHolder get(Context ctx) {
if(sProductHolder == null) {
sProductHolder = new ProductHolder(ctx);
}
return sProductHolder;
}
private ProductHolder(Context ctx) {
mProducts = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Product product = new Product("Product = " + i, "Desc = "
+ i, "ImgUrl = " + i, "Price = " + i + 2.2);
mProducts.add(product);
}
}
public Product getProduct(UUID prodId) {
for (Product pr:mProducts) {
if(pr.getId().equals(prodId));
return pr;
}
return null;
}
public List<Product> getProducts() {
return mProducts;
}
}
I building a music player that has a tab layout. One of the tabs is "Genres"(Genre.java) that displays the genres of songs in RecyclerView( songs that are present on the external storage of the android phone, by querying it). I have set onClickListeners too for the genres in the RecyclerView. So, when I click one the genres it should take me to another activity (GenresSongs.java) that displays all the song belonging to that clicked genre.
My problem:
When I click any of the genres, it takes me to another activity but it displays the song that was last added to the array. No matter which genre I click it takes me to the same song.
What I want:
When I click one of genres in the list it should take me to the song that belongs to the clicked genre. I hope you are getting my point. I'm passing GenreID as intent.
Genre.java(class that displays the genre of all the songs) :
public class Genres extends Fragment {
private static final String TAG = "Genres";
RecyclerView recyclerView_genre;
GenresAdapter genresAdapter;
ArrayList<GenresModel> Genrelist = new ArrayList<>();
Cursor genrecursor;
long id;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.genres_activity, container, false);
recyclerView_genre = view.findViewById(R.id.recyclerView_genre);
LinearLayoutManager genreLayout = new LinearLayoutManager(getContext());
recyclerView_genre.setLayoutManager(genreLayout);
final Uri uri = MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI;
genrecursor = getActivity().getContentResolver().query(uri,null,null, null, null);
if (genrecursor != null) {
if (genrecursor.moveToFirst()) {
do {
id = genrecursor.getLong(genrecursor.getColumnIndex(MediaStore.Audio.Genres._ID));
String name = genrecursor.getString(genrecursor.getColumnIndex(MediaStore.Audio.Genres.NAME));
GenresModel genresModel = new GenresModel(id,name);
Genrelist.add(genresModel);
Collections.sort(Genrelist, new Comparator<GenresModel>() {
#Override
public int compare(GenresModel lhs, GenresModel rhs) {
return lhs.getGenreName().compareTo(rhs.getGenreName());
}
});
} while (genrecursor.moveToNext());
}
genrecursor.close();
}
genresAdapter = new GenresAdapter(getContext(), Genrelist, new GenresAdapter.GenreItemClickListener() {
#Override
public void onClickListener(GenresModel genresModel, int GenrePosition) {
Intent nIntent = new Intent(getContext(), GenresSong.class);
nIntent.putExtra("genre_ID", id);
startActivity(nIntent);
}
});
recyclerView_genre.setAdapter(genresAdapter);
genresAdapter.notifyDataSetChanged();
return view;
}
GenresAdapter.java(the adapter class of Genres.java):
public class GenresAdapter extends RecyclerView.Adapter<GenresAdapter.GenresHolder> {
private Context gContext;
private ArrayList<GenresModel> GenreList = new ArrayList<>();
private GenreItemClickListener listenerGenre;
public GenresAdapter(Context gContext, ArrayList<GenresModel> genreList, GenresAdapter.GenreItemClickListener listenerGenre) {
this.gContext = gContext;
GenreList = genreList;
this.listenerGenre = listenerGenre;
}
#Override
public GenresAdapter.GenresHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view3 = LayoutInflater.from(gContext).inflate(R.layout.row_genre, parent, false);
return new GenresHolder(view3);
}
#Override
public void onBindViewHolder(GenresAdapter.GenresHolder holder, int position) {
final GenresModel genresModel1 = GenreList.get(position);
holder.genreText.setText( genresModel1.getGenreName());
holder.bindSong(genresModel1, listenerGenre);
}
#Override
public int getItemCount() {
return GenreList.size();
}
public class GenresHolder extends RecyclerView.ViewHolder {
TextView genreText;
public GenresHolder(View itemView) {
super(itemView);
genreText = itemView.findViewById(R.id.genreText);
}
public void bindSong(final GenresModel genresModel1, final GenreItemClickListener listenerGenre) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listenerGenre.onClickListener(genresModel1, getLayoutPosition());
}
});
}
}
public interface GenreItemClickListener{
void onClickListener(GenresModel genresModel, int GenrePosition);
}
GenresSong.java(class that is supposed to display songs when genre is clicked):
public class GenresSong extends Activity {
RecyclerView recyclerView_genreSong;
ArrayList <GenreSongModel> GenreSongList = new ArrayList<>();
GenresSongAdapter genresSongAdapter;
long genreID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.genres_details);
recyclerView_genreSong = findViewById(R.id.recyclerView_genreSong);
LinearLayoutManager l1 = new LinearLayoutManager(getApplicationContext());
recyclerView_genreSong.setLayoutManager(l1);
genreID = getIntent().getExtras().getLong("genre_ID");
Uri uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreID);
String[] projection ={MediaStore.Audio.Media.TITLE};
Cursor cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
GenreSongModel s = new GenreSongModel(name);
GenreSongList.add(s);
} while (cursor.moveToNext());
}
cursor.close();
Collections.sort(GenreSongList, new Comparator<GenreSongModel>() {
#Override
public int compare(GenreSongModel lhs, GenreSongModel rhs) {
return lhs.getSongName().compareTo(rhs.getSongName());
}
});
}
genresSongAdapter = new GenresSongAdapter(getApplicationContext(), GenreSongList);
recyclerView_genreSong.setAdapter(genresSongAdapter);
genresSongAdapter.notifyDataSetChanged();
}
GenresSongAdapter.java(adapter class for GenresSong.java):
public class GenresSongAdapter extends RecyclerView.Adapter<GenresSongAdapter.GenresSongHolder> {
Context gsContext;
ArrayList<GenreSongModel> GenresSongList2 = new ArrayList<>();
public GenresSongAdapter(Context gsContext, ArrayList<GenreSongModel> genresSongList2) {
this.gsContext = gsContext;
GenresSongList2 = genresSongList2;
}
#Override
public GenresSongAdapter.GenresSongHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v5 = LayoutInflater.from(gsContext).inflate(R.layout.row_genredetails, parent, false);
return new GenresSongHolder(v5);
}
#Override
public void onBindViewHolder(GenresSongAdapter.GenresSongHolder holder, int position) {
GenreSongModel genreSongModel = GenresSongList2.get(position);
holder.genreSongName.setText(genreSongModel.getSongName());
}
#Override
public int getItemCount() {
return GenresSongList2.size();
}
public class GenresSongHolder extends RecyclerView.ViewHolder {
TextView genreSongName;
public GenresSongHolder(View itemView) {
super(itemView);
genreSongName = itemView.findViewById(R.id.genreSongName);
}
}