How can I populate a spinner with my Firebase database? - java

I want to populate a spinner instead of a ListView with data from Firebase.
The code below works fine with ListView. But how can I replace the ListView with a spinner? Hope someone can help me with this.
My research:
Firebase data to Spinner
Populatate the spinner from Firebase database
Here is my Main Activity:
public class Ansattliste extends AppCompatActivity {
DatabaseReference databaseAnsatt;
ListView lvansattliste;
Button btnleggtilansatt;
List<Ansatt> listansatt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ansattliste);
databaseAnsatt = FirebaseDatabase.getInstance().getReference("Ansatte");
lvansattliste = (ListView)findViewById(R.id.lvansattliste);
listansatt = new ArrayList<>();
btnleggtilansatt = (Button)findViewById(R.id.btnleggtilansatt);
btnleggtilansatt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent leggtil = new Intent(Ansattliste.this, Leggtilansatt.class);
startActivity(leggtil);
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseAnsatt.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
listansatt.clear();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
listansatt.add(ansatt);
final listAnsatt adapter = new listAnsatt(Ansattliste.this, listansatt);
lvansattliste.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
}
}
And my Adapter:
public class listAnsatt extends ArrayAdapter<Ansatt> {
private Activity context;
private List<Ansatt> listansatt;
public listAnsatt(Activity context, List<Ansatt> listansatt) {
super(context, R.layout.list_ansatt, listansatt);
this.context = context;
this.listansatt = listansatt;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_ansatt, null, true);
TextView tvansattnavn = (TextView) listViewItem.findViewById(R.id.tvansattnavn);
TextView tvansaattnr = (TextView) listViewItem.findViewById(R.id.tvansattnr);
Ansatt ansatt = listansatt.get(position);
tvansattnavn.setText(ansatt.getAnsattnavn());
tvansaattnr.setText(ansatt.getAnsattnr());
return listViewItem;
}
Firebase:
Firebase

You'd do something like following (I've adapted from Kotlin code I have here so possibility of some syntax errors)...have assumed for illustration that getAnsattnavn() is value you want to show in spinner. You'd still have listansatt which presumably you'd look up when item is selected in spinner.
In onDataChange:
List<String> optionList = new ArrayList<>();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
optionList.add(ansatt.getAnsattnavn());
listansatt.add(ansatt);
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, optionList);
spinnerControl.setAdapter(adapter);

Related

Recycler View doesn't show any item

