Retrieve Firestore Data into Recylerview not working - android

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.

Related

ERROR anonymous com.google.firebase.database.ValueEventListener

Error: 'UsersAdapter(java.util.List<com.thptcualo.main.models.User>, com.thptcualo.main.listeners.UserListener)' in 'com.thptcualo.main.adapters.UsersAdapter' cannot be applied to '(java.util.List<com.thptcualo.main.models.User>, anonymous com.google.firebase.database.ValueEventListener)'
Class Recycl
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserViewHolder>{
private final List<User> users;
//private final Userlistener userlistener;
private final UserListener userListener;
public UsersAdapter(List<User> users, UserListener userListener) {
this.users = users;
this.userListener = userListener;
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
ItemContainerBinding itemContainerBinding = ItemContainerBinding.inflate(
LayoutInflater.from(parent.getContext()), parent, false);
return new UserViewHolder(itemContainerBinding);
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
holder.setUserData(users.get(position));
}
#Override
public int getItemCount() {
return users.size();
}
class UserViewHolder extends RecyclerView.ViewHolder{
ItemContainerBinding binding;
UserViewHolder(ItemContainerBinding itemContainerBinding){
super(itemContainerBinding.getRoot());
binding = itemContainerBinding;
}
void setUserData(User user){
binding.TextName.setText(user.fullname);
binding.Textemail.setText(user.email);
//binding.getRoot().setOnClickListener(v->userlistener.onUserClicked(user));
binding.getRoot().setOnClickListener(v->userListener.onUserCLicked(user));
}
}
}
public class Tab2 extends Fragment implements UserListener {
// 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";
private String lmeo;
private Tab2Binding binding;
private PreferenceManager preferenceManager;
private String email;
//private PreferenceManager preferenceManager;
private String fullname;
//Tab2Binding binding;
private RecyclerView messagesRecyclerView;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Tab2() {
// 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 Tab2.
*/
// TODO: Rename and change types and number of parameters
public static Tab2 newInstance(String param1, String param2) {
Tab2 fragment = new Tab2();
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 void onViewCreated(View view, Bundle savedInstanceState) {
getUsers();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//preferenceManager = new PreferenceManager(getApplicationContext());
// Inflate the layout for this fragment
binding=Tab2Binding.inflate(inflater,container,false);
preferenceManager = new PreferenceManager(getActivity().getApplicationContext());
getToken();
return binding.getRoot();
//return inflater.inflate(R.layout.tab2, container, false);
}
private void getToken(){
FirebaseMessaging.getInstance().getToken().addOnSuccessListener(this::updateToken);
}
private void updateToken(String token) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance("https://somethings-great-default-rtdb.asia-southeast1.firebasedatabase.app").getReference("Users");
databaseReference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("keyfcm").setValue(token);
}
private void getUsers(){
loading(true);
DatabaseReference db = FirebaseDatabase.getInstance("https://somethings-great-default-rtdb.asia-southeast1.firebasedatabase.app").getReference("Users");
//db.getReference().child("User").get().addOnCompleteListener(this::onComplete);
loading(false);
//List<com.thptcualo.main.models.User> users = new ArrayList<>();
//String CurUserId = preferenceManager.getString(Constants.KEY_EMAIL);
DatabaseReference databaseReference = FirebaseDatabase.getInstance("https://somethings-great-default-rtdb.asia-southeast1.firebasedatabase.app").getReference();
databaseReference.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("email").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if(!task.isSuccessful()){
//
}
else{
//preferenceManager.putString(Constants.KEY_NAME,String.valueOf(task.getResult().getValue()));
lmeo = String.valueOf(task.getResult().getValue());
Log.d("firebasename",String.valueOf(task.getResult().getValue()));
}
}
});
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<User> users = new ArrayList<>();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
com.thptcualo.main.models.User user = new com.thptcualo.main.models.User();
user = dataSnapshot.getValue(User.class);
//Log.d("LOGTEST", CurUserId);
if(!user.email.equals(lmeo)) {
users.add(user);
}
user.token="error";
}
if(users.size()>0){
UsersAdapter usersAdapter = new UsersAdapter(users,this);
binding.usersRe.setAdapter(usersAdapter);
binding.usersRe.setVisibility(View.VISIBLE);
}else{
showerr();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void showerr(){
binding.TextError.setText(String.format("%s","Null lmao"));
binding.TextError.setVisibility(View.VISIBLE);
}
private void loading(Boolean isLoading){
if(isLoading){
binding.progressBar.setVisibility(View.VISIBLE);
}
else{
binding.progressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void onUserCLicked(User user) {
Intent intent = new Intent(getApplicationContext(),chatscreen.class);
intent.putExtra(Constants.KEY_USER,user);
startActivity(intent);
}
}
public interface UserListener {
void onUserCLicked(User user);
}
Since you're calling new UsersAdapter(users,this) inside db.addValueEventListener(new ValueEventListener() {, the this refers to the ValueEventListener and not to the Tab2/UserListener that you need.
To fix this, explicitly indicate what type of this you want:
UsersAdapter usersAdapter = new UsersAdapter(users,Tab2.this);
// 👆
Also see: Keyword for the outer class from an anonymous inner class

Problem when I delete a record on my firebase database

I'm trying to delete a record from my database and it work well only when in the database there is only one record and when there are more then one it works bad.
I delete only the item with specific date that i pass to the function.
This is my database:
This is the class where I delete the item on swipe:
public class HomeFragment 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;
private View rootView;
TextView titoloHome,sottotitoloHome,finePagina;
DatabaseReference reference;
RecyclerView recyclerViewMieiAllen;
ArrayList<MieiAllenamenti> list;
AllenamentiAdapter mieiAllenamentiAdapter;
Button btnAddNew;
public HomeFragment() {
// 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 HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
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,#NonNull ViewGroup container,
#NonNull Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
titoloHome = (TextView) rootView.findViewById(R.id.titoloHome);
sottotitoloHome = (TextView) rootView.findViewById(R.id.sottotitoloHome);
finePagina = (TextView) rootView.findViewById(R.id.finePagina);
btnAddNew = (Button) rootView.findViewById(R.id.btnAddNew);
//lavoro con i dati
recyclerViewMieiAllen=rootView.findViewById(R.id.mieiallenamentiRecyclerView);
recyclerViewMieiAllen.setLayoutManager(new LinearLayoutManager(rootView.getContext()));
list=new ArrayList<MieiAllenamenti>();
ItemTouchHelper itemTouchHelper=new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerViewMieiAllen);
try {
//prendo i dati dal database
reference= FirebaseDatabase.getInstance().getReference().child("WorkoutApp");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
// set code to retrive data and replace layout
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
MieiAllenamenti p = dataSnapshot1.getValue(MieiAllenamenti.class);
Log.d("uz",""+dataSnapshot1.getValue(MieiAllenamenti.class));
Log.d("uz",""+p.titleAllenamento);
list.add(p);
}
Log.d("LISTA",""+list.toString());
Context contexts = getActivity().getApplicationContext();
mieiAllenamentiAdapter = new AllenamentiAdapter(contexts, list);
recyclerViewMieiAllen.setAdapter(mieiAllenamentiAdapter);
Log.d("","SET ADAPTER");
Log.d("",mieiAllenamentiAdapter.getItemCount()+"");
mieiAllenamentiAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), "non ci sono dati",
Toast.LENGTH_LONG).show();
}
});
}catch (Exception e){}
btnAddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent a =new Intent(getActivity(),NuovoAllenamento.class);
startActivity(a);
}catch (Exception e){}
}
});
// Inflate the layout for this fragment
return rootView;
}
ItemTouchHelper.SimpleCallback simpleCallback=new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT ) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position=viewHolder.getAdapterPosition();
switch (direction){
case ItemTouchHelper.LEFT:
/*
reference.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});*/
Log.d("POSIZIONE",position+"");
Log.d("viewHolder",viewHolder.toString()+"");
Log.d("mieiAllenamentiAdapter",mieiAllenamentiAdapter.getData().toString());
new Thread(new Runnable() {
#Override
public void run() {
//this is a http request
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("WorkoutApp").orderByChild("dateAllenamento").equalTo(mieiAllenamentiAdapter.getData().toString());
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
appleSnapshot.getRef().removeValue();
}
mieiAllenamentiAdapter.deleteItem(position);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("TAG", "onCancelled", databaseError.toException());
}
});
}
}).start();
// mieiAllenamentiAdapter.notifyItemRemoved(position);
break;
}
}
};
}

