Unable to implement custom calendar view library in android java - java

I want to use this Calendar view in my android java app.
https://github.com/kizitonwose/CalendarView
I've tried myself first before coming here but I could not implement this in java as documentation is for Kotlin.
Someone please help me, I am stuck on step 2.
Step 2:
Kotlin Code of Documentation:
class DayViewContainer(view: View) : ViewContainer(view) {
val textView = view.calendarDayText
}
My Java Equivalent Code:
class DayViewContainer extends ViewContainer {
public DayViewContainer(View view) {
super(view);
final TextView calendar_day_text = view.findViewById(R.id.calendarDayText);
}
}
Kotlin Code of Documentation:
calendarView.dayBinder = object : DayBinder<DayViewContainer> {
// Called only when a new container is needed.
override fun create(view: View) = DayViewContainer(view)
// Called every time we need to reuse a container.
override fun bind(container: DayViewContainer, day: CalendarDay) {
container.textView.text = day.date.dayOfMonth.toString()
}
}
My Java Equivalent Code:
calendarView.setDayBinder(new DayBinder<DayViewContainer>(){
#Override
public DayViewContainer create(View view) {
return new DayViewContainer(view);
}
#Override
public void bind(DayViewContainer dayViewContainer, CalendarDay calendarDay) {
TextView textView =
dayViewContainer.getView().findViewById(R.id.calendarDayText);
textView.setText(calendarDay.getDate().getDayOfMonth());
}
});

DayViewContainer should make the TextView a member variable so you can actually access it. You could make a getter for it, but for simple classes like this my personal preference is to make fields public final to simplify it.
class DayViewContainer extends ViewContainer {
public final TextView calendarDayText;
public DayViewContainer(View view) {
super(view);
calendarDayText = view.findViewById(R.id.calendarDayText);
}
}
And since you're calling your own Java code, and we made this member field public, you don't need to call a getter for it in your DayBinder:
#Override
public void bind(DayViewContainer dayViewContainer, CalendarDay calendarDay) {
dayViewContainer.calendarDayText.setText(calendarDay.getDate().getDayOfMonth());
}

Thank you guys for showing some concern here.
I figured it out.
The mistake was that I was not converting integer days to String to use it as text on TextView.
The correction is here in following line:
textView.setText(Integer.toString(calendarDay.getDate().getDayOfMonth()));

Related

Accessing methods or classes from another java file/class from Activity

