I want to know that how can I make a an Object again go back to its initial stage.
In my case I make a fragment and initialize it. I want that when it goes back to another fragment, and then back to first one, all values and variables of the first objects again initializes.
MyFragment frag = new MyFragment();
How can it again go back to this stage without initialization it again with new Keyword.
You can use setters.
public class MyFragment extends Fragment{
private String name;
public void setName(String name){
this.name = name;
}
//other code
}
Now you can use
frag.setName(null);
You can also make a method to reset all the variables inside the MyFragment class.
public void reset(){
name = null;
//other stuffs = null
}
so that you can call frag.reset();
You can use below setter technique
public class MyFragment extends Fragment{
private String name;
private String address;
public void resetAll(){
myFragment = null;
}
}
Here myFragment is reference variable of fragment. After call of resetALL method, every String variable available in fragment will be null
Related
What will be the implications if I passed an object to a fragment without using bundle? I just opened one of the old code and found it there and couldn't help asking this question as I have never tried it. Also I am not finding any memory leaks in it.
This is how it is implemented -
Activity class:
MyFragment fragment =
MyFragment.newInstance(getIntent().getStringExtra(DATA),
instance.getCallback(),
instance.getRequest());
getSupportFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();
Fragment class:
public class MyFragment extends Fragment {
public MyFragment() {
/* Required empty public constructor */
}
public static MyFragment newInstance(String data, Callback callback,
Request request) {
MyFragment fragment = new MyFragment();
fragment.setCallback(callback);
fragment.setRequest(request);
fragment.setData(data);
return fragment;
}
private void setCallback(Callback callback) {
this.callback = callback;
}
private void setData(Data data) {
this.data = data;
}
private void setRequest(Request request) {
this.request = request;
}
}
Generally, what I have used till date is Fragment#setArguments(Bundle)
Please check out this answer: Why its not recommended to pass object to fragment with simple getter setter.
Long story short, you will lose your data on configuration changes.
There are mainly two ways of communicating with a fragment: via bundles or via an interface that you implement in your activity. Please see this link in order to see how to properly communicate with a fragment via an interface: https://developer.android.com/training/basics/fragments/communicating
I have two classes where I want to access the value of a unique variable. In the first class I want to set the value of a 'isToogleflagon= true'. In the second class I want to get the value of 'IsToogleflagon'.
Here is where I set and get 'IsToogleFlagon'
public class Toogleflag{
private String _isToogleflagon;
public Toogleflag(){}
public Toogleflag(String isToogleflagon) {
this._isToogleflagon=isToogleflagon;
}
public String get_isToogleflagon(){
return _isToogleflagon;
}
public void set_isToogleflagon(String isToogleflagon) {
this._isToogleflagon = isToogleflagon;
}
I want to set the value of isToogleflagon="true" in my main class. Below is part of my main class where I do this.
public class MainActivity extends AppCompatActivity {
Toogleflag toogleflag1 = new Toogleflag();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
toogleflag1.set_isToogleflagon(GlobalVariables.TRUE);
...
Global.values(True)
public class GlobalVariables
{
public static String TRUE = "true";
public static String FALSE = "false";
}
Here's my second class where I want to get the value of isToogleflagon, in this case "true"
public class secondclass {
Toogleflag toogleflag2 = new Toogleflag();
public void test{
String test=toogleflag2.get_isToogleflagon();
}
When I run Class Secondclass the value of 'string test' does not get assigned a value. I want it to be assigned the value of "true". Any advise on how to fix this is greatly appreciated.
thanks,
Jim
This is happening because you are making a new object with default/ no argument constructor. When you make an object with default constructor, all the instance variable gets initialzes with their default values. For example,
1) int variable gets 0
2) boolean variable gets false
3) String variable gets null
That is happening in your case. As in your code it is mentioned that in main class when are you are setting value with String constructor to the variable named isToogleflagon it gets set as your constructor passed value, but when you are accessing the value of that variable again via calling no argument constructor, the variable isToogleflagon gets initiaze with defualt values as well. To get the value consistant across over all the app you need to make that class object as Singleton. It will be solving your problem. Hope you got my point. Below is the sample code for your reference to make singleton
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton() { }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
I have been looking for a long time for a simple way to pass data (string type) from class to activity.
I found some tutorials about passing data from activity to class but is it possible to do the opposite, passing data from class to activity ?
if you import the class in your activity (which is also a class by the way) you can easily access the classes attributes.
example: MyClass.java
package edu.user.yourappname;
public class MyClass {
public string infoToPass = "whatever";
}
MyActivity.java
package edu.user.yourappname;
import edu.user.yourappname.MyClass
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String myString = MyClass.infoToPass;
}
}
i have no IDE to type this in atm it might contain some errors :S but i hope you get the idea.
if you need more specific help you have to provide a code sample.
also, what do you want to achieve exactly? maybie there's a different approach.
cheers!
Create Interface and implement that in your activity. Pass the activity instance in your class and and call that instance with interface method whenever you like.
To be more clear, create an interface and use it as following:
public interface SomeInterface{
public void passValue(String value);
}
public SomeActivity extends Activity implements SomeInterface{
// place any code you want in your activity, onCreate, onResume, etc.
private void someMethod(){
// Wherever in your activity, initialize your class with your activity.
SomeClass someClass = new SomeClass(this);
someClass.someMethod();
}
public void passValue(String value){
// do whatever you want with your value
}
}
public class SomeClass{
private SomeInterface someInterfaceInstance;
public SomeClass(SomeInterface someInterfaceInstance){
this.someInterfaceInstance = someInterfaceInstance;
}
public void someMethod(){
// Some code...
someInterfaceInstance.passValue("Hello World!");
// Some more code...
}
}
Here is a easy way of doing it -
By defining static variables
In your class, make the String whose value you want to pass public static like this -
public static String pass;
And then in you activity, you can directly access it since it's a public variable like this -
String receive = className.pass;
I've got a class which contains a getter and setter for the variable "artist":
Class:
public void setArtist(String artist) {
this.artist = artist;
}
public String getArtist() {
return artist;
}
I'd like to call setArtist from an activity like so:
Activity 1:
Playlist.setArtist(someString)
But eclipse tells me I need to change setArtist to static. The whole point of me using setters was to avoid having any static references. Am I doing something wrong, or is there another way to accomplish this?
It entirely depends on where and when you want your object. You could do something like this:
class Artist implements Serializable{
public static final String EXTRA = "com.your.package.ARTIST_EXTRA";
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Activity 1:
public void onCreate(Bundle savedInstance){
// ....
Artist artist = new Artist();
artist.setName("Rolf");
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Artist.EXTRA, artist);
startActivity(intent);
}
Activity 2:
You then have a reference to your Artist in the second Activity:
public void onCreate(Bundle savedInstance){
// ....
Artist artist = (Artist) getIntent().getSerializableExtra(Artist.EXTRA);
Log.d("YourApp", "I have the artist! "+ artist.getName());
}
Watch what you are serialising as you cannot serialize certain objects.
Another way to go it would be to have a class that extends Application and keep a reference in there, then you could retrieve it from any Activity context.
You cannot assume that the other activity will be in memory so its the wrong way to do it. I would read some of the android activities and how to use them.
http://developer.android.com/guide/topics/fundamentals/activities.html
please make an Object of Playlist then set the variable.
Playlist mObjPlaylist= new Playlist();
mObjPlaylist.setArtist(someString);
If you want to access a method like A.show(), the show() method should be a static method, coz static method does not require objects to be accessible.
One solution is to make these getters and setters as static method and access it as you are accessing it now.
Another solution, is to use, Singleton pattern, so in this case you don't need to make these methods static, you just need to get the singleton object of that class and access these methods like this:
PlayList.getInstance().setArtist();
The way you are dealing with activity is not the right way.
If you need some common data to use in both Activity then you can manipulate it by using a common Class,not putting it in Activity.Also if you want to pass some data while launching another activity from an activity you can pass it through intent extra.
class PlayList{
private static PlayList self=null;
private string artist;
public static PlayList getInstance(){
if(self==null){
self=new PlayList();
}
return self;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getArtist() {
return artist;
}
}
I'm trying to create an ArrayList of Data containing Objects (Like a list of Addresses and properties (pretty complex)) and am wondering: How can I make an Object accessible (and editable) by all Activities and not just the one it was instanciated in?
Basically this:
Create Array in Activity 1
Access same Array in Activity 2 and 3
???
Profit.
The easiest way to do this is by creating an Singleton. It's a kind of object that only can be created once, and if you try to access it again it will return the existing instance of the object.
Inside this you can hold your array.
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
Read more about singleton:
http://en.wikipedia.org/wiki/Singleton_pattern
You can extend the application class. And add your arrays there.
You can access the instance of the class by using this command
MyApplication appContext = (MyApplication)getApplicationContext();
Well you can create a Constant class and declare you ArrayList as a static variable.
1.)
Class ConstantCodes{
public static ArrayList<MyClass> list = new ArrayList<MyClass>;
}
This will be accessible from everywhere you want by just ConstantCodes.list
2.) You can extend your class by Application class like this
class Globalclass extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class TempActivity extends Activity {
#Override
public void onCreate(Bundle b){
...
Globalclass appState = ((Globalclass)getApplicationContext());
String state = appState.getState();
...
}
}
you should make it static and access it from any other activity.....
how about use a static keyword ?
public static SomeClass someObject
in your activity class that initiate your object
1- In your Activity1, déclare your array in public static
public static ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String, String>>();
2- In your Activity2, Activity3, etc. access to your ArrayList
Activity1.myArray
You can create a java file x beside other java files.
x file contains static method which used to access the class method without instantiate it.
Now make a method called createVariable() and declare variable which you want to make it Global.
Now make a method called getVariable() which returns the Global variable.
At which point you want to create global variable, call className.createVariable().
And to get access to that variable call className.getVariable().
Here is my example for Database class.
public class GlobalDatabaseHelper{
static DatabaseHelper mydb;
public static DatabaseHelper createDatabase(Context context)
{
mydb = new DatabaseHelper(context);
return mydb;
}
public static DatabaseHelper returnDatabase()
{
return mydb;
}
}