I am trying to display contacts in a Fragment but the recycler view doesn't show any item. Despite having items in the list recycler view is not showing any item. I am not sure what I have done wrong as the app does not crash when it is running.
Here is The Code
public class UsersFragment extends Fragment {
RecyclerView recyclerView;
UsersAdapter adapter;
List<Users> actualuserList;
List<String> contactsList;
DatabaseReference reference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
contactsList = new ArrayList<>();
actualuserList = new ArrayList<>();
return view;
}
private void getContactList() {
Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (cursor.moveToNext()) {
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactsList.contains(phone)) {
cursor.moveToNext();
} else {
contactsList.add(phone);
}
}
getActualUser();
Log.d("contact: ", String.valueOf(contactsList.size()));
}
private void getActualUser() {
reference = FirebaseDatabase.getInstance().getReference().child("Users");
for (String number : contactsList) {
Query query = reference.orderByChild("phoneNumber").equalTo(number);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
actualuserList.clear();
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Users user = dataSnapshot.getValue(Users.class);
actualuserList.add(user);
}
Log.d("actual: ", String.valueOf(actualuserList.size()));
adapter = new UsersAdapter(getContext(), actualuserList);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getContactList();
}
}
In the Log statement, it is showing actual:1 that means there is an item.
Here is Adapter Code
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
Context mContext;
List<Users> mList;
public UsersAdapter(Context mContext, List<Users> mList) {
this.mContext = mContext;
this.mList = mList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.display_contacts, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final Users users = mList.get(position);
holder.name.setText(users.getUsername());
holder.number.setText(users.getPhoneNumber());
String url = users.getProfilephotoURL();
if (url.equals(""))
holder.circleImageView.setImageResource(R.drawable.ic_user);
else
Glide.with(mContext).load(url).into(holder.circleImageView);
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(mContext, ChatActivity.class);
intent.putExtra("name", users.getUsername());
intent.putExtra("firendPhoneNumber", users.getPhoneNumber());
mContext.startActivity(intent);
});
}
#Override
public int getItemCount() {
return mList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView name, number;
CircleImageView circleImageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.contactName);
number = itemView.findViewById(R.id.contactNumber);
circleImageView = itemView.findViewById(R.id.profilePic);
}
}
}
Logs
2020-07-27 14:52:51.651 25366-25366/com.mycompany.newchatapp D/contact:: 167
2020-07-27 14:52:51.670 25366-25366/com.mycompany.newchatapp E/RecyclerView: No adapter attached; skipping layout
2020-07-27 14:52:51.691 25366-25366/com.mycompany.newchatapp W/ClassMapper: No setter/field for status found on class com.mycompany.newchatapp.Model.Users
2020-07-27 14:52:51.691 25366-25366/com.mycompany.newchatapp D/actual:: 1
2020-07-27 14:52:51.723 25366-25366/com.mycompany.newchatapp W/ClassMapper: No setter/field for status found on class com.mycompany.newchatapp.Model.Users
2020-07-27 14:52:51.723 25366-25366/com.mycompany.newchatapp D/actual:: 1
Any Idea why this is happening?
Seems like you forgot to set adapter.
In onCreateView method put something like:
recyclerView.setAdapter(new UsersAdapter(this.getActivity(), getContactList()));
UPD:
Before that, make getContactList() return relevant dataset. Do not set adapter after initializing recycler view.
Strangely, I've faced this issue very recently and I was using as global List variable as well and the list wasn't empty, even the adpater was not empty but RecyclerView wasn't showing any data until second adpater.notifyDataSetchanged().
I'd found an answer here on this site that said "create a new list variable" and it worked.
Try making the actualUserList a local variable as in your onDataChange(),
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<Users> actualuserList = new ArrayList<>();
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Users user = dataSnapshot.getValue(Users.class);
actualuserList.add(user);
}
Log.d("actual: ", String.valueOf(actualuserList.size()));
adapter = new UsersAdapter(getContext(), actualuserList);
recyclerView.setAdapter(adapter);
}
}
If this doesn't solve your problem, you can also try calling notifyDataSetChanged() after setting up the adapter as adapter.notifyDataSetChanged();.
Also, set the adapter in onCreatedView() and call adapter.notifyDataSetChanged() in this onDataChange().

Android Dont know how to fix this index out of bounds exception FirebaseRecyclerview