I am new to android studio but I am getting better at it as I program more and more. I have a MainActivity.java and the .xml file. And a friend provided me some code that it suppose to work with the input areas. The problem is I do not know how to access that regular java file. So that I can use it the way it is intended. He was using eclipse to build everything while I use android studio. I have the buttons all good to go and areas of input good to go but I just dont know how to implement his code. Any guidance will be greatly appreciated.
See examples to understand what I am trying to do.
"In android studio" a class is created called WaterDetails.java with a .xml file called activity_water_details.xml. There are calculations that were made for the duration that I need to be able to use or access from a java file created in eclipse called DurationCalculations.java. I have tried importing. I have tried opening the folder in explorer and putting the class in the same project. But, nothing seems to work.
Code:
public class WaterDetails extends AppCompatActivity {
Button continueWaterDetailsPart2;
EditText duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water_details);
duration = (EditText)findViewById(R.id.enter_duration);
duration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = duration.getText().toString();
if(duration.equals(" "))// if user inputs information
//Then get calculations from other java file.
}
});
Sample Code:
Second Java fie. The file I need to access.
package ScubanauiTables;
import java.util.Arrays;
public class DurationCalculations {
private int duration;
//Constructor
DurationCalculations(int duration, int maxDepth, int avgDepth, int temp, int visibility, int pressureStart,
int pressureEnd, String[] diveConditions, String[] diveActivities) {
setDuration(duration);
setMaxDepth(maxDepth);
setAvgDepth(avgDepth);
setTemp(temp);
setVisibility(visibility);
setPressureStart(pressureStart);
setPressureEnd(pressureEnd);
setAirType(21);
setDiveConditions(diveConditions);
setDiveActivities(diveActivities);
setPressureGroup();
public int getDuration() {
int temp = duration;
return temp;
}
private void setDuration(int duration) {
this.duration = duration;
}
I hope this sample code makes sense. Thank you all for your help in advance.
You want to use methods of your DurationCalculation class, and for that, you've to create an instance of that class.
You can instantiate and use your class like this
DurationCalculations durationCalculation = new DurationCalculations(
/*enter your constructor values*/);
Now you can call all public methods of your DurationCalculations class using durationCalculation variable like this
durationCalculation.getDuration();
You cannot call any private methods from outside of the class, like your setDuration() whose scope is set to private. For it be accessed outside of DurationCalculations class. You need to set it to public

How to load data according to data in recyclerview android java

I am very new to android and Firebase
So My Problem is: I have a RecylerView like this:
Note: I am Loading data from Firebase Firestore so please give answer according to that
And I want if anyone click on Pizza then pizza's data should be load like this:
If you have any question or doubt related to my question feel free to ask in comment.
How can I achieve that?
Can you provide the data model you are using in your RecyclerView's adapter? I imagine that you may have something like this (this is just an example):
{
"id": 123123
"name": "Pizza",
"image": "http://yourimageurl...",
.
.
.
}
So what I would do is to display a new fragment or activity passing the object that the user clicked. In order to do so, this class must be Parcelable. This way you will have the data you need to display in the next screen, and if you need to make another request, let's say using the id of the Pizza, you can also do it.
To exemplify, let's say you have a "Meal" class, so you just have to make this class Parcelable:
#Parcelize
data class Meal(
val id: Long,
val name: String,
val imageUrl: String
) : Parcelable
After this, in your item click callback, just call the fragment/activity you use to display selection info:
fun onItemClickListener(meal: Meal) {
val intent = Intent(this, MealDetailActivity::class.java)
intent.putExtra("selected_meal", meal)
startActivity(intent)
}
And in your "MealDetailActivity" just recover your meal object and use it to populate your view or fetch the data you need.
Hope this helps, if not tell me and I will try to be more specific.
UPDATE: I add the Java solution.
The Meal class would be something like this:
public class Meal implements Parcelable {
private long id;
private String name;
private String image;
public Meal(long id, String name, String image) {
this.id = id;
this.name = name;
this.image = image;
}
protected Meal(Parcel in) {
id = in.readLong();
name = in.readString();
image = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(name);
dest.writeString(image);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Meal> CREATOR = new Creator<Meal>() {
#Override
public Meal createFromParcel(Parcel in) {
return new Meal(in);
}
#Override
public Meal[] newArray(int size) {
return new Meal[size];
}
};
}
As you can see, in Java the Parcelable is much more verbose (I strongly suggest you start coding in Kotlin :P). However, when you make a Java class implement the Parcelable interface, the AndroidStudio will ask you to add the Parcelable implementation for you (before this, you have to write the attributes you want this class to have). To clarify this, follow these steps:
Create a new Java class
Add the attributes that this class needs
Write implements Parcelable
In the red lamp, click it and select "Add Parcelable implementation".
Then, in your item click callback, just call the fragment/activity you use to display selection info:
public void onMealItemClick(Meal meal) {
Intent intent = new Intent(this, MealDetailActivity.class);
intent.putExtra("selected_meal", meal);
startActivity(intent);
}
Finally, in your MealDetailActivity you can recover your Meal object:
#Override
public void onCreate(#Nullable Bundle onSavedInstanceState) {
Meal selectedMeal = getIntent().getParcelableExtra("selected_meal");
// do the stuff you need to do with your selected item.
}
As I said, I suggest you check how Parcelable works, since you will use it a lot in the future.
Hope this helps, if it does please mark as resolved :)

Linked List not updating values

So I've debugged my program and have found that the part of my program is updating, whilst another isn't.
I have a method:
public void storeApplication(String name, String item){
Application app = new Application(name, item);
peopleAttending.add(app);
}
The debugger reports that an object is contained in the LinkedList (peopleAttending).
In another method:
public void populateListView() {
int noOfPeopleAttending = peopleAttending.size();
String noPeopleAttending = String.valueOf(noOfPeopleAttending);
Toast.makeText(GuestsAttending.this, noPeopleAttending, Toast.LENGTH_SHORT).show();
}
This method can be called after the previous one and states that there isn't an object within the LinkedList.
I've checked the object references just to make sure that they are pointing at the same reference and they are.
Any help would be greatly appreciated.
EDIT: Entire Class:
public class GuestsAttending extends Activity {
private LinkedList<Application> peopleAttending = new LinkedList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guests_attending);
populateListView();
}
public void storeApplication(String name, String item){
Application app = new Application(name, item);
peopleAttending.add(app);
}
public void populateListView() {
// GuestsAdapter adapter = new GuestsAdapter(this, peopleAttending);
// ListView listView = (ListView) findViewById(R.id.listView);
// listView.setAdapter(adapter);
peopleAttending.size();
int noOfPeopleAttending = peopleAttending.size();
String noPeopleAttending = String.valueOf(noOfPeopleAttending);
Toast.makeText(GuestsAttending.this, noPeopleAttending, Toast.LENGTH_SHORT).show();
}
Second Edit:
Java Booking Screen Method:
public void saveBookingInfo(View view) {
GuestsAttending sendApplication = new GuestsAttending();
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
sendApplication.storeApplication(appName, appItemToBurn);
}
}
GuestsAttending Java Class: -- See Above.
Useful hint: It's really popular to set type of List as a List<> interface from java.util package instead of LinkedList<> itself.
Anyway, i am pretty sure that storeApplication method is not automatically triggered before onCreate method ran by Activity framework. Maybe your debugger is stopoing on it in different order (because of using threads or smth), but you should to log some invoke. Try to find it out.
I've found out what the problem is:
When I submit the booking information, it runs all the necessary methods. However, when the "storeApplication()" method has finished executing, the ArrayList 'empties' all the objects out.
I only noticed this when I used breakpoint and tried running the method twice, on the second time I entered booking details, the ArrayList stated it was empty.
I'm going to see if I can try and store the ArrayList in a more secure place.

