getting strings from other classes - java

hi guys im writing a method that contains a string name from other classes..
i use the String apkName and mcurrentPhotoPath in alot of activites but need to pass the value of them string into my download method.
ive tried this
public static class Stringz{
public String APK() {
return apkNames;
}
public String FILEPATH() {
return mCurrentPhotoPath;
}
}
then in my download method i use
Stringz st = new Stringz();
String apkNames = st.APK();
String mCurrentPhotoPath = st.FILEPATH();
which works fine for a single activity. but because i have multiple activites using the same string names how can i write it so my method know which string to look for in every activity
thanks guys

You need one of these two:
1) An instance of Stringz
2) A static reference to the Strings you want to access
A static reference you define as:
public static String yourString = "Some string";
And instance:
public Stringz reference = new Stringz();
//and access like:
reference.yourString;

Related

Convert instanced object to string

I initialize a Password object and I am having trouble using the same object as a string for later purposes like counting the amount of letters in the string. I know that I'm only getting the textual representation of the object with the methods String.valueOf and .toString. How do I go about taking the my object pass and getting the "hello" string I initialized it with?
public class Password {
public Password (String text) {
}
public String getText(){
String string = String.valueOf(this);
return string;
}
public static void main (String[] args) {
Password pass = new Password ("hello");
System.out.println(pass.toString());
}
}
Your actual getText() method doesn't make sense :
public String getText(){
String string = String.valueOf(this);
return string;
}
You try to recreate a String from the toString() method of the Password instance.
It is really not necessary (useless computation) and it is clumsy as toString() is not designed to provide a functional data.
To reach your goal, it is very basic.
Store the text in a field of the Password instance :
public Password (String text) {
this.text = text;
}
And provide a view on the text field.
You could replace getText() in this way :
public String getText(){
return text;
}
Use fields.
public class Password {
private String text; // This is a member (field) It belongs to each
// Password instance you create.
public Password(String value) {
this.text = value; // Copy the reference to the text to the field
// 'text'
}
}
The problem with String.valueOf(this), where this is a Password instance, is that the valueOf() method has absolutely no idea of how to convert a Password instance to a field. You named it "Password", but it could also beMyTextorMySecret. So you need to tell how aPasswordinstance can be displayed as text. In your case, you'll need to just use thetext` field from the abovementioned example.
You should definitely read the docs about classes. I think you're missing something basic.
Note: You should also never store a password into a String, because of security implications, but that's a whole other story, and beyond the scope of your question.

NullPointerException when creating new String

SOLUTION
I was adding a new instance of A to the list: aList.add( new A() ), whose name property is of course null, instead of adding the actual initialized instance. Sorry for the dumb question.
I have this A class of ProjectA which overrides its toString method to return a clone of its name property, like this:
public class A {
private String name;
#Override
public String toString() {
return new String(name);
}
}
I then export this library to a jar and import it into ProjectB and when I call a.toString() I get a NullPointerException that says there is an error exactly on the return line: return new String(name);.
However, if I put it like this:
public class A {
private String name;
#Override
public String toString() {
return name;
}
}
I don't get any exception but the String returned is null.
I built the jar (ProjectA) using Eclipse and imported it into ADT (ProjectB - Eclipse too).
NOTE:
I omitted the getters/setters intentionally for the sake of simplicity, but they're in there in the original code and I'm pretty sure I set the name property way before calling the toString() method. In fact, if I call the getName() method, the name is returned perfectly fine, but I'm using lists and I need the toString() method.
This is the part of the code where the List of A objects is created (ProjectA too):
ArrayList<A> aList = new ArrayList<Categoria>();
for (int i = 0; i < random.nextInt(3)+1; i++) {
A a = new A();
a.setId(0);
a.setName("Test name");
a.setDescription("Test desc.");
aList.add(a);
Log.d("app", "Created object A: "+a.getName()); // The name is displayed OK here
}
aList.trimToSize();
And this is the exact part of the code where the toString() method is called (ProjectA):
new ArrayAdapter<A>(
actionBar.getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
DataAccess.getAList() // The ArrayAdapter class calls the toString method to populate a list
)
As you could see, I in fact verify the content of the name property via the getName() method and it is okay. I have to mention that the first approach (the on which uses new String(name), without an finals nor null checks) worked flawlessly on another project.
This is the (relevant part of the) DataAccess class:
public final class DataAccess {
private static final Data data;
public static Arrayist<A> getAList() {
return this.data.getAList();
}
}
When you invoke new String(name); it invokes the overloaded parameterized constructor of String shown below :
public String(String original) {
int size = original.count;
........
.........
}
As you can see the first line in the code tries to compute the length of the String passed to the constructor. Since in your case the String is null invoking the member variable count on that null reference throws NullPointerException.
Note : In the code where you create AList, i dont see you adding the object to the list i.e. AList.add(a); is missing
return new String(name);
Would fail on name being null. It could happen on A a = new A(); System.out.println(a):.
The used constructor String(String) is a relict of the beginning of Java, reminiscent of the C++ copy constructor.
In Java String is immutable, and Java does not need the copy constructor.
Two solutions:
return String.valueOf(name); // Would return "null" for null.
return name == null ? "" : name;
As far as the exception goes you are getting a null pointer as already explained by #Kakarot.
This line blows up
original.count
But if you want to save yourself from null checking etc and at the same time have a efficient toString() method than user some thing like this.
public class A {
private String name = null;
private String address = " Some place";
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
return sb.append(name).append(address).toString();
}
}
Using string builder is efficient and you can see the output for the above toString() even with null values.
null Some place
In java new String(null) results into NullPointerException.
#Override
public String toString() {
if(name!=null){
return name;
}else{
return "";
}
}