I get this error and I dont know how to fix it
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.get(ArrayList.java:411)
at com.tijdelijk.firebasetest.Start$1.populateViewHolder(Start.java:69)
at com.tijdelijk.firebasetest.Start$1.populateViewHolder(Start.java:64)
I am working with firebase database and based on CategoryId I put the items in a arraylist for the SubCategories my code:
public class CategoryFragment extends Fragment {
View myFragment;
RecyclerView listCategory;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category, CategoryViewHolder> adapter;
FirebaseDatabase database;
DatabaseReference categories;
DatabaseReference subCategory;
public static CategoryFragment newInstance() {
CategoryFragment fragment = new CategoryFragment();
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
categories = database.getReference("Category");
subCategory = database.getReference("SubCategory");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_category, container, false);
listCategory = (RecyclerView) myFragment.findViewById(R.id.listCategory);
listCategory.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(container.getContext());
listCategory.setLayoutManager(layoutManager);
loadCategories();
return myFragment;
}
private void loadCategories() {
adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(
Category.class,
R.layout.category_layout,
CategoryViewHolder.class,
categories
) {
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, final Category model, int position) {
viewHolder.category_name.setText(model.getName());
Picasso.with(getActivity())
.load(model.getImage())
.into(viewHolder.category_image);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent startGame = new Intent(getActivity(), Start.class);
Common.categoryId = adapter.getRef(position).getKey();
loadSubCategory(Common.categoryId);
startActivity(startGame);
}
});
}
};
adapter.notifyDataSetChanged();
listCategory.setAdapter(adapter);
}
private void loadSubCategory(String categoryId) {
//Clear list if there are old subCategory
if (Common.subCategoryList.size() > 0) {
Common.subCategoryList.clear();
}
subCategory.orderByChild("CategoryId").equalTo(categoryId)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
SubCategory ques = postSnapshot.getValue(SubCategory.class);
Common.subCategoryList.add(ques);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
in this activity I want to display also a recyclerview but this time based on the arraylist I got from the categoryfragment here is my code:
public class Start extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference subCategory;
FirebaseRecyclerAdapter<SubCategory, SubCategoryViewHolder> adapter;
RecyclerView listSubCategory;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
database = FirebaseDatabase.getInstance();
subCategory = database.getReference("SubCategory");
listSubCategory = findViewById(R.id.listSubCategory);
listSubCategory.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getBaseContext());
listSubCategory.setLayoutManager(layoutManager);
loadSubCategories();
adapter.notifyDataSetChanged();
listSubCategory.setAdapter(adapter);
}
private void loadSubCategories() {
adapter = new FirebaseRecyclerAdapter<SubCategory, SubCategoryViewHolder>(
SubCategory.class,
R.layout.subcategory_layout,
SubCategoryViewHolder.class,
subCategory
) {
#Override
protected void populateViewHolder(SubCategoryViewHolder viewHolder, SubCategory model, int position) {
viewHolder.subcategory_nlname.setText(Common.subCategoryList.get(position).getLatijnseNaam());
viewHolder.subcategory_ltname.setText(Common.subCategoryList.get(position).getNederlandseNaam());
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent startGame = new Intent(Start.this, Start.class);
Common.categoryId = adapter.getRef(position).getKey();
startActivity(startGame);
}
});
}
};
}
}
here is my viewholder:
public class SubCategoryViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
public TextView subcategory_nlname;
public TextView subcategory_ltname;
private ItemClickListener itemClickListener;
public SubCategoryViewHolder(View itemView) {
super(itemView);
subcategory_ltname = itemView.findViewById(R.id.latijnse_naam);
subcategory_nlname = itemView.findViewById(R.id.nederlandse_naam);
// itemView.findViewById(R.id.btnPlay).setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
IndexOutOfBoundException means that you are trying to access a value that is at an index out of the array.
In your case, you have an array of two values. So you have the keys 0 and 1. As said in the error, your code is trying to access the index 2, which does not exist.
You have to check that you are accessing an index that is in the range of values of the array.
Good day to you.

Recycle view not displaying data on the first instance

Recycle view not displaying data its shows an empty screen, It displays data when I go back and click the icon again. Not sure why I'm facing this problem.Please check the activity, adaptor and fragment code below. I'm new to android and I'm doing my capstone project it would be great if you can help me.
public class AppDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("App Details");
setContentView(R.layout.activity_app);
AppDetailsFragment newFragment = new AppDetailsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordAppFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshAppDuration(View v) {
Intent intent = new Intent(this, AppDetailsActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackAppDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Adaptor
public class AppDetailsAdaptor extends RecyclerView.Adapter<AppDetailsAdaptor.ViewHolder> {
private List<AppUsage> mApps;
private Context mContext;
public AppDetailsAdaptor(Context context, List<AppUsage> apps) {
mApps = apps;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public AppDetailsAdaptor.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View appUsageView = inflater.inflate(R.layout.item_app_details, parent, false);
// Return a new holder instance
AppDetailsAdaptor.ViewHolder viewHolder = new AppDetailsAdaptor.ViewHolder(appUsageView);
return viewHolder;
}
#Override
public void onBindViewHolder(AppDetailsAdaptor.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final AppUsage ch = mApps.get(position);
// Set item views based on your views and data model
viewHolder._appTextView.setText(ch.getAppName());
viewHolder._durationTextView.setText(ch.getDurationInMinutes());
viewHolder._dateTextView.setText(ch.getDate().substring(0,10));
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mApps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _appTextView;
public TextView _durationTextView;
public TextView _dateTextView;
super(itemView);
_appTextView = (TextView) itemView.findViewById(R.id.rvs_app_name);
_durationTextView = (TextView) itemView.findViewById(R.id.rvs_app_duration);
_dateTextView =(TextView) itemView.findViewById(R.id.rvs_app_date);
}
}
}
Fragment
public class AppDetailsFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<AppUsage> appList = new ArrayList<>();
ArrayList<AppUsage> appListTemp = new ArrayList<>();
ArrayList<AppUsage> appListAdaptor = new ArrayList<>();
ArrayList<AppUsage> appObject = new ArrayList<>();
ArrayList<AppUsage> appListDate = new ArrayList<>();
private AppDetailsFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvApp;
private RecyclerView.Adapter appAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText date;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_list, container, false);
rvApp = (RecyclerView) rootView.findViewById(R.id.rvAppList);
rvApp.setHasFixedSize(true);
eLayoutManager = new LinearLayoutManager(getActivity());
rvApp.setLayoutManager(eLayoutManager);
appList = getAllAppRecords();
appAdaptor = new AppDetailsAdaptor(getActivity(), appList);
rvApp.setAdapter(appAdaptor);
return rootView;
}
public ArrayList<AppUsage> getAllAppRecords(){
DatabaseReference ref = database.getReference();
ref.child("AppUsage").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
appObject.clear();
HashMap<String,Object> app = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
app =(HashMap<String, Object>) item.getValue();
appObject.add(new AppUsage(app.get("appName").toString(),app.get("durationInMinutes").toString(),app.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return appObject;
}

Display Firebase data into a custom adapter view within Fragment tab

This is the edited version of my Fragment class inside my main activity. There were some bugs- it was not displaying anything and it was no longer saving the data to the database.
public static class DummyFragment extends Fragment {
int color;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
DatabaseReference mDatabaseGig;
final List<Dessert> dessertList;
// get the gig database
mDatabaseGig = FirebaseDatabase.getInstance().getReference("Gig Posts");
dessertList = new ArrayList<>();
mDatabaseGig.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot.getValue(Dessert.class);
dessertList.add(dessert);
}
DessertAdapter adapter = new DessertAdapter(getContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// possible to put progress dialogue
return view;
}
}
I already got the saving to firebase working perfectly and I'm using the MVC model - I created an adapter, a model and wired it to the main activity but my problem is how to use this model into the onAddValueEventChangedListener();
public class DessertAdapter extendsRecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts = new ArrayList<>();
private static final int VIEW_TYPE_EMPTY_LIST_PLACEHOLDER = 0;
private static final int VIEW_TYPE_OBJECT_VIEW = 1;
private Context context;
// TODO: placeholder stuff here
#Override
public int getItemViewType(int position) {
if (desserts.isEmpty()) {
return VIEW_TYPE_EMPTY_LIST_PLACEHOLDER;
} else {
return VIEW_TYPE_OBJECT_VIEW;
}
}
public DessertAdapter(Context context) {
this.context = context;
this.desserts = desserts;
desserts = Dessert.prepareDesserts(
context.getResources().getStringArray(R.array.dessert_names),
context.getResources().getStringArray(R.array.dessert_descriptions),
context.getResources().getStringArray(R.array.dessert_amounts));
}
// TODO: another placeholder stuff here
#Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_dessert, parent, false);
return new DessertAdapter.DessertVh(view);
}
#Override
public void onBindViewHolder(DessertVh holder, int position) {
Dessert dessert = desserts.get(position);
holder.mName.setText(dessert.getName());
holder.mDescription.setText(dessert.getDescription());
holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));
holder.mPrice.setText(String.valueOf(dessert.getAmount()));
}
#Override
public int getItemCount() {
// if nothing, return null,
// else return the number of items in the list
return desserts == null ? 0 : desserts.size();
}
public static class DessertVh extends RecyclerView.ViewHolder {
private TextView mName;
private TextView mPrice;
private TextView mDescription;
private TextView mFirstLetter;
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mPrice = (TextView) itemView.findViewById(R.id.txt_price);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
}
}
main activity where the tabs are displayed
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs_header);
// get the gig database
mDatabaseGig = FirebaseDatabase.getInstance().getReference("Gig Posts");
dessertList = new ArrayList<>();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this , this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
This handles the display of the data
#Override
public void onStart(){
super.onStart();
mFirebaseAuth.addAuthStateListener(firebaseAuthListener);
// load the data from database here
mDatabaseGig.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot.getValue(Dessert.class);
dessertList.add(dessert);
}
// maybe this will work?
DummyFragment dummyFragment = new DummyFragment();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
some code missing here but still part of mainactivity
This is the Dummy Fragment Class inside the main activity
public static class DummyFragment extends Fragment {
int color;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
// possible to put progress dialogue
DessertAdapter adapter = new DessertAdapter(getContext());
recyclerView.setAdapter(adapter);
return view;
}
}
Put the Firebase code inside the Fragment, not the Activity and also pass the dessertList as a param to the DessertAdapter.
Example:
public static class DummyFragment extends Fragment {
int color;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
DatabaseReference mDatabaseGig;
final List<Dessert> dessertList;
// get the gig database
mDatabaseGig = FirebaseDatabase.getInstance().getReference("Gig Posts");
dessertList = new ArrayList<>();
DessertAdapter adapter = new DessertAdapter(getContext(), dessertList);
recyclerView.setAdapter(adapter);
mDatabaseGig.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot.getValue(Dessert.class);
dessertList.add(dessert);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// possible to put progress dialogue
return view;
}
}

