passing variable status between classes - android

I am making a boolean variable value in one class and accessing the status of that variable in another class , on the basis of the boolean variable status my list view shows items,
So my question is
how to create a global boolean varible
how to pass it to another class
how the second class check it

1. Variable in class A
public class A{
public String aClassVar="hello";
}
Using it in Class B
A obj=new A();
String inBClass=obj.aClassVar;
2. To pass data from one Activity to Another Activity you can use Intent remember your Class should extends Activity only than you will be able to pass data by using Intent
Example
Send Data From First Activity using :
Intent i = new Intent(this, SecondClassName.class);
i.putExtra("key", "Value");// key is used to get value in Second Activiyt
startActivity(i);
Receive Data on Second Activity using:
Intent intent = getIntent();
String temp = intent.getStringExtra("key");// usr getStringExtra() If your extra data is represented as strings:
And you Must set Activity Name inside AndroidManifest.xml
like:
<activity android:name="yourPackageName.SecondClassName" />

Let me suggest 3 options.
Do you want to pass a boolean variable between Android Activities? If so, You may want to use a Bundle. Yes, those little things given to Activities on onCreate(). You can pass variables of your own into these, in your case a boolean, with putBoolean() and getBoolean()
Would you prefer using Android's SharedPref? It's an interface for sharing small preferences, like boolean flags, between parts of your app and storing it for later.
Or, you could just implement a singleton class that has the boolean variable and other variables you need to store and check by different classes within your app.

If you just want to access the value of an object or variable in another class, make it Static and then when you need its value, do like
public class tempClass {
public void tempMethod() {
boolean status = myClass.myVariable ; // where myVariable is static boolean varaible of myClass
}
}
But make sure to access the variable after some value is stored in it.
If you want to send the value to another activity then send the value by using intent.
Eg.
Bundle myBund = new Bundle();
myBund.putBoolean(myBool);
Intent intent = new Intent(myClass.this, tempClass.class);
intent.putExtras("myKey",myBund);
startActivity(myBund);

Related

Passing Intent data from Activity to Class

I want to pass string from my activity class to my class that is not extended to activity. I know this is possible but how to do that? I am new to android development so please help
In android you can send data through Intent or Intent followed by Bundle like:
Intent i = new Intent(current_activity.this, linked_class.class);
i.putextra("Key", value);
And get the value(suppose string value) in another class like:
String value = getIntent.getExtra("String key which you used when send value");
Option 2:
class yourClass {
public static String _utfValue = "";
void sendValue(){
_utfValue = "some value";
}
}
And fetch this value in your java class like:
String value = A._utfValue ;
Option 3: You can use SharedPreference to save the value and get it from other class.
Option 4: You can use a static method with some return value and fetch the method in your java class through class name.
All the options are rough here. So just check this ,hope one of these will help you .
You create static variable and access anotherclass
like
Static String mydemo=null;
mydemo="sagar";
then access directly in another class

How to store global variables using setter and getter in Android?

i am new to android development and i was trying to use a global variable across two activities. So how do i do the same using setter and getter? or is there a better way?
Please do help me!
Thanks in advance!
Sidharth
For global variable :
Use can use SharedPreference, which will save the value till you uninstall the application and can be accessed from anywhere within application using context.
Extend Application class, and declare the global variable inside it and add getter and setter methods.
And in your activity :
YourApplication yourApplication = (YourApplication) getApplicationContext();
yourApplication.setGlobalValue(10);
yourApplication.getGlobalValue();
Create class :
class YourApplication extends Application {
private Integer globalValue;
public Integer getGlobalValue() {
return globalValue;
}
public void setGlobalValue(Integer value) {
globalValue = value;
}
}
The easiest way to do this would be to pass the variable to the second activity in the intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("variableKEY", variable);
startActivity(intent)
Access that intent on next activity
String s = getIntent().getStringExtra("variableKEY");
The docs for Intents has more information (look at the section titled "Extras").
From here

How to persist a subset of data from a larger set in Android?

