What are the possible ways to store this data? - java

Well, I need this data to be used in at least two classes:
String navHome = "home";
String navAbout = "about";
String navUpload = "upload";
String navUploadProc = "uploadProc";
String navStartUpload = "startUpload";
String navContact = "contact";
String navSearch = "search";
String navManual = "manual";
String navBackToGmis = "backToGmis";
I was thinking of just pasting that into other classes, but then it violates the principles of programming, since it's repeating the same thing. Text and XML files are not comfortable to store data, inheritance isn't an option, since Java doesn't support multiple inheritance... Any ideas?
Yeah, I know it will sound retarded to most of you, but I need tipps on this.

If these are constants, then you can declare them in one class (or interface) and use them in another:
A.java:
public class A {
public static final String navHome = "home";
public static final String navAbout = "about";
public static final String navUpload = "upload";
public static final String navUploadProc = "uploadProc";
public static final String navStartUpload = "startUpload";
public static final String navContact = "contact";
public static final String navSearch = "search";
public static final String navManual = "manual";
public static final String navBackToGmis = "backToGmis";
. . .
}
B.java:
import static A.*; // or list each String in a separate import
public class B {
. . . // code can use nav* as if they were declared in class B
}

Related

How to use variable of method from 1 class in 2 class via Java?

public static class One {
#Override
public String interact(String... values) {
String actualTextOne = "test";
return actualTextOne;
}
}
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
/* Here I need to compare actualTextOne and actualTextTwo, but the problem is that I can't find solluction how to use actualTextOne in Two class*/
return actualTextTwo;
}
}
You cannot do that.
Please check variable scope in java.
https://www.codecademy.com/articles/variable-scope-in-java
A possible solution here is to call the method interact from the class One. Something like this
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
One one = new One();
String actualTextOne = one.interact(values);
// compare values here
return actualTextTwo;
}
}
Why in your classes functions have parameters if you dont use it?
You can mark your class with static only if he is nested, else you need do like this:
class Two {
static public String interact(String... values) {
String actualTextTwo = "test";
return actualTextTwo;
}
}
String textOne = One.interact("");
String textTwo = Two.interact("");
System.out.println(textOne==textTwo);

Multiple constants in same class

