Hi sorry for the vague title. I have a specific issue with the Amazon IAP API that you will see in the bottom of the post.
I implemented the API in the simplest way possible, that is I just imported their sample IAP app and pasted all of it in my app. I think the only thing that needs to be changed from the sample app is the SKU and marketplace.
This is a class called MySku.java from the sample app:
package com.amazon.sample.iap.entitlement;
/**
*
* MySku enum contains all In App Purchase products definition that the sample
* app will use. The product definition includes two properties: "SKU" and
* "Available Marketplace".
*
*/
public enum MySku {
// The only entitlement product used in this sample app
LEVEL2("com.amazon.sample.iap.entitlement.level2", "US");
private final String sku;
private final String availableMarkpetplace;
/**
* Returns the MySku object from the specified Sku and marketplace value.
*
* #param sku
* #param marketplace
* #return
*/
public static MySku fromSku(final String sku, final String marketplace) {
if (LEVEL2.getSku().equals(sku) && (marketplace == null || LEVEL2.getAvailableMarketplace().equalsIgnoreCase(marketplace))) {
return LEVEL2;
}
return null;
}
/**
* Returns the Sku string of the MySku object
*
* #return
*/
public String getSku() {
return this.sku;
}
/**
* Returns the Available Marketplace of the MySku object
*
* #return
*/
public String getAvailableMarketplace() {
return this.availableMarkpetplace;
}
private MySku(final String sku, final String availableMarkpetplace) {
this.sku = sku;
this.availableMarkpetplace = availableMarkpetplace;
}
}
So I have to change the sku and availableMarketplace. I know my in-app product's sku so I set it, but what do I change availableMarketPlace to so that my app allows all marketPlaces instead of just the US one?
you need to declare each SKU for each availableMarkpetplace, like this>
LEVEL2("com.amazon.sample.iap.entitlement.level2", "US"),
LEVEL2_MX("com.amazon.sample.iap.entitlement.level2", "MX");
And for the MySku function as follows>
public static MySku fromSku(final String sku, final String marketplace) {
for (MySku mySku : values()) {
if (mySku.getSku().equals(sku) &&
(null == marketplace || mySku.getAvailableMarketplace().equals(marketplace))) {
return mySku;
}
}
return null;
}
Don Pec
Related
Trying to print the username in the method printShortSummary in the MessagePost class. The username is private in the Post class. Doing this for educational purposes. Still getting error that the username is private in Post.
import java.util.ArrayList;
/**
* This class stores information about a news feed post in a
* social network. Posts can be stored and displayed. This class
* serves as a superclass for more specific post types.
*
* #author Michael Kölling and David J. Barnes
* #version 0.2
*/
public class Post
{
private String username; // username of the post's author
private long timestamp;
private int likes;
private ArrayList<String> comments;
/**
* Constructor for objects of class Post.
*
* #param author The username of the author of this post.
*/
public Post(String author)
{
username = author;
timestamp = System.currentTimeMillis();
likes = 0;
comments = new ArrayList<>();
}
public void getUserName()
{
getUserName();
}
/**
* Record one more 'Like' indication from a user.
*/
public void like()
{
likes++;
}
/**
* Record that a user has withdrawn his/her 'Like' vote.
*/
public void unlike()
{
if (likes > 0) {
likes--;
}
}
/**
* Add a comment to this post.
*
* #param text The new comment to add.
*/
public void addComment(String text)
{
comments.add(text);
}
/**
* Return the time of creation of this post.
*
* #return The post's creation time, as a system time value.
*/
public long getTimeStamp()
{
return timestamp;
}
/**
* Display the details of this post.
*
* (Currently: Print to the text terminal. This is simulating display
* in a web browser for now.)
*/
public void display()
{
System.out.println(username);
System.out.print(timeString(timestamp));
if(likes > 0) {
System.out.println(" - " + likes + " people like this.");
}
else {
System.out.println();
}
if(comments.isEmpty()) {
System.out.println(" No comments.");
}
else {
System.out.println(" " + comments.size() + " comment(s). Click here to view.");
}
}
/**
* Create a string describing a time point in the past in terms
* relative to current time, such as "30 seconds ago" or "7 minutes ago".
* Currently, only seconds and minutes are used for the string.
*
* #param time The time value to convert (in system milliseconds)
* #return A relative time string for the given time
*/
private String timeString(long time)
{
long current = System.currentTimeMillis();
long pastMillis = current - time; // time passed in milliseconds
long seconds = pastMillis/1000;
long minutes = seconds/60;
if(minutes > 0) {
return minutes + " minutes ago";
}
else {
return seconds + " seconds ago";
}
}
}
import java.util.ArrayList;
/**
* This class stores information about a post in a social network news feed.
* The main part of the post consists of a (possibly multi-line)
* text message. Other data, such as author and time, are also stored.
*
* #author Michael Kölling and David J. Barnes
* #version 0.2
*/
public class MessagePost extends Post
{
private String message; // an arbitrarily long, multi-line message
/**
* Constructor for objects of class MessagePost.
*
* #param author The username of the author of this post.
* #param text The text of this post.
*/
public MessagePost(String author, String text)
{
super(author);
message = text;
}
public static void printShortSummary()
{
Post.getUserName();
System.out.print ("Message postfrom" + username);
}
/**
* Return the text of this post.
*
* #return The post's message text.
*/
public String getText()
{
return message;
}
}
You should be calling getUserName() but obviously cannot because it returns void and causes a Stack Overflow exception if called:
public void getUserName()
{
getUserName();
}
This should be
public String getUserName()
{
return userName;
}
And then that's how you access the user name from the subclass.
After that you would modify this method to be:
public static void printShortSummary()
{
//Post.getUserName();
System.out.print ("Message postfrom" + getUserName());
}
The portion where you have Post.getUserName(); doesn't make any sense, it's not a static method and can't be referenced in that manner.
If you don't have access to Post class or you don't wanna change Post class, you can use java Reflection API to access private members in any class
Ex:
public void printShortSummary() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = Post.class.getDeclaredField("username");
field.setAccessible(true);
System.out.print("Message post from " + field.get(this).toString());
}
Note : Anyway this not the object oriented way
I am starting to develop my skills in JAVA, however I have a doubt.
I'm creating an object in JAVA, created the constructor and so on, then, it asks "Change the AGE_RECENT value from 1 to 3", I initially declared this as final because I never thought it would change, so no SET or GET were created. I am wondering how can I change the value from 1 to 3 in the SET Method.
I have this variable
private static int AGE_RECENT=1;
I did this.
public void setAgeRecent() {
Vehicle.AGE_RECENT = 3;
}
It works if you run the program, it changes the variable's value, however nothing was declared in that method as every SET method.
Just wondering how can I do this. If this is correct, good, if not, thanks for helping!
As someone asked, the code.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tp1;
/**
*
* #author Nelson
*/
public class Vehicle {
/** Variáveis da classe, têm como função **/
private String registration;
private int registrationYear;
private double consumption;
private double autonomy;
private int cilinderCapacity;
/**
* Final variables. They are final because they do not suffer any kind of modification during the project.
* YEAR_OMISSION is 2016 because the currect year is 2016.
* ENVIRONMENTAL_CHARGE_OMISSION is 0.10(10 cents), gave this value because there is nothing to mention the
especific value, hence why I gave 0.10.
* RATING_RECENT = Is a string, just has the text "RECENT" inside.
* RATING_COMTEMPORY - Another string, just with the "Comtempory" text inside.
* RATING_CLASSIC - Yet again another string, with the "Classic" text.
* AGE_RECENT - It is to help to compare if a vehicle is recent or not, it has the value 3.
* AGE_CLASSIC - It is to again help to compare, value is 20.
*/
private static final int YEAR_OMISSION = 2016;
private static final double ENVIRONMENTAL_CHARGE_OMISSION=0.10;
private static final String RATING_RECENT="Recent";
private static final String RATING_CONTEMPORY="Contempory";
private static final String RATING_CLASSIC="Classic";
private static int AGE_RECENT=1;
private static final int AGE_CLASSIC=20;
/**
* Constructor of the object, it has the Registration
* #param registration
* #param registrationYear - The year the vehicle was first registered.
* #param consumption - How many liters the vehicle consumes.
* #param autonomy - How many KMs a vehicle can go without refuelling.
* #param cilinderCapacity - How many Cubic Inches the engine has.
*/
public Vehicle(String registration,int registrationYear, double consumption, double autonomy, int cilinderCapacity) {
this.registration = registration;
this.registrationYear = registrationYear;
this.consumption = consumption;
this.autonomy = autonomy;
this.cilinderCapacity = cilinderCapacity;
}
/**
* Null Constructor, it has no values, they will be attributed in the MAIN Class.
*/
public Vehicle() {
this.registration = "";
this.registrationYear = 0;
this.consumption = 0;
this.autonomy = 0;
this.cilinderCapacity =0;
this.registrationYear = YEAR_OMISSION;
}
/**
* Copy Constructor.
*/
public Vehicle(Vehicle vehicle) {
this.registration = vehicle.getRegistration();
this.registrationYear = vehicle.getRegistrationYear();
this.consumption = vehicle.getConsumption();
this.autonomy = vehicle.getAutonomy();
this.cilinderCapacity = vehicle.getCilinderCapacity();
}
public String getRegistration() {
return registration;
}
public int getRegistrationYear() {
return registrationYear;
}
public double getConsumption() {
return consumption;
}
public double getAutonomy() {
return autonomy;
}
public int getCilinderCapacity() {
return cilinderCapacity;
}
public double getYearRecent() {
return AGE_RECENT;
}
public double getAgeRecent(){
return AGE_RECENT;
}
public void setRegistration(String registration) {
this.registration = registration;
}
public void setRegistrationYear(int registrationYear) {
this.registrationYear = registrationYear;
}
public void setConsumption(double consumption) {
this.consumption = consumption;
}
public void setAutonomy(double autonomy) {
this.autonomy = autonomy;
}
public void setCilinderCapacity(int cilinderCapacity) {
this.cilinderCapacity = cilinderCapacity;
}
public void setAgeRecent() {
Vehicle.AGE_RECENT = 3;
}
/**
* Calculate the age of the vehicle to compare in the vehicleRating method
* #return The year, which is 2016 minus the year the vehicle was first registered.
*/
private int calculateAge(){
return YEAR_OMISSION-this.registrationYear;
}
/**
* Calculate the Circulation Tax.
* #return Returns the value of the Environmental Charge multiplied by the Cilinder Capacity of the vehicle.
*/
public double calculateCirculationTax(){
return ENVIRONMENTAL_CHARGE_OMISSION*cilinderCapacity;
}
/**
* Classify the vehicle based on the age.
* If the result given by the calculateAge method is minor than the AGE_RECENT variable(3), then it will
return "Recent"
* If the result is between Age_RECENT and AGE_CLASSIC(20), then it will say "Contemporary"
* If none of the IFs apply, it will return "Classic".
**/
public static String vehicleRating(Vehicle vehicle) {
if(vehicle.calculateAge() < Vehicle.AGE_RECENT) {
return Vehicle.RATING_RECENT; }
else if ((vehicle.calculateAge()>=Vehicle.AGE_RECENT)&&(vehicle.calculateAge()<=Vehicle.AGE_CLASSIC)){
return Vehicle.RATING_CONTEMPORY;}
else
return Vehicle.RATING_CLASSIC;
}
#Override
public String toString() {
return "Vehicle{" + "registration=" + registration + ", registrationYear=" + registrationYear + ", consumption=" + consumption + ", autonomy=" + autonomy + ", cilinderCapacity=" + cilinderCapacity + '}';
}
}
A setter that takes no arguments is simply a method, not a setter. In order to work as a setter a method must take a parameter that matches the type of the value being set - in your case, that would be int:
public static void setAgeRecent(int age) {
AGE_RECENT = age;
}
Note a few things here:
Since AGE_RECENT is static, setAgeRecent should be static
Since AGE_RECENT and setAgeRecent are static members of the same class Vehicle, you do not need to qualify AGE_RECENT with Vehicle
Now users of your class would be able to call your static setter as follows:
Vehicle.setAgeRecent(3);
A static varible, or class variable, may be used without the need to create an instance of that class. But its value may be changed freely at runtime.
A final variable is not a variable in a true sense, because it's value can't be changed at runtime.
Thus, you may have a set method for a static variable, but never to a final variable.
Forgive me if this is a stupid question, I've been doing iphone and android for a while now and recently I need to develop for the web.
I'm using parse.com to handle my server requests. According to their documentation, I can do a subclass like this.
//A complex subclass of Parse.Object
var Monster = Parse.Object.extend("Monster", {
// Instance methods
hasSuperHumanStrength: function () {
return this.get("strength") > 18;
},
// Instance properties go in an initialize method
initialize: function (attrs, options) {
this.sound = "Rawr"
}
}, {
// Class methods
spawn: function(strength) {
var monster = new Monster();
monster.set("strength", strength);
return monster;
}
});
var monster = Monster.spawn(200);
alert(monster.get('strength')); // Displays 200.
alert(monster.sound); // Displays Rawr.
Ultimately I'm trying to translate the following code from Java to JS.
/**
* #author XujieSong
*
*/
#ParseClassName("_User")
public class SHUser extends ParseUser {
/**
* SHUser is a subclass of ParseUser
* Class name _User
*/
/**
* Default constructor
*/
public SHUser() {
}
/**
* Create a SHUser object with known objectId
* This method only returns a SHUser without data
* #param userID the objectId of the SHUser
* #return user a reference to a SHUser
*/
public SHUser(String userId) {
this.setObjectId(userId);
}
/**
* Create a new SHUser with attributes
* #param userName
* #param password
* #param email
* #param displayName
* #param installation
* #param profileImage
* #return user a new user
*/
public SHUser(String userName, String password, String email, String displayName) {
this.setUsername(userName);
this.setPassword(password);
this.setEmail(email);
this.setDisplayName(displayName);
}
}
And this is what I have got so far,
var SHUser = Parse.Object.extend("_User", {
/**
* Instance properties go in an initialize method
* #param {userId}
* #return {[type]}
*/
SHUser: function () {
},
/**
* Instance properties go in an initialize method
* #param {userId}
* #return {[type]}
*/
SHUser: function (userId) {
this.id = userId;
},
/**
* Instance properties go in an initialize method
* #param {userName}
* #param {password}
* #param {email}
* #param {displayName}
* #return {[type]}
*/
SHUser: function (userName, password, email, displayName) {
this.setUsername(userName);
this.setPassword(password);
this.setEmail(email);
this.setDisplayName(displayName);
}
}, {
// Class methods
});
after
var user = new SHUser(userId);
window.alert(Shelf.seller.id);
I got undefined.
So here's the question. Is it possible to have a default constructor, then a few customized constructors like the way it is in Java? Is it a good practice to do so? Thank you.
After further digging in Backbone.js, I've found the answer.
Turns out there's no need for any additional coding.
var SHUser = Parse.Object.extend("_User", {
/**
* Instance properties go in an initialize method
*/
initialize: function (attr, options) {
},
}, {
// Class methods
});
It's a backbone.js model, so when initializing, just pass the parameters in and it would work.
var seller = new SHUser({"id": sellerId});
And that's it!
For more information please refer to backbonejs.org
I don't really know exactly how to word this but basically I need to get the child class instance of an Actor without assigning it (if that makes since?). Is this possible?
package org.game.world.entity.actor;
import java.util.HashMap;
import java.util.Map;
import org.game.world.entity.Entity;
import org.game.world.entity.actor.npc.NPC;
import org.game.world.entity.actor.player.Player;
import org.game.world.entity.actor.player.PlayerData;
public abstract class Actor extends Entity {
/**
* The type of Actor this Entity should be
* recognized as.
*/
private final ActorType actorType;
/**
* A map of ActionStates, not necessarily 'Attributes'.
*/
private final Map<ActionState, Boolean> actionState = new HashMap<ActionState, Boolean>();
/**
* Constructs a new Actor {#Entity}.
*/
public Actor(ActorType actorType) {
this.actorType = actorType;
actionState.putAll(ActionState.DEFAULT_ACTION_STATES);
}
/**
* Gets the status of a {#Actor} ActionSate.
* #param state The ActionState.
* #return The ActionState flag.
*/
public boolean getActionState(ActionState state) {
return actionState.get(state);
}
/**
* Sets a {#Actor} ActionState flag.
* #param state The ActionState.
* #param flag The flag true:false.
*/
public void setActionState(ActionState state, boolean flag) {
actionState.put(state, flag);
}
/**
* Resets all ActionState's for this Actor.
*/
public void setDefaultActionStates() {
actionState.putAll(ActionState.DEFAULT_ACTION_STATES);
}
/**
* Checks if this Actor is a specific ActorType (i.e NPC)
* #param actorType The ActorType
* #return
*/
public boolean isActorType(ActorType actorType) {
return this.actorType == actorType;
}
/**
* The type of Actor.
*/
public static enum ActorType {
PLAYER,
NPC
}
}
An Actor type.
package org.game.world.entity.actor.player;
import org.game.world.entity.Location;
import org.game.world.entity.actor.Actor;
import org.game.world.entity.actor.SkillLink;
/**
* This class represents a Player {#Actor} in the world.
*
* #author dillusion
*
*/
public class Player extends Actor {
/**
* This Player objects unique set of stored
* data.
*/
private final PlayerData playerData;
/**
* Creates a new Player object in the world.
* #param playerData The set of data unique to this Player.
*/
public Player(PlayerData playerData) {
super(ActorType.PLAYER);
this.playerData = playerData;
}
/**
* Gets the players name.
* #return The name.
*/
public String getName() {
return playerData.name;
}
/**
* Gets the players password.
* #return The password.
*/
public String getPassword() {
return playerData.password;
}
/**
* Gets the players permission level.
* #return The permission.
*/
public Permission getPermission() {
return playerData.permission;
}
/**
* Gets the players SkillLink instance.
* #return The SkillLink.
*/
public SkillLink getSkillLink() {
return playerData.skillLink;
}
#Override
public Location getLocation() {
return playerData.location;
}
#Override
public Location setLocation(Location location) {
return playerData.location = location;
}
}
But let's say I have multiple 'Actors'. I don't want to have to cast if I don't need to.
Sorry if I didn't explain this very well.
I dont know what are you questioning about here - so what i have figured out that you might want to do is to use Player as Actor right? Well that is possible by Java standard and inheritance
Actor temp=new Actor(){//implementing abstract methods if any}
Actor player=new Player(); //that is still fine as Actor is common superclas for player and actor
Player another=(Player)player; // thats just fine after typecasting
////but
another=player; // compile error, type mismatch
another=(Player)temp; // ClassCastException but no compilation error;
But still you can use different Actors and Players as Actors.
I'm testing CodePro Anlaytix (Eclipse plug-in) to check for code style in a project.
CPA tells me that "Variable has null value" for the variable "titleParam" and "descParam" in the setters.
Here's the class:
/**
* fdas fsda fsda fsa
* #version 1.0
*/
public class CodeProItem {
/**
* Field title.
*/
private String title;
/**
* Field desc.
*/
private String desc;
/**
* Method getTitle.
* #return String
*/
public String getTitle() {
return title;
}
/**
* Method setTitle.
* #param titleParam String
*/
public void setTitle(String titleParam) {
this.title = titleParam;
}
/**
* Method getDesc.
* #return String
*/
public String getDesc() {
return desc;
}
/**
* Method setDesc.
* #param descParam String
*/
public void setDesc(String descParam) {
this.desc = descParam;
}
}
Here's the summary of the rule (from CPA doc):
A variable that is guaranteed to have a null value and is used in an
expression may indicate that the programmer forgot to initialize
variable with its actual value.
The rule "Variable has null value" is activated and this is an example of code that would be caught by this rule (from CPA doc):
public boolean myMethod(String param)
{
String tmp = null;
if (tmp.equals(param)) {
return true;
} else {
return false;
}
}
I get the example, but why does it say that my parameters in the setters are null?
It seems like a bug for me. If it would say it might be null and should be checked, that is possible. But unless it is called with a known null value somewhere else (that is possible and often possible to find out statically), the error makes no sense. However, if the caller provides the issue, then simply the error marker is misplaced.
Generally, I use FindBugs - that is optimized not to give false warnings, but works quite nice in my experience.