Saving variables on android til the app closes

I have a basic understanding of java and android but am still new and am struggling to find the correct way to save a variable and be able to access it/read it from other classes/activities. I have seen singletons but I am confused if it is the right way and how it would look, also do I need to make sure its thread safe?
Is there a better way that I am unaware of?
Basically I have a login that gets a username and some info about that user. How can I save that to a class/singleton and access it later?
EDIT
after some more searching I found this example:
public class Drivers {
private static Array drivers;
public static void setDrivers(Array c){
drivers = c;
}
public static Array getDrivers(){
return drivers;
}
}
and get and set like this:
public class AnyClass {
{
int clicks = ActionClass.getDrivers();
ActionClass.setDrivers(0);
}
Would this work/be correct?
Create a Constant Class like :
public class Constant {
public static String USERNAME = "";
public static String PASSWORD = "";
}
Now, you can set this value in Activity1 like
Constant.USERNAME = "uname";
Constant.PASSWORD= "password";
Now, get this value in Activity2 like:
String u_name = Constant.USERNAME;
String pass = Constant.PASSWORD;
You can access this variables any where in your app.
And/or for Preference go to my this answer:Android. How to save user name and password after the app is closed?
You could use SharedPreferences (kind of a persistence layer). Or you could pass data through Intent.
You can use sharedPreferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("PASSWORD_KEY", mPassword);
editor.commit();
String s = sharedPreferences.getString("PASSWORD_KEY", ""); // get the saved string

How to get a preference value into a static String variable?

I am getting the following error message:
"Cannot make a static reference to the non-static method
getPreferences(int) from the type Activity" is the error in my case.
'TimeCardLogin' must be a static variable."
How do I get a preference into a static String variable?
public class MyBaseURLContainer extends Activity {
public static String urlPref = "";
static String BASE_URL =
getPreferences(MODE_PRIVATE).getString("Name of variable",urlPref);
public static final String TimeCardLogin = BASE_URL + "/timecard";
}
I'd recommend making a static getter that takes an Context as an argument. That way a) it will actually compile, and b) if your base-url changes at some point, it will load the most recent value, instead of loading once in the beginning like your program is:
private final static String PREFS = "myUrlPrefs";
public static String getBaseUrl(Context context) {
return context.getSharedPreferences(PREFS, MODE_PRIVATE).getString(
"Name of variable",urlPref);
}
You'd call it from another activity like this:
String baseUrl = MyBaseUrlContainer.getBaseUrl(this);
Or from anywhere you have access to a Context like this (an Activity is a Context):
String baseUrl = MyBaseUrlContainer.getBaseUrl(myContext);
If you absolutely have to use this code from somewhere that doesn't have access to a Context (which really should almost never be the case in an Android app), you could store the value after it's retrieved, but the first time you get the value it has to be from a Context.

Javassist - redirect field access to methods (doesn't work)

I have the following Class
public class Booking{
public String name;
public String comment;
public String session;
public void test(){
this.name = "hi";
}
}
I instrument it using the following:
cc.instrument(new ExprEditor(){
public void edit(FieldAccess arg) throws CannotCompileException {
if (arg.isWriter()) {
StringBuffer code = new StringBuffer();
code.append("$0.");
code.append(arg.getFieldName());
code.append("=$1.toUpperCase();");
arg.replace(code.toString());
}
}
});
Now when I call this:
Booking b = new Booking();
b.name = "hello";
System.out.println(b.name); // Edited correction
b.test();
System.out.println(b.name);
Gives me
hello // Externally, doesn't.
HI // Internally, works as expected
What am I missing? It just seems like one of those things I should be able to accomplish easily.
Please don't tell me I have to do a blanket "fieldAccess.replace" on all classes? O.O
Your example code fragment that contains the statement b.name = "hello"; isn't being instrumented, hence the value it writes is not converted to uppercase. An ExprEditor can only transform the field access from classes that are instrumented by it. If you want every write to the 'name' field converted to uppercase, you will have to instrument every class that contains a write statement for that field.

Categories