RecyclerView: No adapter attached; skipping layout (Im using Fragments and a custom Adapter)

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();
}
}
}

how to get genre in list

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;
}

Getting the values of ListView selected item

I have this ListView adapter:
public class UpicksAdapter extends BaseAdapter
{
Context context;
List<Upick> upick_list;
public UpicksAdapter(List<Upick> listValue, Context context)
{
this.context = context;
this.upick_list = listValue;
}
#Override
public int getCount()
{
return this.upick_list.size();
}
#Override
public Object getItem(int position)
{
return this.upick_list.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_items, null);
viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView);
viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.SubNameTextView.setText(upick_list.get(position).Subject_Name);
viewItem.SubFullFormTextView.setText(upick_list.get(position).Subject_Full_Form);
return convertView;
}
}
class ViewItem
{
TextView SubNameTextView;
TextView SubFullFormTextView;
}
The ListView is in a fragment.
I need to get data from the listview selected item. I have this listener:
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = UpicksListView.getItemAtPosition(position).toString();
Log.d("VALOR","VALOR "+item);
}
});
How can I get the values of the selected item?
EDIT:
Complete Fragment code:
public class MisUpicksFragment 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";
private SessionManager session;
private ProgressDialog loading;
private EditText txtbusqueda;
private Button botonbuscar,botonrefrescar;
//movies
private static final String TAG = MainActivity.class.getSimpleName();
public List<Upick> upicks;
private RecyclerView recyclerView;
private GridLayoutManager gridLayout;
private UpicksAdapter adapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String user_id;
private Button btnNew;
ListView UpicksListView;
ProgressBar progressBar;
String HttpURL = "http://***/upicks_todos.php";
private OnFragmentInteractionListener mListener;
public MisUpicksFragment() {
// 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 MensajesFragment.
*/
// TODO: Rename and change types and number of parameters
public static MisUpicksFragment newInstance(String param1, String param2) {
MisUpicksFragment fragment = new MisUpicksFragment();
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 view = inflater.inflate(R.layout.fragment_misupicks, container, false);
UpicksListView = (ListView) view.findViewById(R.id.UpicksListView);
progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(getActivity()).execute();
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = UpicksListView.getItemAtPosition(position).toString();
Log.d("VALOR","VALOR "+item);
}
});
return view;
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
List<Upick> upickFullFormList;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Upick upick;
upickFullFormList = new ArrayList<Upick>();
for (int i = 0; i < jsonArray.length(); i++) {
upick = new Upick();
jsonObject = jsonArray.getJSONObject(i);
upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");
upickFullFormList.add(upick);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
UpicksListView.setVisibility(View.VISIBLE);
if (upickFullFormList != null) {
UpicksAdapter adapter = new UpicksAdapter(upickFullFormList, context);
UpicksListView.setAdapter(adapter);
}
}
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
//finish();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Change this code to setters.
upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");
eg:
upick.setSubjectname(jsonObject.getString("id_servicio"));
Then inside onclick you can take values using getters
String item = upicks.get(position).getSubjectname();
parent.getItemAtPosition(position) will return an Object (the model used in your adapter).To get some field from your Object don't call Object.toString(); it will return the object reference not the value that you're looking for. Use Object.yourField; instead.
The ArrayList.get() method is used to get the element of a specified
position within the list.
String str_ITEM= upicks.get(position).yourGETMETHOD();
in your callback listener you have adapter object just use that like below.
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = parent.getSelectedItem().toString();
Log.d("VALOR","VALOR "+item);
}
});

Categories

Resources