I am a beginner in android development. I make the firebase recycler view and try switch-case to add AdMob ads in the firebase recycler view but it didn't work. anybody, please guide me about banner ad(Admob) in firebase recycler view. [![enter image description here][1]][1]
here is my code :
MyAdapterWith
public class MyAdapterWith extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<Object> list;
DatabaseReference database;
private static final int item_data = 0;
private static final int item_banner = 1;
public MyAdapterWith(Context context, List<Object> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType){
case item_data:
View dataview = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemwith, parent, false);
return new MyViewHolder(dataview);
case item_banner:
default:
View bannerview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bannersinglerow, parent, false);
return new bannerviewholder(bannerview);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
int viewtype = getItemViewType(position);
switch (viewtype){
case item_data:
MyViewHolder mvh = (MyViewHolder) holder;
Historywith users = (Historywith) list.get(position);
mvh.status.setText(users.getStatus());
mvh.created_at.setText(users.getCreated_at());
mvh.plandetails.setText(users.getPlandetails());
mvh.amountfigure.setText(users.getAmountfigure());
mvh.amountwords.setText(users.getAmountwords());
database = FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("requestpayment").child(users.getStatus()).child("status");
if ((Integer.parseInt(users.getStatus()) == 1)){
mvh.statusaccept.setText("Accepted");
mvh.statusaccept.setVisibility(View.VISIBLE);
mvh.statuspendding.setVisibility(View.GONE);
}
else {
if((Integer.parseInt(users.getStatus()) == 0)){
mvh.statuspendding.setText("Pedding");
mvh.statusaccept.setVisibility(View.GONE);
mvh.statuspendding.setVisibility(View.VISIBLE);
}
}
break;
case item_banner:
default:
bannerviewholder bvh = (bannerviewholder) holder;
AdView adView = (AdView) list.get(position);
ViewGroup adcardview = (ViewGroup) bvh.itemView;
if (adcardview.getChildCount()>0)
adcardview.removeAllViews();
if (adcardview.getParent()!=null)
((ViewGroup)adView.getParent()).removeView(adView);
adcardview.addView(adView);
}
}
#Override
public int getItemCount() {
return list.size();
}
public int getItemViewType(int position){
if (position%withdraw.ITEM_PER_AD==0)
return item_banner;
else
return item_data;
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView status, created_at, plandetails, amountfigure, amountwords, statusaccept, statuspendding;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
status = itemView.findViewById(R.id.statuspendding);
created_at = itemView.findViewById(R.id.date);
plandetails = itemView.findViewById(R.id.plandetails);
amountfigure = itemView.findViewById(R.id.amountfigure);
amountwords = itemView.findViewById(R.id.amountwords);
statusaccept = itemView.findViewById(R.id.statusaccept);
statuspendding = itemView.findViewById(R.id.statuspendding);
}
}
public static class bannerviewholder extends RecyclerView.ViewHolder{
public bannerviewholder(#NonNull View itenView){
super(itenView);
}
}
}
withdraw(Activity)
public class withdraw extends AppCompatActivity {
RecyclerView recystatement;
DatabaseReference database;
MyAdapterWith myAdapter;
List<Object> list;
AdView adView;
FirebaseStorage storage;
static int ITEM_PER_AD = 2;
private static final String BANNER_AD_ID = "ca-app-pub-****************~**********";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_withdraw);
recystatement = findViewById(R.id.recystatement);
database = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getUid()).child("requestpayment");
recystatement.setHasFixedSize(true);
recystatement.setLayoutManager(new LinearLayoutManager(this));
storage = FirebaseStorage.getInstance();
list = new ArrayList();
myAdapter = new MyAdapterWith(this, list);
recystatement.setAdapter(myAdapter);
getbanneritems();
loadbannerads();
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.blue)));
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Object users = dataSnapshot.getValue(Object.class);
// users.setUserId(dataSnapshot.getKey());
list.add(users);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public void getbanneritems(){
for (int i=0; i<list.size(); i+=ITEM_PER_AD){
AdView adView = new AdView(withdraw.this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(BANNER_AD_ID);
list.add(i, adView);
}
}
public void loadbannerads(){
for (int i=0; i<list.size(); i++){
Object item = list.get(i);
if (item instanceof AdView){
final AdView adView = (AdView) item;
adView.loadAd(new AdRequest.Builder().build());
}
}
}
}```
[1]: https://i.stack.imgur.com/X84oJ.jpg
Related
I am trying to fetch data from my Parse database and display it into my RecyclerView. Upon entering the Fragment, the RecyclerView displays no data. It isn't until I Swipe Refresh the feed that the items are accurately displayed in the RecyclerView. How can I make the RecyclerView have the items already initialized upon entering the Fragment?
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
placeName = view.findViewById(R.id.profileEstablishmentName);
placeAddress = view.findViewById(R.id.restroomAddressInfo);
placeRating = view.findViewById(R.id.ratingBar);
rvFeed = view.findViewById(R.id.rvRestaurant);
swipeContainer = view.findViewById(R.id.swipeContainer);
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() { queryPosts(); }
});
allPosts = new ArrayList<>();
adapter = new PostsAdapter(getContext(), allPosts);
rvFeed.setAdapter(adapter);
rvFeed.setLayoutManager(new LinearLayoutManager(getContext()));
queryPosts();
setHasOptionsMenu(true);
}
Parse Query:
protected void queryPosts(){
ParseQuery<Post> query = ParseQuery.getQuery(Post.class);
query.include(Post.KEY_USER);
query.include(Post.KEY_PLACE_NAME);
//Constraint to only see posts of the selected Restaurant
query.whereEqualTo(Post.KEY_PLACE_NAME, placeName.getText().toString());
query.setLimit(20);
//Filters the order of the posts based on the time created key (newest on top)
query.addDescendingOrder(Post.KEY_CREATED_KEY);
query.findInBackground(new FindCallback<Post>() {
#Override
public void done(List<Post> posts, ParseException e) {
if (e != null) {
Log.e(TAG, "Issue with getting posts", e);
return;
}
for(Post post : posts){
Log.i(TAG, "Post: " + post.getPlaceName());
}
adapter.clear();
allPosts.addAll(posts);
adapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
}
});
}
PostAdapter:
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder>{
private Context context;
private List<Post> posts;
public PostsAdapter(Context context, List<Post> posts){
this.context = context;
this.posts = posts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Post post = posts.get(position);
holder.bind(post);
}
#Override
public int getItemCount() {
return posts.size();
}
public void clear() {
posts.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Post> list) {
posts.addAll(list);
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView tvUsername;
private TextView tvDescription;
private TextView tvPlaceName;
private ImageView ivImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvUsername = itemView.findViewById(R.id.username);
tvPlaceName = itemView.findViewById(R.id.placeName);
tvDescription = itemView.findViewById(R.id.reviewDescription);
ivImage = itemView.findViewById(R.id.ivImage);
}
public void bind(Post post) {
//Bind the post data to the view elements
tvDescription.setText(post.getDescription());
tvUsername.setText("#" + post.getUser().getUsername());
tvPlaceName.setText(post.getPlaceName());
ParseFile image = post.getImage();
if (image != null) {
Glide.with(context).load(post.getImage().getUrl()).into(ivImage);
}
}
}
I'm making my first app (calendar),
clicking the cardview item applies the same effect (changing Textview text color and Imageview background) to other items when scrolling the recycleview
in the main activity
RecyclerView daysRecyclerView;
DaysAdapter daysAdapter;
private RecyclerView.LayoutManager horizontalLayout;
ArrayList<DaysModel> daysModels;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
daysModels = getDaysList();
initDaysRecycleview();
}
private void initDaysRecycleview(){
daysRecyclerView = findViewById(R.id.daysRecyclerView);
daysRecyclerView.setHasFixedSize(true);
horizontalLayout = new LinearLayoutManager(this,RecyclerView.HORIZONTAL,false);
daysAdapter = new DaysAdapter(daysModels);
daysRecyclerView.setLayoutManager(horizontalLayout);
daysRecyclerView.setAdapter(daysAdapter);
daysAdapter.setOnItemClickListener(new DaysAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
dayClickHandler(position, 1);
}
});
}
public void dayClickHandler(int position, int change){
daysModels.get(position).changeDayHighlight(change);
daysAdapter.notifyItemChanged(position);
}
private ArrayList<DaysModel> getDaysList(){
//Not accurate used for testing
ArrayList<DaysModel> models = new ArrayList<DaysModel>();
String[] dayName ={"SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON"};
int i,j;
for (i = 0;i <dayName.length;i++){
j =i+1;
models.add(new DaysModel(dayName[i], j, 0, false));
}
return models;
}
I'm using an interface for the onClickListener.
ViewHolder
public class DaysViewHolder extends RecyclerView.ViewHolder {
TextView hDayName,hDayNumber;
ImageView currentDayHighlight;
CardView dayCard;
public DaysViewHolder(View itemView, DaysAdapter.OnItemClickListener listener) {
super(itemView);
this.hDayName = itemView.findViewById(R.id.dayName);
this.hDayNumber = itemView.findViewById(R.id.dayNumber);
this.currentDayHighlight = itemView.findViewById(R.id.dayHihlight);
this.dayCard = itemView.findViewById(R.id.dayCard);
dayCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
Adapter
public class DaysAdapter extends RecyclerView.Adapter<DaysViewHolder> {
Context context;
ArrayList<DaysModel> daysModels;
OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public DaysAdapter(ArrayList<DaysModel> daysModels) {
this.daysModels = daysModels;
}
#NonNull
#Override
public DaysViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.day_card,parent,false);
DaysViewHolder daysViewHolder = new DaysViewHolder(view, mListener);
return daysViewHolder;
}
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}
}
#Override
public int getItemCount() {
return daysModels.size();
}
}
sorry for the long code text, I've just started and I am already struggling.
All you need is to set else part for you if condition in bind method of Adapter class.
So change your bind method to something like this:
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}else{
holder.currentDayHighlight.setBackgroundResource(/*what ever you want for default situation*/);
holder.hDayNumber.setTextColor(/* for example Color.White*/);
}
}
I have a recycler view to show an activity timeline and three floating buttons that click to add activity. How can I code three buttons to a different view? How can I pass the condition to the Adapter?
Now I can show only one viewType.
thx a lot.
Adapter.java
public class TripAdapter extends RecyclerView.Adapter<TripAdapter.TripHolder> {
private List<Trip> trips = new ArrayList<>();
private OnItemClickListener listener;
#NonNull
#Override
public TripHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.trip_item, parent, false);
return new TripHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TripHolder holder, int position) {
Trip currentTrip = trips.get(position);
holder.textViewLodgingTitle.setText(currentTrip.getLodgingTitle());
holder.textTextViewLodgingCheckInDateTime.setText(currentTrip.getLodgingCheckInDateTime());
holder.textTextViewLodgingCheckOutDateTime.setText(currentTrip.getLodgingCheckOutDateTime());
holder.textViewLodgingAddress.setText(currentTrip.getLodgingAddress());
}
#Override
public int getItemCount() {
return trips.size();
}
public void setTrips(List<Trip> trips) {
this.trips = trips;
notifyDataSetChanged();
}
public Trip getTripAt(int position) {
return trips.get(position);
}
class TripHolder extends RecyclerView.ViewHolder {
//lodging
private TextView textViewLodgingTitle;
private TextView textTextViewLodgingCheckInDateTime;
private TextView textTextViewLodgingCheckOutDateTime;
private TextView textViewLodgingAddress;
private TextView textViewLodgingPhone;
private TextView textViewLodgingWebsite;
private TextView textViewLodgingEmail;
public TripHolder(#NonNull View itemView) {
super(itemView);
context = itemView.getContext();
textViewLodgingTitle = itemView.findViewById(R.id.text_view_title);
textTextViewLodgingCheckInDateTime = itemView.findViewById(R.id.text_view_start_date_time);
textTextViewLodgingCheckOutDateTime = itemView.findViewById(R.id.text_view_end_date_time);
textViewLodgingAddress = itemView.findViewById(R.id.text_view_description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(trips.get(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Trip trip);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
MainActivity.java
//adapter
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TripAdapter adapter = new TripAdapter();
recyclerView.setAdapter(adapter );
tripViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(TripViewModel.class);
tripViewModel.getAllTrips().observe(this, new Observer<List<Trip>>() {
#Override
public void onChanged(#Nullable List<Trip> trips) {
adapter.setTrips(trips);
}
});
//this on onActivityResult()
else if (requestCode == ADD_LODGING && resultCode == Activity.RESULT_OK) {
//get data from lodging activity
String lodgingTitle = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_TITLE);
String lodgingCheckInDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_IN_DATE_TIME);
String lodgingCheckOutDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_OUT_DATE_TIME);
String lodgingDescription = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_DESCRIPTION);
String lodgingAddress = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_ADDRESS);
String lodgingPhone = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_PHONE);
String lodgingWebsite = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_WEBSITE);
String lodgingEmail = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_EMAIL);
String lodgingImagePath = "test";
Trip lodging = new Trip(lodgingTitle, lodgingCheckInDateTime, lodgingCheckOutDateTime,lodgingDescription, lodgingAddress, lodgingPhone, lodgingWebsite, lodgingEmail,lodgingImagePath);
tripViewModel.insert(lodging);
Toast.makeText(this, "lodging save", Toast.LENGTH_SHORT).show();
}
My application I adapt from codinginflow channel.
https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction
I mean how to make the adapter work not with the model class, but with the already created ArrayList (randomPlaceList)? I take 20 records from my Firestore and put 3 random of them to the ArrayList(randomPlaceList). And now, I want that my adapter connect ViewHolder object not with the model class(Places.class), but with this early created ArrayList(randomPlaceList), where I have already 3 random records..
RecycleView class:
public class Myactivity extends AppCompatActivity {
public RecyclerView mResultList;
public FirebaseFirestore mFirestore;
public com.google.firebase.firestore.Query query;
public FirestoreRecyclerAdapter<Places, PlaceViewHolder> firestoreRecyclerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycle_activity);
mResultList = findViewById(R.id.list_result);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
Boolean l_check2 = getIntent().getExtras().getBoolean("2");
Boolean l_check3 = getIntent().getExtras().getBoolean("3");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("colour", "1").limit(20);
//QUESTION START HERE
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
int placeCount = placesList.size();
int randomNumber = new Random().nextInt(placeCount);
//THIS ARRAYLIST I WANT TO USE INSTEAD THE PLACES.CLASS
List<Places> randomPlaceList = new ArrayList<>();
for (int i=1; i<=3; i++) {
randomPlaceList.add(placesList.get(randomNumber));
}
}
}
});
} else if (l_check2) {
query = mFirestore.collection("Places").whereEqualTo("colour", "2").limit(3);
} else if (l_check3) {
query = mFirestore.collection("Places").whereEqualTo("colour", "3").limit(3);
}
mResultList.setLayoutManager(new LinearLayoutManager(this));
FirestoreRecyclerOptions<Places> options = new FirestoreRecyclerOptions.Builder<Places>()
.setQuery(query, Places.class)
.build();
firestoreRecyclerAdapter = new FirestoreRecyclerAdapter<Places, PlaceViewHolder>(options) {
#Override
protected void onBindViewHolder(PlaceViewHolder holder, int position, Places model) {
holder.setDetails(getApplicationContext(), model.getName(), model.getImage());
}
#Override
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
return new PlaceViewHolder(view);
}
};
mResultList.setAdapter(firestoreRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firestoreRecyclerAdapter.startListening();
}
class PlaceViewHolder extends RecyclerView.ViewHolder {
View mView;
public PlaceViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context context, String placeName, String placeImage) {
final TextView place_Name = mView.findViewById(R.id.text_image_id);
ImageView place_Image = mView.findViewById(R.id.image_id);
place_Name.setText(placeName);
Glide.with(context).load(placeImage).into(place_Image);
place_Name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Card_activity.class);
intent.putExtra("qwerty", place_Name.getText());
startActivity(intent);
}
});
}
}
#Override
protected void onStop() {
super.onStop();
if (firestoreRecyclerAdapter != null) {
firestoreRecyclerAdapter.stopListening();
}
}
}
And that model class, that used in OnCreate method, for query, but I need to use in Adapter, randomPlaceList to take 3 records, that already put earlier in it. In other words, use 2 model class, if I can say so..:
My Model class:
public class Places {
private String image, name;
public Places() { }
public Places(String image, String name) {
this.image = image;
this.name = name;
}
public String getImage() { return image; }
public String getName() { return name; }
}
EDITED WITH LISTVIEW:
MyListAdaper:
class MyListAdapter extends ArrayAdapter {
public MyListAdapter(Context context, int resource,List<Places> randomPLaceList) {
super(context, 0, randomPLaceList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_list, parent, false);
}
TextView place_Name = convertView.findViewById(R.id.text_image_id);
ImageView place_Image = convertView.findViewById(R.id.image_id);
Places places = (Places) getItem(position);
place_Name.setText(places.getName());
Glide.with(getContext()).load(places.getImage()).into(place_Image);
return convertView;
}
}
ListViewPlaces.class:
public class ListViewPlaces extends AppCompatActivity {
public ListView mListView;
public MyListAdapter myListAdapter;
public FirebaseFirestore mFirestore;
public Query query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_places);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("meet", "1").whereEqualTo("cash", "1").limit(7);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
//mListView = findViewById(R.id.place_list);
//mListView.setAdapter(myListAdapter);
final int placeCount = placesList.size();
final Random randomGenerator = new Random();
List<Places> randomPlaceList = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
}
ListView mListView = (ListView) findViewById(R.id.place_list);
MyListAdapter mListAdapter = new MyListAdapter(this, randomPlaceList);
mListView.setAdapter(mListAdapter);
}
}
});
}
}
}
Error:
error: constructor MyListAdapter in class MyListAdapter cannot be
applied to given types; required: Context,int,List found:
>,List reason:
actual and formal argument lists differ in length
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;
}
}