can anyone guide me to the right direction, as the situation is
have two classes calssA with Activity while classB is simple java class
1.classA has a editbox where the user inputs some value.
2.classB has a method that computes the user input.
need to get the user input value from classA to classB.
a).cannot get it through passing intent as the other class does not have activity.
b).have tried getter setter method by creating a class thus,calling setter where the user inputs the detail.
and calling the getter in another class.
Still the value is null, so what apparently is missing here.Any guidance to a example or brief explanation would be great.Thanks
You can use your own customized class to store the data and use it any where you need.
DataClass
public class Data {
private String a,b;
private static Data data= new Data( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Data (){ }
/* Static 'instance' method */
public static Data getInstance( ) {
return data;
}
public String getA()
{
return this.a;
}
public String getB()
{
return this.b;
}
public void setA(String a)
{
this.a = a;
}
public String getB(String b)
{
this.b = b;
}
}
In Activity
Data data = Data.getInstance()
data.setA("Stack");
data.setA("Overflow");
you can use this values in Java file like this
Data data = Data.getInstance()
System.out.println(data.getA());
System.out.println(data.getB());
according to my knowledge here you have to use singleton class.
public class DataHolderClass {
private static DataHolderClass dataObject = null;
private DataHolderClass() {
// left blank intentionally
}
public static DataHolderClass getInstance() {
if (dataObject == null)
dataObject = new DataHolderClass();
return dataObject;
}
private String _ProductNames;
public String get_ProductNames() {
return _ProductNames;
}
public void set_ProductNames(String _ProductNames) {
this._ProductNames = _ProductNames;
}
}
to set data
DataHolderClass.DataHolderClass.set_ProductNames(your data variable);
to get data
DataHolderClass.DataHolderClass.get_ProductNames(your data variable);
You can save the edittext value in SharedPreferences, thus making it available in all activity.
By doing this you can fetch the value in other activity without any hassle.
eg:
SharedPreferences.Editor editor = preferences.edit();
editor.putString("edtTextValue", valueOfEditText);
editor.commit();
Further fetching the value in other activity like this,
preferences.getString("edtTextValue", "");
In your activity class create
public static String valueEntered;
valueEntered=mEdtTxt.getText().toString();
and in your java class where you want
String enteredValue=ClassA.valueEntered;
Related
I'm attempting to code an app that takes the users numerical specifications from the main activity in the form of a TextEdit input, convert that to an integer and then use that specific value of the integer and use that value in a separate class file which I will use the result of the class in the main activity.
Is this possible? Here's what I've attempted in the global variables of the main activity:
deadzoneValue = findViewById(R.id.TextView_deadzoneInfo);
public EditText threshold, deadzone;
public String deadzoneString = deadzone.getText().toString(); //deadzone being the name of the
public int timeLimit = Integer.parseInt(deadzoneString);
public String thresholdString = threshold.getText().toString();
public static int thresholdLimit = Integer.parseInt(thresholdString);
I'm not sure how to use these in the Deadzone class, which I'm trying to take the specific value and use there.
EDIT: Deadzone.java isn't an activity but a class with functions that are called in the MainActivity.
Using of ClassicSingleton:
public class ClassicSingleton2 {
private static String instance = null;
protected ClassicSingleton2() {
}
public static String getInstance() {
return instance;
}
public static void setInstance(String instance) {
ClassicSingleton2.instance = instance;
}
}
You could change type of instance variable to int ...
And in target code you could get this data:
xRef = ClassicSingleton2.getInstance();
This is very simple.
2:
And using of put (putExtra)
Intent oI = new Intent((FirstActivity)this,SecondActivity.class);
oI.putExtra("XRefCaller",123);
And in target code(activity) :
Bundle oBundle = getIntent().getExtras();
if(oBundle != null){
oXRefCaller = oBundle.getString("XRefCaller",-1);
//checking with -1 if the parameter does not exist or is null
}
Code A works well, I think Code B can work correctly, but in fact, Code B doesn't work correctly. Why?
Why can't I create an object in the function- private void SetField(Context mContext,MAtt aField,String name) ?
Code A
public class MURLPar {
public MAtt diskcount=new MAtt();
public MAtt diskindex=new MAtt();
public MURLPar(Context mContext){
SetField(mContext,diskcount,"Pardiskcount");
SetField(mContext,diskindex,"Pardiskindex");
}
public class MAtt {
public String name;
public String value;
}
private void SetField(Context mContext,MAtt aField,String name){
int id = mContext.getResources().getIdentifier(name, "string", mContext.getPackageName());
aField.name=mContext.getString(id);
}
}
Code B
public class MURLPar {
public MAtt diskcount;
public MAtt diskindex;
public MURLPar(Context mContext){
SetField(mContext,diskcount,"Pardiskcount");
SetField(mContext,diskindex,"Pardiskindex");
}
public class MAtt {
public String name;
public String value;
}
private void SetField(Context mContext,MAtt aField,String name){
aField=new MAtt(); //Create object
int id = mContext.getResources().getIdentifier(name, "string", mContext.getPackageName());
aField.name=mContext.getString(id);
}
}
Because aField gets new memory address when you use the command aField=new MAtt();
As a result memory address of diskcount and diskindex remain uninitialized.
For more check here: https://stackoverflow.com/a/73021/3923800
What's happening in code B is that the MURLPar constructor passes a reference to diskcount/diskindex to SetField, which within that method has the name aField.
You then reassign aField with a reference to a newly created object, and you then manipulate that object. Note that aField is now referring to a completely separate object, and not whatever it was referring to when you entered SetField.
If you're familiar with C you can think of what you're doing here as something along these lines:
void SetField(MAtt *aField) {
aField = (MAtt*) calloc(1, sizeof(MAtt));
}
MAtt *diskcount;
SetField(diskcount);
And then expecting diskcount to have changed after the call to SetField, which it obviously won't have.
If you want something like an out parameter, you can simulate that by returning a newly created object:
private MAtt SetField(Context mContext, String name){
MAtt aField = new MAtt(); //Create object
int id = mContext.getResources().getIdentifier(name, "string", mContext.getPackageName());
aField.name=mContext.getString(id);
return aField;
}
And then:
diskcount = SetField(mContext, "Pardiskcount");
Background info:
Sometimes you need to share a couple of global preferences in your android application and one option is to use the SharedPreferences to accomplish this;
//get the preferences
SharedPreferences prefs = myActivity().getSharedPreferences(“ConfigurationStore”, Context.MODE_PRIVATE);
//store a value
prefs.edit().putString(“user”, “Teddy”).commit();
//get the value
prefs.getString(“user”, null);
I like my code simple so I wrote a wrapper to hide the above, here is the result.
public enum ConfigurationStore {
USER(“user”);
private String key;
private SharedPreferences prefs = //get this from your activity class
ConfigurationStore(String key){
this.key = key;
}
public String get(){
return prefs.getString(key, null);
}
public void set(String value){
prefs.edit().putString(key, value).commit();
}
}
The usage of the wrapper is shown below
//Set a value:
ConfigurationStore.USER.set("Teddy");
//get a value
ConfigurationStore.USER.get()
It's easy to extend with new properties just by adding to the enum:
public enum ConfigurationStore {
USER(“user”),
DEPLOYMENT_TYPE(“deployment_type”);
....
//Set a value:
ConfigurationStore.DEPLOYMENT_TYPE.set("Beta-test");
//get a value
ConfigurationStore.DEPLOYMENT_TYPE.get()
The question:
The enum is strictly handing String properties.
Is there a way I can make this enum handle different types safely without adding other method signatures (getStringValue, getIntValue)?
I want to be able to do something like:
int age = 23;
String name = "Teddy"
ConfigurattionStore.AGE.set(age)
ConfigurattionStore.NAME.set(name)
...
age = ConfigurattionStore.AGE.get();
name = ConfigurattionStore.NAME.get();
No, not with this design.
To be able to do what you want, you would need to define a generic interface or class
public PrefHandler<T> {
T get();
void set(T);
}
And have multiple instances of this interface:
public class ConfigurationStore {
public static final PrefHandler<String> FOO = ...;
public static final PrefHandler<Integer> BAR = ...;
}
I have one class ApplicationDetails, with getter and setter methods.
public class ApplicationDetails {
String supportURL;
String companyURL;
String copyRightText;
// with getter and setter methods
}
I am setting all data in my splash screen activity.
ApplicationDetails appDetails = new ApplicationDetails();
String supportURL = getResources().getString(R.string.support_url);
appDetails.setSupportURL(supportURL);
For sample I just setting data from string file but in app its coming from different sources.
But when I tried to access data in different activity its returns null value.
e.g.
public class AboutViewController extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApplicationDetails appDetails = new ApplicationDetails();
System.out.println(" app support url " + appDetails.getSupportURL());
}
}
output
I/System.out(2242): app support url null
any help.
You get null, because you create a new object and all fields are initialized to zero.
In your case, I see these fields are going to be the same through application, so you can use a Singleton pattern and instantiate only one object for your application and refer to it later on. You don't need to create a new object each time you refer to it. It would be ok for this class and you can also make them constants. (I guess these variables won't change through execution)
As fast solution you can make your supportURL object static, but this isn't good solution.
public class ApplicationDetails {
static String supportURL;
static String companyURL;
static String copyRightText;
// with getter and setter methods
}
better solution is to pass strings from one activity to another with intents, when you are starting your AboutViewController Activity.
You can use the shared preference to store data to be used through your application.
Here the Context in the constructor is nothing but your Activity.
public class ApplicationDetails {
public static final String SUPPORT_URL = "support_url";
public static final String COMPANY_URL = "company_url";
public static final String COPYRIGHT_URL = "copyright_url";
String supportURL;
String companyURL;
String copyRightText;
private Context context;
public ApplicationDetails(Context context) {
super();
this.context = context;
}
private String getPreference(String key)
{
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, null);
}
private void setPreference(String key, String value)
{
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
}
public String getSupportURL() {
if(supportURL == null)
supportURL = getPreference(SUPPORT_URL);
return supportURL;
}
public void setSupportURL(String supportURL) {
this.supportURL = supportURL;
setPreference(SUPPORT_URL, supportURL);
}
public String getCompanyURL() {
if(supportURL == null)
supportURL = getPreference(COMPANY_URL);
return companyURL;
}
public void setCompanyURL(String companyURL) {
this.companyURL = companyURL;
setPreference(COMPANY_URL, companyURL);
}
public String getCopyRightText() {
if(copyRightText == null)
copyRightText = getPreference(COPYRIGHT_URL);
return copyRightText;
}
public void setCopyRightText(String copyRightText) {
this.copyRightText = copyRightText;
setPreference(COPYRIGHT_URL, copyRightText);
}
}
Thanks all for all suggestions. Now I am using only one instance of a class.
public class ApplicationDetails {
private static ApplicationDetails instance = null;
String supportURL;
String companyURL;
String copyRightText;
// with getter and setter methods
public static ApplicationDetails getInstance() {
if (instance == null) {
instance = new ApplicationDetails();
}
return instance;
}
}
And I am setting and getting like this
ApplicationDetails appDetails = ApplicationDetails.getInstance();
appDetails.setSupportURL(supportURL);
and in activity
ApplicationDetails appDetails = ApplicationDetails.getInstance();
appDetails.getSupportURL();
Its wrks fine.
Update
As you setting value in Splash screen that object in memory was different and in another activity you creating another object that also different in memory that's why you getting null.
If this was your requirement to init url in splash screen and used in another then there are many ways.
You directly get the string in your activity as you getting in splash screen.
In splash screen make appDetails object as public static so you can access in another activities also
Implement serialization on ApplicationDetails and put this object in putExtra as we put string,int etc value for passing data between activity and get this data using bundle in started activity
Edited
For using single object you need make that object declare as public static in splash screen
public static ApplicationDetails appDetails;
now assign value in splash screen oncreate() and used in another activity or even another class also like this way
public class AboutViewController extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// direct use object by class name
System.out.println(" app support url " + SplashScreen.appDetails.getSupportURL());
}
}
I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
public final class Connection {
public static final Connection EMAIL = new Connection("email");
public static final Connection PHONE = new Connection("phone");
public static final Connection FAX = new Connection("fax");
/**/
private final String unmodifiableName; //<-- it's final
private String modifiableName;
/*
* The constructor is private so no new connections can be created outside.
*/
private Connection(String name) {
this.unmodifiableName = name;
}
public String getUnmodifiableName() {
return unmodifiableName;
}
public String getModifiableName() {
return modifiableName;
}
public void setModifiableName(String modifiableName) {
this.modifiableName = modifiableName;
}
}
The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as final, and use the constructor to initialize all of them.
For reference, the following code works as expected:
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.get()); // prints "null"
MyEnum.valueA.set(new Integer(42));
System.out.println(MyEnum.valueA.get()); // prints "42"
}
}
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx