Sorry for my bad English and for maybe stupid question but I'm new in Java.
I need use same string in 2 java files for example:
In first java file I've got code for sending emails, I've got string set to default email:
public String mail = new String ("lala#gmail.com");
and I use this string in code for send email:
email.addTo(mail);
In second java file something like set up where can user set new email address I want to have same string, connected with string in first java file. When user put new email String mail will be change to new email address and in email.addTo(mail); will be use this new address
How can I do this?
use Shared Preferences, you can store it as key-value Pair. value being your email and key can be any unique string which you want to identify it with.
I'm a bit confused with the question, but I'll take a stab at it. Basically, you would like to have one String in a given file be used in multiple locations. This is easily done using class-level variables and making them publicly accessible.
For example, in the file:
EmailObject.java
public class EmailObject {
public static final String mail = "lala#gmail.com";
// The rest of your code
}
Another file can access this like so:
OtherObject.java
public void sendEmail() {
EmailMessage email = new EmailMessage();
email.addTo(EmailObject.mail);
}
Note the static and final modifiers on the original. This ensures that you do not need an actual instance of EmailObject to access the string and it also ensures that the string is never modified accidentally by some other object.
There are, of course, other ways to do this, but this one matches your code the most. This is also a very "Java" solution. Android has other ways to share data (as indicated by the other answer).
The simplest way that I would not recommend is to have a public static field:
class A {
public static String commonString;
}
class B {
public void methodThatUsesString () {
// Do stuff with the string
Log.d("I have the string", A.commonString);
}
}
If you have two Activities, and one starts another, you can send data through Intents.
The forementioned SharedPreferences way is a good solution too, if the email address is a persistent thing, a preference if you will, and not just data reqired for an operation.
You can keep a reference of one instance of a class in the otherone, and access it's fields through it:
class A {
public String commonString;
}
class B {
private final A instaceOfA;
public B (A instanceOfA) {
this.instanceOfA = instanceOfA;
}
public void methodThatUsesString () {
// Do stuff with the string
Log.d("I have the string", instanceOfA.commonString);
}
}
Or even use a getter or setter if performance is not an issue.
Many answers depending on how the string will be used.
If it's a constant string, one that will never change, never use final static String
public final static String AUTHOR_MAIL = "lala#gmail.com";
Then you can use it in a static way wherever you want.
email.addTo(MyClass.AUTHOR_MAIL);
If this String will be used in different Activities you can not access it directly (you can not tell if the other Activity is still alive). You have to use Persistence Mechanisms such as SharedPreferences or directly send needed data in your Intent.
If it's in a helper class inside your Activity, you can just use mObject.mail to get it.
Related
I have an old doubt about constants in Java Projects maintenance. From my perspective, when we try putting the constants inside an Abstract class like that:
public final class MyConstants {
public static final String CONSTANT1 = "const1";
public static final String CONSTANT2 = "const2";
public static final String CONSTANT3 = "const3";
public static final String CONSTANT4 = "const4";
}
after that using those constants inside classes in the project:
public void myMethod(final Map params) {
final String myparam = (String) params.get(MyConstants.CONSTANT1);
//DO SOMETHING WITH PARAMS
}
It leads to boiler plate code, verbose use of constants and no real advances. In other hand if we put those constants inside the class for somehow people don't like it. They say "what about we have the same constant declare somewhere?" the problem is maintainance issues, if we change those constants in that class the change can be visible on several parts without any big problem.
Those constants are mainly used for mapping webservices for java perspective without having to generating POJOs like JAXB based on WSDL, the webservices operations are mapped directly for key value maps in Java.
I want to know what do you think about this approach and if we have any other choice.
Thank you.
If I understand your concern, don't hardcode those constants as values except perhaps as defaults and store them with Properties and/or ResourceBundle(s). You might also read the Java Tutorial on Properties. Something like,
Properties props = new Properties();
FileInputStream in = new FileInputStream("my.proprties");
props.load(in);
String v = props.get("CONSTANT_ONE", "const1"); // <-- the "1" is a default.
Then if you need to change the property later you only have to modify the properties file.
I'm trying to make an array of objects called Verbs.
The Verb class has 4 Strings.
public class Verb {
String maori;
String englishPast;
String englishPresent;
String englishFuture;
}
Do I need to write get and set methods into this class in order to change these values or does android handle it for you somehow?
This seems to not be an Android problem but a java related question. You should create a Verb class like this:
public class Verb {
private String maori;
//All other strings you need
public String getMaori() {
return maori;
}
//Add a setter as well
Then you should create your Verb objects and add these objects to your array. But this has nothing to do with Android at all!
I'm developing a Android-application using StackMob. Now I'm at the point that I want to save an object but not all his properties let's take this example.
class A extends StackMobModel
{
String UserOneInput;
String UserTwoInput;
}
Now I have two people using one instance of class A at the same time. User one puts his information in UserOneInput and user two in UserTwoInput. Now if user one saves hits information while user two already has fetched this object the situation would be
class A extends StackMobModel
{
String UserOneInput = "User one his input";
String UserTwoInput = null;
}
For user one while user two has
class A extends StackMobModel
{
String UserOneInput = null;
String UserTwoInput = null;
}
Now if player two saves his data it's saved as it is in his situation so we get
class A extends StackMobModel
{
String UserOneInput = null;
String UserTwoInput = "User two input";
}
User one his input is overwritten. I can fetch the object again before saving but if you use it on mobile networks the latency can still cause the same problem. (User two saves his information between the time that use one does a fetch and save)
I looked into the javadoc and only found a function that you can use to select certain fields but it says that won't work for saving.
Is there such an method for saving only certain fields of a class? Or is there some different model I should use to prevent overwriting?
The class does not know who is the owner, in order to know which one String to save.
This class must be decomposed to
class Answer {
String answer;
....
}
and
class Question {
Answer userOne;
Answer userTwo;
....
}
Each user has access to and saves his own Answer and the Question knows the Answers of the users.
I have a class called Info, and i have a bunch of static String variables described in it.
public class Info{
public static stringOne= "Hello";
public static stringTwo = "world";
}
and i'm hoping to access these variables as Info.stringTwo from other classes.
1.) I need to know if this is java-Internationalization that i have applied here ? (I have all the messages that i will display in the application assigned in this class. And, i am hoping to have different languages support to the app as well)
Have a look at Resource bundle
A copy paste from the documentation:
When your program needs a locale-specific object, it loads the ResourceBundle class using the getBundle method:
ResourceBundle myResources =
ResourceBundle.getBundle("MyResources", currentLocale);
Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle.
Here's an example of a ListResourceBundle that contains two key/value pairs:
public class MyResources extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] {
// LOCALIZE THE SECOND STRING OF EACH ARRAY (e.g., "OK")
{"OkKey", "OK"},
{"CancelKey", "Cancel"},
// END OF MATERIAL TO LOCALIZE
};
}
}
Keys are always Strings. In this example, the keys are "OkKey" and "CancelKey". In the above example, the values are also Strings--"OK" and "Cancel"--but they don't have to be. The values can be any type of object.
You retrieve an object from resource bundle using the appropriate getter method. Because "OkKey" and "CancelKey" are both strings, you would use getString to retrieve them:
button1 = new Button(myResources.getString("OkKey"));
button2 = new Button(myResources.getString("CancelKey"));
Here is an example from here:-
import java.util.*;
public class InternationalizationDemo {
public static void main(String[] args) {
String language;
String country;
Locale locale;
ResourceBundle rb;
if (args.length != 2) {
language = new String("en");
country = new String("US");
}
else {
language = new String(args[0]);
country = new String(args[1]);
}
locale = new Locale(language, country);
rb = ResourceBundle.getBundle("MessagesBundle", locale);
System.out.println(rb.getString("localeInfo") + " ( " +
locale.getDisplayLanguage() + "," + locale.getDisplayCountry() + ").\n");
System.out.println(rb.getString("welcome"));
System.out.println(rb.getString("sayThanks"));
}
}
Though using a ResourceBundle is the traditional and most well-known approach to internationalization in Java, it is possible to make internationalization data available as class members, somewhat similar to the way you seek.
You can further put your strings for some message in different languages in a Map, indexed by language. And make this Map a static member of some class. Thus you get the ability to reference these string collections for messages by their class member names in a compiler-checked manner. And next, if you have a way to select preferred user language at run time (you have to have it), you just pick the right string from an appropriate collection using its language key, boiling down to something like this:
logger.info (MyClassWithMessages.MY_MULTILANGUAGE_MESSAGE.s ());
And the s() method to be added to your Map subclass can be made resposible for dealing with user preferences and selection from Map by language key.
That said, the remaining task is just to formulate a convenient API for all this... You are welcome to have a look at such an implementation on my blog page Look Ma, no ResourceBundle :) ..., and the next page that goes ahead with message formatting arguments.
For internationalization of Java and other applications I implemented a Message Compiler, which creates the resource bundle files and constant definitions as Java enum or static final strings for the keys from one single source file. So the constants can be used in the Java source code, which is a much safer way than using plain string constants. The message compiler cannot only be used for Java. It creates also resource files and constants for Objective-C or Swift and can be extended for other programming environments.
Let me start by confessing that I come from an Erlang background and am new to Android and Java programming... to be honest object orientation is giving me a headache. :)
I am having some trouble with the sticky old chestnut: "Cannot make a static reference to the non-static method".
Basically I am writing an app that receives XML from our server and uses it to create a form to be filled in by the user.
I have managed to successfully parse the XML and create (and display) the form. I assign each EditText field it's own ID using a (very) simple algorithm that I can recreate later.
I am busy with the submit button, which makes a HTTP post back to our server with the user entered details.
My problem comes in when I try to retrieve the values that the user has entered into the form.
What I am attempting to do is loop through my IDs, open each EditText instance using EditText.findViewById(ID) and retrieve its text using getText().
When i do so however I receive the error "Cannot make a static reference to the non-static method".
Now I've done some reading and the way I understand it is that this is because I am trying access a a non-static method in a static way and in order to make it static I need to call the method of an instance rather than the class in general... the problem is that I am calling it IN ORDER to get that particular instance and I can't figure out what I should be doing differently.
I would really appreciate any help, advice or further reading that anyone has for me.
Cheers,
Bevan
p.s. Here are the relevant sections of my code
private static LinearLayout renderForm(...)
{
//Build Fields
...
//Build Buttons
...
Button BT = new Button(App);
BT.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
...
for(int j = 0; j < FFListLength; j++)
{
EditText BinField = (EditText) EditText.findViewById(20000+j);
...
}
...
}
}
}
Update:
After reading JB Nizet's answer I realized what I was doing wrong.
I have changed the line:
EditText BinField = (EditText) EditText.findViewById(20000+j);
to:
EditText binField = (EditText) lContent.findViewById(20000+j);
where lContent is the content of my view.
Thanks for the assistance.
Bevan
I'm not going to comment on the Android specific problems. Only on the general compilation error you're getting. Let's take an example:
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
To be able to call the getName() method, you need an instance of User:
User john = new User("John");
String johnsName = john.getName();
What you're doing is calling the getName() method without any instance of User:
String someName = User.getName();
This doesn't make sense. You don't have any user. Only the User class.
As noted in my comment; variables should start with a lower-case letter. Classes start with an upper-case letter. If you respect this convention, everything is clearer:
john.getName(); // instance method call on object john, of type User.
User.getName(); // static method call on User class.