I've made my own ListView Adapter but no data is printed

This is what i have tried, but my ListView doesn't get filled. I use a custom adapter because i wan't to change the background color of the items that't got a boolean value = true. I am using Android Studio.
Hope someone can help.
i'm new to android.
public class ShoppingListActivity extends ActionBarActivity {
private TextView header;
private ListView listView;
private CustomArrayAdapter arrayAdapter;
private ShoppingList shoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
header = (TextView)findViewById(R.id.textView2);
//get reference to ListView
listView = (ListView)findViewById(R.id.shoppingListItemsView);
shoppingList = (ShoppingList) getIntent().getSerializableExtra(Globals.CHOSENLISTKEY);
arrayAdapter = new CustomArrayAdapter(this, R.layout.custom_list_view, shoppingList.getItemList());
listView.setAdapter(arrayAdapter);
header.setText(shoppingList.toString());
Button btnShop = (Button) findViewById(R.id.btnShop);
btnShop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ShoppingListActivity.this, SelectStoreActivity.class);
startActivity(intent);
}
});
}
public void setData() {
for(int i = 0; i < shoppingList.getItemList().size(); i++) {
arrayAdapter.add(shoppingList.getItemList().get(i));
}
}
}
public class CustomArrayAdapter extends ArrayAdapter<Entry> {
private int resource;
private ArrayList<Entry> list;
public CustomArrayAdapter(Context context, int resource, ArrayList<Entry> list) {
super(context, resource);
this.resource = resource;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parentGroup) {
View view = convertView;
Entry entry = list.get((position));
if(view == null) {
LayoutInflater layoutInflater = ((Activity) getContext()).getLayoutInflater();
view = layoutInflater.inflate(resource, parentGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.customName);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
return view;
}
}
To show data in ListView rows call setText method of TextView which is return from getView method:
TextView textView = (TextView) view.findViewById(R.id.customName);
// get Text from entry and pass it to setText method
String strTextViewData=entry.getItem()...;
textView.setText(strTextViewData);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}

Categories