How can I display another field from my object in vigiltime.setText? I want it to display the specific relating value of the time fields wihtin the object from the parishArrayList?
The parent.getItemAtPosition(position) already retrieves the specific object then how can I get it to parse relevant object details within the onItemSelected method?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parishArrayList = new ArrayList<>();
parishArrayList.add(new Parish(1, "Aghyaran", "Termonamongan, N.West Tyrone", "6.30pm", "10.00am"));
parishArrayList.add(new Parish(2, "Castlederg", "Castlederg, N.West Tyrone", "7pm", "11.00am"));
parishArrayList.add(new Parish(3, "Strabane", "Strabane, N.West Tyrone", "8pm", "12.00am"));
Spinner parishSpinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the parishArrayList and a default spinner layout
ArrayAdapter<Parish> parishAdapter = new ArrayAdapter<Parish>(getApplicationContext(), android.R.layout.simple_spinner_item, parishArrayList);
// Specify the layout to use when the list of choices appears
parishAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
parishSpinner.setAdapter(parishAdapter);
parishSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView vigiltime = (TextView) findViewById(R.id.vigiltime);
vigiltime.setText("Spinner selected : ");
vigiltime.setText(vigiltime.getText() + parent.getItemAtPosition(position).toString());
}
Parish.java
public class Parish {
private int parishIdNumber;
private String pName;
private String pAddress;
private String pVigilTimes;
private String pSundayTimes;
public Parish(int id, String name, String address, String vigilTimes, String sundayTimes) {
parishIdNumber = id;
pName = name;
pAddress = address;
pVigilTimes = vigilTimes;
pSundayTimes = sundayTimes;
}
public int getId() {
return parishIdNumber;
}
public void setId(int id) {
parishIdNumber = id;
}
public String getName() {
return pName;
}
public void setName(String name) {
pName = name;
}
public String getAddress() {
return pAddress;
}
public void setAddress(String address) {
pAddress = address;
}
public String getVigilTimes() {
return pVigilTimes;
}
public String getsundayTimes() {
return pSundayTimes;
}
public int getParishIdNumber() {
return parishIdNumber;
}
public void setParishIdNumber(int parishIdNumber) {
this.parishIdNumber = parishIdNumber;
}
#Override
public String toString() {
return pName;
}
}
You don't need to use toString(). You could simply call the relevant functions or variables of your Parish class:
Parish item = parent.getItemAtPosition(position);
vigilTime.setText("Spinner selected : ");
vigilTime.append(item.getTime() + " "); //append has the same effect as what you're currently doing
vigilTime.append(item.getSomethingElse + " ");
//etc
If you want to simply use toString(), override it in your Parish class:
#Override
public String toString() {
return /* format the String you want returned here */
}
EDIT: to answer your actual question:
ViewAdapter#getItemAtPosition() returns an Object, not your specific class. You need to cast that call to Parish:
Parish item = (Parish) parent.getItemAtPosition(position);
Then you can call item.getVigilTimes();.
Override the toString method in the class that you want to alter the string representation.
#Override
public String toString() {
//TODO - Here.
}
You can access any private variable of an object through a public method of class shown below.
vigiltime.setText(vigiltime.getText() + ((Parish)parent.getItemAtPosition(position)).getVigilTimes());
You can also override toString() method to display VigilTimes and call parent.getItemAtPosition(position).toString().
#Override
public String toString() {
return pVigilTimes;
}
The toString() method is inherited from the Object Class that every other class in java inherits from. The foundational toString() returns this:
getClass().getName() + '#' + Integer.toHexString(hashCode())
The string class if you are creating a new string object like String
first_name = 'someFirstName'
actually creates an instances with the constructor,
String first_name = new String("someFristName")
and this class overrides the object toString() method once more.
The documentation at Oracle says of toString() in the String class,
This object (which is already a string!) is itself returned.
Every single class that is created or built is directly or indirectly inherited from the Object class which has the foundational toString() which one can override within the current class. It's as simple as...
#Override
public String toString(){
//to do logic here
}
Your overrided toString() is nothing more than your getName() method. Consider if it is necessary.
Related
I have a provider that takes a decent number of properties. For example:
public MyProvider(
byte[] image,
String firstName,
String nickName,
String lastName,
String hairColor,
String favoriteFood,
String favoriteColor,
String cityBorn,
String stateBorn,
long favoriteNumber,
int age,
String nameOfFather,
String nameOfMother,
String nameOfBestFriend
)
I do know that I can get the value of each property, and set each individual one as an extra, like so:
Intent myIntent = new Intent(firstActivity.this, secondActivity.class);
myIntent.putExtra("firstName", myProvider.getFirstName().toString());
myIntent.putExtra("nickName", myProvider.getNickName().toString());
...
firstActivity.this.startActivity(myIntent);
I would like to just pass the entire provider as an extra, and then be able to get the provider in the next activity. I know it's possible to do such a thing in Swift, but I am not sure how to do so in Java for Android Studio.
What I am hoping to be able to do is something like the following:
MyProvider newPerson = new MyProvider(image, firstName, nickName, lastName, hairColor, favoriteFood, favoriteColor, cityBorn, stateBorn, favoriteNumber, age, nameOfFather, nameOfMother, nameOfBestFriend);
intent.putExtra(newPerson);
But it seems like a provider cannot be passed like this (or possibly at all?).
Alternative Attempt:
I also attempted passing it as data like a URI (see here), but .setData is specifically for URIs.
Is there such a way to pass the entire provider as an extra, and then be able to get the provider in the next activity?
Thanks in advance.
EDIT
I have implemented Parcelable as #NabinBhandari and #JuanCruzSoler suggested, but it is causing the following error:
Cannot resolve constructor 'MyProvider(byte[], java.lang.String, long)'
when I call:
MyApartmentsProvider newApartment = new MyApartmentsProvider(image, firstName, favoriteNumber);
My updated MyProvider.java is as follows:
(note: I cut out some variables for the time being to make the example easier to work with)
import android.os.Parcel;
import android.os.Parcelable;
public class MyProvider implements Parcelable {
/////////////////////////
// Initializers
byte[] image;
String firstName;
long favoriteNumber;
// End of [Initializers]
/////////////////////////
/////////////////////////
// Getters
public byte[] getImage() {
return image;
}
public String getFirstName() {
return firstName;
}
public long getFavoriteNumber() {
return favoriteNumber;
}
// End of [Getters]
/////////////////////////
/////////////////////////
// Setters
public void setImage(byte[] image) {
this.image = image;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setFavoriteNumber(long favoriteNumber) {
this.favoriteNumber = favoriteNumber;
}
// End of [Setters]
/////////////////////////
public MyProvider() {
super();
}
public MyProvider(Parcel parcel) {
image = new byte[parcel.readInt()];
parcel.readByteArray(image);
this.firstName = parcel.readString();
this.favoriteNumber = parcel.readLong();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(image.length);
parcel.writeByteArray(image);
parcel.writeString(this.firstName);
parcel.writeLong(this.favoriteNumber);
}
public static final Creator<MyProvider> CREATOR=new Creator<MyProvider>() {
#Override
public MyProvider createFromParcel(Parcel parcel) {
return new MyProvider(parcel);
}
#Override
public MyProvider[] newArray(int i) {
return new MyProvider[i];
}
};
}
Make your Provider class implement the interface Serializable or Parcelable.
Parcelable is faster but Serializable is easier to implement.
To send:
intent.putExtra(KEY, yourObj);
To receive:
Provider provider = (Provider) getIntent().getSerializableExtra(KEY);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So. I got a mission from my teacher to make a program that manages different students. The program will hold the name, education, information and points.
You will have the option to:
Add new students
Change education and information
Manage points
Making new students is not a problem, but managing education, info and points for specific students is the hard part, that's where I need your help. My main.java does not contain anything for now.
Student.java
package student;
public class Student {
String namn;
String program;
String info;
int points;
public void managePoints(){
}
public void changeProgram(){
}
public void changeInfo(){
}
}
Main.java
package student;
public class main {
public static void main(String[] args) {
}
}
According to the comments, I guess the three methods in your class are supposed to change the points, program and info of the student to a desired value. In Java, we call these setters.
You should rename your methods to setPoints, setProgram and setInfo. It's a pattern, you know.
Next, how are you going to know the "desired" value of those fields? You might say, I get them from the text boxes in the methods. But a better approach would be to get the values from another method and pass the value to the setters as a parameter.
To add a parameter to your methods, add a variable-like thingy in the brackets of the method declaration:
public void setPoints (int p)
And for the setInfo
public void setInfo (String i)
And so on.
In the method bodies, you set the fields to the parameters. E.g. In the setInfo method you write
info = i;
I think you can figure out the others.
Now how do you use these methods? For instance, suppose you have a student variable called student. And you got the info of him/her and stored it in a string variable called studentInfo. You can set the student variable's info to studentInfo by
student.setInfo (studentInfo);
Or if you don't want to use a variable, you can just use a string literal.
student.setInfo("this is my info. Blah blah blah");
I don't exactly know what do you want to actually do but your Student class (if I think correctly what you will need) should look more like this:
public class Student {
private String name; // private because you don't want anyone to interact with the variable too much.
private String program;
private String info;
private int points;
public Student( String name, String program, String info, int points ) { // contructor with variables to initialize. You can remove some of the variables if you do not consider they should be here.
this.name = name;
this.program = program;
this.info = info;
this.points = points;
// without `this` you would change parameter's value to itself which isn't what you want.
}
public String getName( ) { // getter because I guess you would like to know students name
return name;
}
public int getPoints( ) {
return points;
}
public void addPoints( int points ) { // setter so you can modify points
this.points += points;
}
public String getProgram( ) { // same as getName
return program;
}
public void setProgram( String program ) {
this.program = program;
}
public String getInfo( ) {
return info;
}
public void setInfo( String info ) {
this.info = info;
}
}
But how to use these methods? You use them as the example below shows
Student s1 = new Student("Abc Xyz", "IT", "Some informations", 12);
Student s2 = new Student("Cba Zyx", "Some other program", "Some more informations, 0);
s2.setInfo( s1.getInfo( ) );
s1.setPoints(1234);
s2.setProgram("Axbzcy");
Getter is a method which returns (most likely) private variable's value.
Setter is a method which sets private variable's value to another value which is passed as a parameter to the method.
Final code:
package student;
// The student class definition
public class Student {
private String name;
private String address;
private String info;
private String kurs;
private int points;
// Constructor
public Student(String name, String address, String info, String kurs, int points) {
this.name = name;
this.address = address;
this.points = points;
this.kurs = kurs;
this.info = info;
}
// Public getter for private variable name
public String getName() {
return name;
}
// Public getter for private variable address
public String getAddress() {
return address;
}
public String getInfo() {
return info;
}
public int getPoints() {
return points;
}
// Public setter for private variable address
public void setAddress(String address) {
this.address = address;
}
public void setPoints(int points){
this.points = points;
}
public void setInfo(String info){
this.info = info;
}
public void setKurs(String kurs){
this.kurs = kurs;
}
// Describe itself
public String toString() {
return name + ", Adress: " + address + ", Info: " + info + ", Kurs: " + kurs + ", Poäng: " + points +" ";
}
}
Main
package student;
// A test driver program for the Student class
public class main {
public static void main(String[] args) {
Student ArHa = new Student("A H", "Jysgaan 61", "ADHD", "Teknik", 5);
ArHa.setPoints(10);
ArHa.setKurs("TEINF");
System.out.println(ArHa);
Student DaSk = new Student("Dael Sklbr", "Fegea 65", "Svart", "Teknik", 5);
DaSk.setInfo("Riktigt svart");
System.out.println(DaSk);
Student FaMe = new Student("Falafel Medusa", "Fågel 123", "Maten", "Kock", 123);
System.out.println(FaMe);
}
}
Thank you everyone for the help.
I have started with parse to store the data of my class. I have followed parse guide and tutorials and tried to implement the code. Unfortunately, the objects of class are not getting saved in parse data browser. When I see the data in browser just one object id is shown not the columns of name, desc and qty of my item class. I have created class in dashboard also created columns respective to my data. Unable to get the solution as I am new to android and parse.
Here is my code
Item class
package com.example.owner.newstock;
import com.parse.ParseClassName;
import com.parse.ParseObject;
#ParseClassName("Item")
public class Item extends ParseObject {
public int id;
public String item_name;
public String item_desc;
public String item_qty;
public Item(){}
public Item(int id, String item_name, String item_desc, String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public Item(String item_name, String item_desc, String item_qty){
this.item_name = item_name;
this.item_desc=item_desc;
this.item_qty = item_qty;
}
public int getID(){
return id;
}
public void setID(int id){
this.id= id;
}
public String getItem_name(){
return getString(item_name);
}
public void setItem_name(String item_name)
{
put("item_name", item_name);
}
public String getItem_desc()
{
return getString(item_desc);
}
public void setItem_desc(String item_desc)
{
put("item_desc", item_desc);
}
public String getItem_qty()
{
return getString (item_qty);
}
public void setItem_qty(String item_qty){
put("item_qty", item_qty);
}
}
code of parse in main activity
ParseObject.registerSubclass(Item.class);
Parse.initialize(this, "Kw0dyUgLoqv24QdLE30mvFBVclEzLHRGtR2hQVHA", "5BWc3bAd60EgqU0sFIj31mMYYg7OIX9WKgC0a6oP");
ParseAnalytics.trackAppOpened(getIntent());
code to save the objects
Item i = new Item();
i.setItem_name(item_name);
i.setItem_desc(item_desc);
i.setItem_qty(item_qty);
i.saveInBackground();
Am I missing something?
Rather than creating an item class that extends ParseObject, set up a ParseObject variable, as follows:
ParseObject item = new ParseObject("Item");
Then put data in as follows:
item.put("quantity", yourQuantityVariable);
item.put("description", yourDescriptionVariable);
item.put("name", yourNameVariable);
To save:
item.saveInBackground();
To retrieve data, make use of querying and the getDataType() methods. Specified on https://parse.com/docs/android/guide#objects and https://parse.com/docs/android/guide#queries
I'm making a small RPG. There is an Item class which is the parent of each item in the game. These items could be Potion (which is a class) or Bandage (which is a class).
The Item class looks like this:
public class Item
{
int qty;
String name;
Hero hero1;
public void passHero(Hero hero1)
{
this.hero1 = hero1;
}
public void use()
{
if(qty == 0)
{
System.out.println("You have no more of this item to use.");
}
else
{
qty--;
}
}
public void addInv(int value)
{
qty = qty + value;
}
}
A method for passing in the Hero class.
A method for using an item.
A method for adding to the inventory of the item.
This method activates these item classes:
public void initializeItemInventory()
{
items[0] = new Potion();
items[1] = new Bandage();
}
And this method would theoretically print all the items and their quantities:
public void useInventory()
{
for(int i = 0; i<items.length; i++)
{
System.out.println("Enter: " + i + " for " + items[i].name);
}
int response = input.nextInt();
items[response].use();
}
The Potion class, as an example, has an instance variable like:
String name = "Potion";
So my question. Why isn't the name variable from Potion being called correctly in the useInventory method. It returns null which tells me it's returning the parent class Item name, and not the name of the individual subclass variables.
public class Item
{
int qty;
String name;
...
The Item class already has name, and that's what you access from an Item-typed variable:
items[0].name
So if you have
public class Potion extends Item
{
String name = "Potion";
...
then the Potion class has two name fields:
Potion p = new Potion();
System.out.println(p.name);
System.out.println((Item) p).name);
As you say, you want polymorphism, but it only applies to methods. Therefore you need a getter:
public class Item
{
String name;
public String getName() { return name; }
...
In the Potion subclass you may have
public class Potion extends Item
{
public Potion() { this.name = "Potion"; }
...
and items[0].getName() will now work as expected.
Additional note
I'll add this to show a bit of the power of polymorphism.
If you happened to have the name property always the same for all the instances of the same class, you could easily refactor your getter-based solution by completely eliminating the need to store a name variable:
public class Item
{
public String getName() { return "Generic item"; }
...
public class Potion extends Item
{
#Override public String getName() { return "Potion"; }
...
Instead of declaring a new variable in your subclass like "String name = "Potion";"
Use your constructor to pass the value to your superclass, something like this:
// the Item supuerclass has one constructor
public Item(name) {
this.name = name;
}
// the Potion subclass has one constructor
public Potion() {
super("Potion");
}
package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?
You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}
You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}
The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.
Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.
I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.