I am trying to show just the name of the player from the array into the list view. this is my code for that:
player_List.setAdapter(new ArrayAdapter<Player>(this, android.R.layout.simple_list_item_1, dataStore.getPlayers()));
im getting all the information from that array using this call. i am unsure how to just call the name.
this is the coding for my data store:
/**
* This class is essentially a global library for the Scoresheet.
* It provides methods through which the Players and Teams can be accessed
* from any part of the application.
* The saving/loading of application data will also be handled through this
* class.
*
* You can access this DataStore by calling:
* DataStore dataStore = ((DataStore)getApplicationContext());
* From any Activity
*/
public class DataStore extends Application {
// Create ArrayLists to hold all our Player and Team objects
private ArrayList<Player> players = new ArrayList<Player>();
private ArrayList<Team> teams = new ArrayList<Team>();
// File names for our internal storage:
private String playerFileName = "players";
private String teamFileName = "teams";
/**
* Add a Player object to the list of players.
* #param p The Player object to add
*/
public void addPlayer(Player p){
this.players.add(p);
}
/**
* Merge an ArrayList of Player objects with the current collection of Players
* #param players ArrayList of Player objects to add to the collection
*/
public void addPlayers(ArrayList<Player> players){
Iterator<Player> it = players.iterator();
while (it.hasNext()){
this.players.add(it.next());
}
}
/**
* Return an ArrayList of player objects containing all Players
* #return
*/
public ArrayList<Player> getPlayers(){
return this.players;
}
and this is my player class:
public class Player implements Serializable{
// Randomly generate serial ID
private static final long serialVersionUID = 7423594865734681292L;
private static int ID = 0; // Class variable
public String name;
private int id;
public Player(String name) throws Exception{
this.setId(ID);
ID++; // Increment class ID counter
if (!this.setName(name))
throw new Exception("Invalid Name"); // This is the only way to prevent the object being instantiated if it has an invalid name
}
public String getName() {
return name;
}
/**
* Set the players name as desired.
* #param name
* #return true on success, false on fail
*/
public boolean setName(String name) {
// Only update the name if we are actually given a string
boolean success = false;
name = name.trim();
if (!name.equals("")){
this.name = name;
success = true;
}
return success;
}
public int getId() {
return id;
}
private void setId(int id) {
this.id = id;
}
}
Use CustomAdapter and set in getView(...) method
Like,
Player player = getPlayers().get(position);
textview.setText(player.name)
see this example,,
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
http://jnastase.alner.net/archive/2010/12/19/custom-android-listadapter.aspx
I'm no expert on android listview, but if it just uses toString to decide what to show, implement toString to just return name:
public String toString() { return name; }
Related
I've been stuck with this java search statement.
I'm trying to search in an Array of Products called stock which is initialized in the class Stockmanager, which contains an id field a name and a stock level.
these product objects are made in a separate class called Product.
constructor Stockmanager:
// A list of the products.
private ArrayList<Product> stock;
/**
* Initialise the stock manager.
*/
public StockManager()
{
stock = new ArrayList<>();
}
Product constructor:
// An identifying number for this product.
private int id;
// The name of this product.
private String name;
// The quantity of this product in stock.
private int quantity;
/**
* Constructor for objects of class Product.
* The initial stock quantity is zero.
* #param id The product's identifying number.
* #param name The product's name.
*/
public Product(int id, String name)
{
this.id = id;
this.name = name;
quantity = 0;
}
There is an accessor method in Product to retrieve a product object id:
/**
* #return The product's id.
*/
public int getID()
{
return id;
}
Now in Stockmanager, I have my search method, but it seems this method will complain about incompatible datatypes if I don't use my for-each loop or will complain about not having a return statement if I do use a for-each loop.
the method:
/**
* Try to find a product in the stock with the given id.
* #return The identified product, or null if there is none
* with a matching ID.
*/
public Product findProduct(int id)
{
int index = 0;
boolean searching = true;
for (Product item : stock)
{
while(searching && index < stock.size())
{
if (item.getID() == id)
{
searching = false;
return item;
} else {
index++;
}
if(searching)
{
return null;
} else {
return item;
}
}
}
}
It's got to be possible to have a while loop in this return statement because I don't need the method to look further in the array if it's found a hit.
Please, what am I doing wrong?
There's no reason to have two nested loops, and you don't need the index and searching variables.
You just need a single for loop. If you find a matching Product, you return it. If not, you return null when the loop ends.
public Product findProduct(int id)
{
for (Product item : stock) {
if (item.getID() == id) {
return item;
}
}
return null;
}
In Java 8 you could use the Stream API
public Optional<Product> findProduct(int id)
{
return stock.stream().filter(item -> item.getID() == id).findAny();
}
Before Java 8 simply implement it using a for loop.
public Product findProduct(int id)
{
for (Product item : stock)
{
if (item.getID() == id)
{
return item;
}
}
return null;
}
Just Remove if(searching) condition,
/**
* Try to find a product in the stock with the given id.
* #return The identified product, or null if there is none
* with a matching ID.
*/
public Product findProduct(int id){
for (Product item : stock){
if (item.getID() == id){
return item;
}
}
return null;
}
Why do you need while loop? There is no need of while loop.
To be clear, this is an active homework assignment. I just need some guidance.
I am creating a bookstore program in Java that, in revision 1, only has to return information about one specific book when it runs. I must use two classes, and call the info in the secondary class inside the main method to output.
I think I created the constructor correctly inside the Book class, but what's the best way to A) define those variables and B) call the info inside the Bookstore class to output? I just need some guidance here, as I'm kinda stuck. Eclipse is asking me to re-define the int and double variables as a String, but they are going to be numbers...is there something in my syntax that is causing it to do that?
Here's what I have so far:
import java.util.Scanner; // Import Scanner
/** Main Class */
public class Bookstore {
/** Secondary Class */
private class Book {
/** Declare Variables */
private int isbn;
private String bookTitle;
private String authorName;
private int yearPublished;
private String publisherName;
private double bookPrice;
/** Constructor */
Book (int isbn, String bookTitle, String authorName, int yearPublished, String publisherName, double bookPrice) {
setIsbn(isbn);
setBookTitle(bookTitle);
setAuthorName(authorName);
setYearPublished(yearPublished);
setPublisherName(publisherName);
setBookPrice(bookPrice);
}
/**
* #return the isbn
*/
public void getIsbn(int isbn) {
return isbn;
}
/**
* #param isbn the isbn to set
*/
public void setIsbn(int isbn) {
this.isbn = isbn;
}
/**
* #return the bookTitle
*/
public void getBookTitle(String bookTitle) {
return bookTitle;
}
/**
* #param bookTitle the bookTitle to set
*/
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle;
}
/**
* #return the authorName
*/
public String getAuthorName() {
return authorName;
}
/**
* #param authorName the authorName to set
*/
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
/**
* #return the yearPublished
*/
public int getYearPublished() {
return yearPublished;
}
/**
* #param yearPublished the yearPublished to set
*/
public void setYearPublished(int yearPublished) {
this.yearPublished = yearPublished;
}
/**
* #return the publisherName
*/
public String getPublisherName() {
return publisherName;
}
/**
* #param publisherName the publisherName to set
*/
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
/**
* #return the bookPrice
*/
public double getBookPrice() {
return bookPrice;
}
/**
* #param bookPrice the bookPrice to set
*/
public void setBookPrice(double bookPrice) {
this.bookPrice = bookPrice;
}
} // End Book Class
/** Main Method */
public static void main(String[] args) {
} // End Main Method
} // End Bookstore Class
That's where I'm at. Again, I'm stuck on how to define the variables properly, and then call the data for output in the Bookstore method. I know how to print it to the screen, it's just getting it there that is perplexing me. Do I create another Book object inside the Bookstore class?
I appreciate any help that's available.
Let's start with...
private class Book {
I would say declaring an inner class as private might not be the best choice, as you not be able to use beyond the scope of BookStore, but that's a choice you need to make...
This...
/**
* #return the isbn
*/
public void getIsbn(int isbn) {
return isbn;
}
is wrong on a number of accounts. First, it is declared as void, meaning that the method won't return anything, but then you use return isbn within the method. It should be declared as returning an int.
Next, you pass isbn as a parameter to the method, but immediately return the same value, this isn't really what you want to do, you want to return the value of isbn defined by Book, for example...
/**
* #return the isbn
*/
public int getIsbn() {
return isbn;
}
The same thing goes for getBookTitle.
In some languages they pass parameters by reference, meaning you can actually alter the value in the method/function and that will be reflected in the callers context. Java doesn't do this (more accurately, you can't reassign the value within the method and have it reflected in the caller). This is tripping point for many developers.
Basically, this means you can't do something like...
public void getBookTitle(String bookTitle) {
bookTitle = this.bookTitle;
}
As the value of the parameter will the same in the callers context after the method call as it was before it. You have to "get" the value from the class.
An interesting side effect though, is you can change the properties of objects passed to a method, if they supply mutable functionality...
I am making a simple text adventure game. I have a room class and an item class.
Each room has multiple items, and I am trying to make a method called addItem to store theitems in an ArrayList, but I get a NullPointerException when I try to add an item.
Room class
public class Room
{
private String description;
private HashMap<String, Room> exits;
private ArrayList<Item>items;
/**
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* #param description The room's description.
*/
public Room(String description)
{
this.description=description;
exits = new HashMap<String, Room>();
items = new ArrayList<Item>();
}
/**
* Define an exit from this room.
* #param direction The direction of the exit.
* #param neighbor The room to which the exit leads.
*/
public void setExit(String direction, Room neighbor)
{
exits.put(direction, neighbor);
}
/**
* #return The short description of the room
* (the one that was defined in the constructor).
*/
public String getShortDescription()
{
return description;
}
/**
* Return a description of the room in the form:
* You are in the kitchen.
* Exits: north west
* #return A long description of this room
*/
public String getLongDescription()
{
return "You are " + description + ".\n" + getExitString();
}
/**
* Return a string describing the room's exits, for example
* "Exits: north west".
* #return Details of the room's exits.
*/
private String getExitString()
{
String returnString = "Exits:";
Set<String> keys = exits.keySet();
for(String exit : keys) {
returnString += " " + exit;
}
return returnString;
}
/**
* Return the room that is reached if we go from this room in direction
* "direction". If there is no room in that direction, return null.
* #param direction The exit's direction.
* #return The room in the given direction.
*/
public Room getExit(String direction)
{
return exits.get(direction);
}
/**
* adds new item to the room
*/
public void addItem(String description)
{
Item Iitem = new Item(description);
items.add(Iitem);
}
}
Item Class
public class Item
{
private String description;
/**
* Constructor for objects of class Item
*/
public Item(String description)
{
this.description=description;
}
/**
* gets description of the item
*/
public String getDescription()
{
return description;
}
}
You never initialized items, so it's null.
items = new ArrayList<Item>();
Also I suggest you use interface for declaration, instead of a specific implementation
private Map<String, Room> exits; // stores exits of this room.
private List<Item> items;
You have not initialize the ArrayList<Item> items
You need to do:
ArrayList<Item> items = new ArrayList<Item>();
i have written two classes first one Member and second one Store. and i wrote a method which can create an object from the member class and i am trying to to write a field store of type Store in the Member class and i want it store a reference to the store the member has entered.
some told me to do this :
memberRegister() needs to be passed, as an argument, a pointer to the Store object that you are currently in.
In fact, the Store object needs to be able to tell the Member object "point to me". That is, the Store object needs a pointer to itself.
but i did not get it
this is Member class
private int pinNumber;
private String name, id;
private Store store;
/**
* Constructor for objects of class Member
*/
public Member(String name, String id, int pinNumber, Store store)
{
// initialise instance variables
this.name = name;
this.id = id;
this.pinNumber = pinNumber;
checkId();
checkPinNumber();
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
private void checkId()
{
// put your code here
int length;
length = id.length();
if (length > 10 ){
System.out.println("lentgh must be at 10 ");
}
}
private void checkPinNumber()
{
int length;
length = id.length();
if ((length > 4) && (length < 4 )){
System.out.println("lentgh must be at 4");
}
class store
private String storeName;
private int total;
private Member member;
/**
* Constructor for objects of class Store
*/
public Store(String storeName, int total)
{
// initialise instance variables
this.storeName = storeName;
this.total = total;
}
/**
*
*/
public String getStoreName()
{
return storeName;
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public Member memberRegister(String name, String id, int pinNumber)
{
// put your code here
Member member;
member = new Member(name, id, pinNumber)
return member;
}
your memberRegister method doesn't invoke your Member constructor correctly:
public Member memberRegister(String name, String id, int pinNumber)
{
// put your code here
Member member;
member = new Member(name, id, pinNumber, this) //this passes in a reference to your store
return member;
}
Then you assign the reference in your Member constructor:
public Member(String name, String id, int pinNumber, Store store)
{
// initialise instance variables
this.name = name;
this.id = id;
this.store = store //where this.store is a Store
this.pinNumber = pinNumber;
checkId();
checkPinNumber();
}
Hope that helps. By the way, update the comments in a way, that they match your code.
Using the keyword this is how you are able to get a self-referential pointer. You should be able to do as #Kerrek SB suggested and return new Member(name, id, pinNumber, this) from inside the memberRegister method.
See in your case passing this keyword to method memberRegister is useless
returning this keyword is useful.
to know more about this keyword check this
I want to improve my use of JDK 1.5 and stop using private static final String instead of enum. This is what seems to be recommended.
But now my constant class looks like this :
public class CEnum{
/**
* #author JJA
* date : 20/10/2010
*/
public enum ListTypeAffichage {
DEP("DEPOT_TVA"), PAD("PAS_DEPOT_TVA"), NORM("CAT_NORMALE"), CAP("CAT_PARTICULIERE"), CAA("CAT_AUTRE_CAS");
private final String sName;
/**
* #param name String
*/
ListTypeAffichage(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
}
/**
* #author JJA
* date : 20/10/2010
*/
public enum ListTypeCategorie {
DEDUIRE("SOMME_A_DEDUIRE"), AJOUTER("SOMME_A_AJOUTER");
private final String sName;
/**
* #param name String
*/
ListTypeCategorie(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
}
/**
* #author JJA
* date : 26/10/2010
*/
public enum ListInterval {
POS("POSITIF"), NS("NON_SIGNE");
private final String sName;
/**
* #param name String
*/
ListInterval(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getInterval() {
return sName;
}
}
}
instead of
public class ConstantesADMD {
public static final List<String> typeAffich = new ArrayList<String>();
...
ConstantesADMD(){
typeAffich.add("DEPOT_TVA");
typeAffich.add("PAS_DEPOT_TVA");
typeAffich.add("CAT_NORMALE");
...
}
}
My code seems to be really bad, but at least works. For each enum I have to add the redundant code :
private final String sName;
/**
* #param name String
*/
ListTypeAffichage(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
What improvment do you advise me?
Note : forget the last sentences of my first question, I need the index. Tell me if I have to post another question, editing my fisrt seems easier.
I would name my enum-constants as you have named your strings. You can then access the name using the Enum.toString() method. For example:
public enum ListTypeAffichage {
DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE, CAT_PARTICULIERE, CAT_AUTRE_CAS;
/**
* #return String
*/
public String getType() {
return toString();
}
}
You could of course also skip the getType() all together, and access the "type" using toString() instead:
ListTypeAffichage myEnum = ListTypeAffichage.CAT_PARTICULIRE;
System.out.println("Type: " + myEnum.toString()); // like this...
System.out.println("Type: " + myEnum); // ...or like this
According to the API, this is better than using the Enum.name() directly:
public final String name()
[...] Most programmers should use the toString() method in preference to this one [...]
Each enum has a name() method which return the exact string represantation of the constant. So you may do this:
public enum ListTypeAffichage {
DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE, CAT_PARTICULIERE, CAT_AUTRE_CAS
}
and then
ListTypeAffichage.DEPOT_TVA.name();
By using the abbreviations (DEP, PAD, NORM) etc. you have created aliases to (DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE) etc.
If you want to keep the abbreviations, then you'll have to maintain the enum as you have it.
If you are willing to do away with the abbreviations, then you can change you enum as below, I have included a main method in the enum to demonstrate its use.
public enum ListTypeAffichageNames {
DEPOT_TVA,
PAS_DEPOT_TVA,
CAT_NORMALE,
CAT_PARTICULIERE,
CAT_AUTRE_CAS;
public static void main(String[] args) {
System.out.println(DEPOT_TVA.toString());
ListTypeAffichageNames affichage = ListTypeAffichageNames.valueOf("DEPOT_TVA");
System.out.println(affichage.toString());
}
}
In addition to this, your current structure of constants does not give you compile time type checking, and does not prevent something like the following happening during runtime:
ConstantesADMD.typeAffich.clear();
// or
ConstantesADMD.typeAffich.remove("DEPOT_TVA");
ConstantesADMD.typeAffich.add("dEpOt-tVa");