A network call returns a very large json file. However, I just need to use a small portion of this through out the entire app. What is the best strategy on using a small amount of data for several fragments and activities ?
I tried to use shared preferences, but that does not store objects.
For sharing complex data structures or objects, I would extend Application by making a custom sub class. Application object (as the name implies) is accessible to all Activities, even when app transitions from one to another. Below is a very simple example, just to show you the idea. You can modify/adjust that to your needs.
public class MyApplication extends Application {
private X x;
public static void setX(X x) { ... }
public static X getX() { ... }
}
public class ActivityA extends Activity {
...
MyApplication.setX(x);
}
public class ActivityB extends Activity {
...
X x = MyApplication.getX();
}
X can be a collection, data structure, or any object for that matter.
When extending Application, you need to declare it in the manifest. You can find information on how to do that.
Extract the required data from your JSON as a String and then pass it as an extras parameter to the Activities and Fragments that need it:
Intent intent = new Intent(context, SomeActivity.class);
intent.putExtra("YOUR_DATA_KEY", yourJsonString);
startActivity(intent);
and then extract it back again at the Activities and Fragments that need it:
Intent intent = getIntent();
String yourJsonString= intent.getStringExtra("YOUR_DATA_KEY");

Putting serializable extra object to intent changes the object

I am trying to pass an object from an activity to another activity. Here is what i do:
MyApplication.db= dbToOpen;
Intent i = new Intent(mContext, OpenDbActivity.class);
i.putExtra("PARENT_GROUP", dbToOpen.root);
mContext.startActivity(i);
Here, MyApplication is the class that extends application, and db object is a static object. My extra object dbToOpen.root is an object of the class DBGroupv1.
Then i get this extra in onCreate method of OpenDbActivity class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opendb);
db = MyApplication.db;
groupToOpen = (DBGroupv1) getIntent().getSerializableExtra("PARENT_GROUP");
}
Then i try this boolean expression:
MyApplication.db.root == groupToOpen
and it returns false. When i look at the objects dbToOpen.root and groupToOpen, every single value of the variables inside those objects are the same. But they are are different objects. Why is this happening? Is it because of casting, or does Intent.putextra() method passes a copy of an object, not a reference? If that is the case how can i pass the object as a reference?(Except using static variables)
Thanks
You should use the .equals()-method to compare instances of objects. if you use == you will only get true if the two objects are exactly the same reference. Since the instance in your intent is newly created when deserialized from the bundle, it is no longer a reference to the same instance (although the two objects contains the same data).
So, instead of
MyApplication.db.root == groupToOpen //bad
use
MyApplication.db.root.equals(groupToOpen) //good
Also make sure that if you made the root-object, you implement the equals method properly, so it takes all appropriate variables into consideration.
You can read a bit more here: What is the difference between == vs equals() in Java?

Passing a simple variable value for use in another class in Android

What is the correct way to pass a simple variable which has its value set to use in another class? I have a counter which is incremented with a button press and when counter = 3 a method is called which loads another activity which loads another screen with a string which states the button was pressed. Here is where I want to include the number 3 passed from the counter variable in the previous class, but I am not sure the correct way to do this.
I tried creating an instance of the class and connecting to the variable that way but the value is never passed and it is always 0.
Try following code,
public class First
{
private static int myVarible = 0;
private void myMethod()
{
myVariable = 5; // Assigning a value;
}
public static int getVariable()
{
return myVariable;
}
}
public class Second
{
int i = First.getVariable(); // Accessing in Another class
}
You may pass value via Intent - resource bundle.
Pass value from current activity,
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra("no",10);
startActivity(intent);
and in ResultActivity (onCreate),
Bundle bundle=getIntent().getExtras();
int value=bundle.getInt("no");
In case of non-activity classes, you may define a public method.
For instance,
public Integer getValue() //returns a value
{
return 10;
}
Or
public void setValue(Integer value)
{
...
}
one way to do it would be when you build your new intent to do :
Intent itn = new Intent(...,...);
itn.putExtra(KEY,VALUE);
startctivity(itn);
And on the other class do something like :
this.getIntent.getStringExtra(KEY);
or
this.getIntent.getWHATEVERYOURVARIABLEWASExtra(KEY);
Hope it helps you, and it's the better way to pass arguments between 2 activities :)
You can also do it through define variable as "static" in one activity and in second activity use that variable with using <<classname>>.<<variableb>>
ex:
Activity1:
Static var = 5;
Activity2:
System.out.println(Activity1.var);
You can pass that value using the intent
Intent new_intent=new Intent(this,SecondActivity.class);
intent.putExtra("counter",10); //here the value is integer so you use the new_intent.putExtra(String name,int value)
startActivity(new_intent);
After that in the second activity class you can get that that values using Bundle
Bundle bundle = getIntent().getExtras();
int count = bundle.getInt("counter");
I think this may help you.

Categories

Resources