I want to know what is the best way to use final constants in the same class? since i have to use a lot for the same class and looks very meshy, thanks.
How i can make it look more readable, since if I need to store more variables there will be many........... thanks
public class Default {
private static final String CLASS_FILE_EXTENSION = ".class";
private static final String JAVA_PACKAGE = "java.";
private static final String NO_PREFIX = "";
private static final String SUFFIX = "sfx";
private static final String TEMP_SUFFIX = "tmp";
private static final String NO_PARAMETERS = "()";
private static final String STRING_DESCRIPTOR = "Ljava/lang/String;";
private static final String RETURNS_VOID = "V";
private static final String JAR = "jar";
private static final int ONLY = 0;
private static final int BUFFER_SIZE = 1024;
private static final int PACKAGE_LOOKUP = 0x8;
private static final int BASE_VERSION = 44;
private static final Class<?> NOT_FOUND = null;
private static final URL NOT_SEALED = null;
private final TypeDescription instrumentedType;
private final TypeAttributeAppender typeAttributeAppender;
private final AsmVisitorWrapper asmVisitorWrapper;
private final ClassFileVersion classFileVersion;
private final AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy;
private final AnnotationValueFilter.Factory annotationValueFilterFactory;
private final AnnotationRetention annotationRetention;
private final Implementation.Context.Factory implementationContextFactory;
private final MethodGraph.Compiler methodGraphCompiler;
private final TypeValidation typeValidation;
private final ClassWriterStrategy classWriterStrategy;
private final LatentMatcher<? super MethodDescription> ignoredMethods;
private final List<DynamicType> auxiliaryTypes;
private final ClassFileLocator classFileLocator;
public Default(..... etc)
There is no objective answer possible for this. A few points to consider:
Having a lot of constants in one class might mean that the class is doing a lot of work. See if you can split the class into multiple classes and declare the constants as per the usage within those classes.
Since all these are private fields, see if they are really being used more than once in the same class. If not you can directly use the string rather than having a constant for that. The downside is, in the future, if you want to use it again in the same class at a different place, you have to remember to make it a constant (which is very easy to forget).
(I don't prefer this) I have seen cases where people will have an interface just for holding constants and static import them into the class to use it. That interface is like a big dumping ground for the constants.

Using an argument as an interface item

In the program I am making, I am trying to get a formatted season name for a given season(formatted so it . I keep the formatted names in an interface, since if I were to use a map, it would be unnecessarily regenerated, since I don't make an instance of TeamBuilder
The Seasons interface:
public interface Seasons {
/*
* Contains a formatted list of seasons.
*
* An interface is being used as an alternative to using a Map in the
* TeamBuilder class, since calling parseTeam would have to build
* mappings for the seasons each time it
* was called. This way, the formatted name can simply be grabbed
*/
final String Skyrise = "Skyrise";
final String Toss_Up = "Toss%20Up";
final String Sack_Attack = "Sack%20Attack";
final String GateWay = "Gateway";
final String Round_Up = "Round%20Up";
final String Clean_Sweep = "Clean%20Sweep";
final String Elevation = "Elevation";
final String Bridge_Battle = "Bridge%20Battle";
final String Nothing_But_Net = "Nothing%20But%20Net";
final String Starstruck = "Starstruck";
final String In_The_Zone = "In%20The%20Zone";
final String Turning_Point = "Turning%20Point";
}
The problem comes when I try to grab these seasons. My TeamBuilder class takes in an argument(String season), which is unformatted. My question is, is there any way that I can use a String argument for a method to get a specific item from an interface? This is the most preferable to using a HashMap, which would needlessly regenerate the same information
All these classes can be found on the Github page for this project.
If you want to do it in a typed way, you can use Enum for this:
enum Season{
Skyrise,Toss_Up, Sack_Attack;
#Override
public String toString() {
switch(this){
case Skyrise: return "Skyrise";
case Toss_Up: return "Toss%20Up";
case Sack_Attack: return "Sack_Attack";
default: return "";
}
}
}
public class main{
public static void printSeason(Seasons seasons){
System.out.println(seasons);
}
public static void main(String[] args) {
Seasons e = Seasons.Skyrise;
printSeason(e);
System.out.println(e);
}
}
Since the compiler internally invokes the toString(), you can pass the argument as a Seasons or a String like my example.
And if you still want to use a map without "unnecessarily regenerated" you can use a static field with static initializer like this:
class Seasons {
private static Map<String,String> map = new HashMap<>();
static {
map.put("Skyrise", "Skyrise");
map.put("Toss_Up", "Toss%20Up");
}
public static String getFormatted(String key){
return map.getOrDefault(key,"");
}
}
class main{
public static void main(String[] args) {
System.out.println(Seasons.getFormatted("Skyrise"));
}
}
Just to integrate on Snoob answer you can have enum with fields, so:
enum Season
{
Skyrise("Skyrise"),
Toss_Up("Toss%20Up"),
Sack_Attack("Sack%20Attack")
;
public final String fancyName;
private Season(String fancyName)
{
this.fancyName = fancyName;
}
}
You really have all the benefits without any drawback.

Correct way to use static parameters in Android

I am pretty new in Android and I do not know how is the proper way to manage static constants. I mean, I need to use several constants (such as COMMAND_BACK = 100) in several Java classes and activities. It is not beautiful to declare them as attributes in each single activity so, what is the correct way to do this?
I though about declaring them in strings.xml, but it does not seem suitable neither...
Thanks in advance.
You can make a class like this :
public final class AppConstants {
//put all the constant here
// Eg :
public static final int SPLASH_TIME = 1000;
}
The disadvantage by declaring it in a resource.xml file is that you need a context to receive the value. This is fine as long as you need those values inside a context class otherwise you have to pass one around.
The elegant solution would be extending the Application class since the android os itself uses static fields that way.
Declare
public final class ConstantClass {
public final static int COMMAND_BACK = 100;
}
Usage
int num = ConstantClass.COMMAND_BACK;
Add a Constants class to the project
public class Constants {
public static final String STRING1 = "First String";
public static final String STRING2 = "Second String";
public static final int INTEGER1 = 1;
public static final float FLOAT1 = 0.1f;
}
// Use
textView.setText(Constants.STRING1);
Create a common interface where you can declare all the constants.Constants can further be grouped here to make it mode clean.
public interface Constants {
public interface XYZ{
public static final int A= 1;
public static final int B= 2;
}
public interface REPORT_TYPE_FLAGS{
public static final String C= "0";
public static final String D= "1";
}
}
Another elegant way is to define a constant class with other inner subclasses
`private final class Constant {
public static class TypeOne {
public static final String NAME = "Type 1";
public static final int CODE = 1;
}
public static class TypeTwo {
public static final String NAME = "Type 2";
public static final int CODE = 2;
}
}
`
And you can access it in this way
`String typeOneName = Constant.TypeOne.NAME;
int typeTwoCode = Constant.TypeTwo.CODE;
`

some problems on declaring and calling of fields in java

I'm trying to access some fields from some class, but i face trouble when i want to call them.
This is the class which i have declared the fields :
public class InfoOfFriends {
public static final String Friends_List = "friends_list";
public static final String userName = "username";
public static final String STATUS = "status";
public static final String PORT = "port";
public static final String Ip = "Ip";
public static final String UserKey = "userKey";
public static final String Message = "message";
}
And this is where i want to use them :
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException
{
if (localName == "friend")
{
InfoOfFriends friend = new InfoOfFriends();
friend.username = attributes.getValue(InfoOfFriends.userName);
String status = attributes.getValue(InfoOfFriends.STATUS);
friend.port = attributes.getValue(InfoOfFriends.PORT);
if (status != null && status.equals("online")) {
friend.status = InfoStatus.ONLINE;
mOnlineFriends.add(friend);
} else if (status.equals("unApproved")) {
friend.status = InfoStatus.UNAPPROVED;
mUnApprovedFriends.add(friend);
} else {
friend.status = InfoStatus.OFFLINE;
mOnlineFriends.add(friend);
}
}
else if (localName == "user")
{
this.userKey = attributes.getValue(InfoOfFriends.UserKey);
}
super.startElement(uri ,localName, name, (org.xml.sax.Attributes) attributes);
}
These parts have errors :
friend.username = attributes.getValue(InfoOfFriends.userName);
friend.port = attributes.getValue(InfoOfFriends.PORT);
friend.status = InfoStatus.ONLINE;
friend.status = InfoStatus.UNAPPROVED;
friend.status = InfoStatus.OFFLINE;
Thanks for your time friends...
first of all are you sure that attributes has the correct values?
and remember to use as string comparator the equals() method
if (localName.equals("friend"))
instead of
if (localName == "friend")
You can't assign new values to final fields. Remove the final keyword to resolve the error.
Also you made all of the fields static and use them as keys to retrieve stuff from Attributes, but at the same time you want to assign new values to them - probably a bad idea. Try doing a separate class with final static keys to use for the Attributes retrieving, and a separate Friend class to assign the retrieved values to.

Categories

Resources