Android, Calling view object from code

I am kind of a newbie so excuse me if this question is too simple or too hard.
I have this code in my java file:
public void button_baby_clicked(View v)
{
//do something here
}
this gets called when someone clicks the imagebutton in my xml file, but how do I call this from the java file itself?
Because it's expecting a View object... and I'm guessing I need to recreate that? How?
Edit:
Ok, to clarify, I want to be able to call the above function via a click in my xml file as well as a function under it.
For example:
public void button_baby_clicked(View v)
{
//do something here
}
public void someFunction()
{
x = 10;
button_baby_clicked(); // This should call the above function.
}
In ur ImageButton you have to add an attribute: android:onClick="button_baby_clicked"
In the java file, you have added:
public void button_baby_clicked(View v)
{
//do something here
}
The logic behind this is:
Upon clicking ur imagebutton, this method will automatically get called, i.e "v" argument will be having ur imagebutton.
The advantage of giving like this is: You no need to initialize the imagebutton in ur activity and no need to set click listener too for this imagebutton.
Alright, if you want to have the method invoked every time the view is clicked, do what the others have said.
Alternatively, you can do something like this.
ImageView globalReference;
#Override
public void onCreate(Bundle icicle){
*** CODE ***
globalReference = (ImageView) findViewById(R.id.myImageView);
*** CODE ***
}
Then, whenever you want that to be called with that particular View, simply call
button_baby_clicked(globalReference);
You can also do this with any View object you create dynamically.
View myTv = new TextView(context);
View myLl = new LinearLayout(context);
button_baby_clicked(myTv);
button_baby_clicked(myLl);
Just get a valid View reference within the same scope as the method, and pass it in like any other method. It can even be null if the method is capable of handling it.
Can't you use it like -
mButton.setOnClickListener(new OnClickListener{
#Override
public void onClick(View v) {
button_baby_clicked(v);
}
}
);
??
EDIT :
If you need to call someFunction() from the onClick of a button,and from there,you need to call button_baby_clicked(),you have to get View v object in someFunction. This link might help you. Please refer Start a service on onClick. You can change appropriately.
I believe its best if you refactor your code and put the code in the event handler into a global method that can be called from anywhere. like this:
public void button_baby_clicked(View v)
{
taskToPerform(); // Perform a certain task
}
public void someFunction()
{
x = 10;
taskToPerform(), // Perform the same task again
}
public void taskToPerform()
{
//This is where you write the task you want to perform
}
This way you can reuse the code in the taskToPerform() method anywhere, anytime.

setOnClickListener to all extended ImageViews - Java

I have a custom class that I've written that extends ImageView (for Android Java). I want to add a ClickListener to every instance I create of the class that will do the same thing (just animate the ImageView.
I tried a few different things to no avail. The code below is what I want to accomplish but it's being applied to an instantiated object of the class.
MyCustomImageView fd = new MyCustomImageView(this);
fd.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Animater(fd);
}
});
I tried using "implements onClickListener" on the class declaration and then a public void onClick() method in the class, and that didn't work for me.
I also tried using the code snippet above with a "this" instead of "fd" and that didn't work either.
I'm relatively new to java and this is out of the scope of my knowledge. Any assistance you can provide is greatly appreciated.
It's really easy. You have to do it in your custom class:
public class MyCustomImageView extends ImageView{
public MyCustomImageView(Context context){
super(context);
setOnClickListener(theCommonListener);
}
private OnClickListener theCommonListener = new OnClickListener(){
public void onClick(View v) {
// do what you want here
}
}
}
There are other ways to do it, but this is one is really easy to implement and understand. Every instance of MyCustomImageView will have the same event listener (unless you override it from outside).

Categories