how to change label from another Activity (Android) - android

is it possible to get all activities in the application? i have a global integer variable that should be in the ActionBar of every activity. i thought something like this:
for (Layout/Activity l in (all activites)) {
l.setTitle(variable);
}
i already tried it with R.layout but this didnt work for me.
How can i do this or is there a better way to display my variable in all activity labels? later i want to call this code from my set method for the global variable.

There is only one activity running at a time, so you can’t get this kind of references.
Said that, I think the way to go it’s create an int static variable in some class, and called it from your activities.
//SomeClass
public static int xValue = 0;
//ActivityOne || ActivityTwo || ActivityThree ...
String text = String.valueOf(SomeClass.xValue);
SomeClass.xValue = 1;
Because it’s a public static variable, you don’t need to instantiate any object to get/set its value, and it will be accesible from any class. Furthermore, this value will be reachable as long as its class is in the memory, and destroy just when class gets unloaded.

yes it's possible with singleton.
This is how to use singleton:
This is Singleton class:
public class Singleton {
private static Singleton mInstance = null;
private String mTitle;
public void setmTitle(String mtitle){
this.mTitle=mtitle
}
public String getmTitle(){
return mTitle;
}
public static FilterArrayList getInstance(){
if(mInstance == null)
{
mInstance = new FilterArrayList();
}
return mInstance;
}
}
This is the first activity:
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Singleton.mInstance.setmTitle("This is Singleton");
}
}
and in second activity:
public class SecondActivity extends Activity {
String Title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Title=Singleton.mInstance.getmTitle();
}
}

Related

how to call method from activity in another class

i need to get method from appcompatactivity to this class and call this method in another appcaompatactity like this
public class WareHouseActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
}
public void showToast(){
Toast.makeText(WareHouseActivity.this,"warehouse",Toast.LENGTH_SHORT).show();
}
}
call method showToast from appcampatactivity in this class :
public class Common {
public static void showToast(Activity activity){
((WareHouseActivity)activity).showToast();
}
}
and i try with context instead of using Activity like:
public class Common {
public static void showToast(Context context){
((WareHouseActivity)context).showToast();
}
}
call method showToast from class in another appcompatactivity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
Common.showToast(MainActity.this);
}
}
If you want to share a method with multiple Activities, it cannot live on an Activity instance. You can't be guaranteed that the instance exists when another Activity is being shown, and you should never create Activity instances yourself.
If you move the full method to a separate class like this:
public class Common {
// You must pass in any arguments needed in the function
public static void showToast(Context context){
Toast.makeText(context,"warehouse",Toast.LENGTH_SHORT).show();
}
}
Then you can call it from any activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
Common.showToast(this);
}
Update
If the reason you want to do this is to have shared data that you can access from both activities, that data should not live in one of the activities. Have a look at the activity lifecycle, activities will be destroyed when the device is rotated, or can be destroyed when in the background by the OS. Any temporary data you store on an activity would be lost when that happens.
One simple option for storing some temporary data is a singleton class. This is not persistent - the data will still be lost if your app is stopped and restarted). If you need persistent data you should use SharedPreferences or a database for that. However, it will let some temporary data live longer than an individual activity's lifecycle and be accessible from multiple activities or fragments.
class Common {
private static Common instance = null;
private Common() {}
public static synchronized Common getInstance() {
if (instance == null) {
instance = new Common();
}
return instance;
}
final List<String> names = new ArrayList<>();
String message = "";
void showMessage(Context ctx) {
Toast.makeText(ctx,message,Toast.LENGTH_SHORT).show();
}
}
Then you can set and use data stored in this class from multiple activities, like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Common c = Common.getInstance();
c.message = "Hello from Main";
c.names.add("Test");
}
}
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Common c = Common.getInstance();
c.showMessage(this)
c.names.add("Test Two");
}
}

How do you pass information to and from a non activity class?

So I have this "middle man" nonactivity class, where I want to get a string path from an activity class. Then, from my nonactivity class send that string path to a different activity?
Activity A
#Override
public void onCreate(Bundle savedInstanceState)
{
Intent imageToFactory = new Intent(this,NonActivity.class);
imageToFactory.putExtra("yourImage", user_image_path);//I already set user_image path
}
NonActivity
public class NonActivity
{
private Intent grabImagePath = new Intent();
private String grabImagePathString = getIntent.getStringExtra("yourImage");//this obviously gives an error but for the example
public String grabUserImage()
{
return grabImagePathString;
}
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
NonActivity nonActivity;
String example = nonActivity.grabUserImage();
}
So this method doesn't work for some reason, I think I have to use contexts some how but im not sure exactly how to use them, if anyone can help with examples or modify the example code i did below that'd be awesome!
You can build a static variable that can serve as message bridge, first thing you need to create a class and name it anything you like, in my case I will name the example class as Conn, then add a static HashMap.
public class Conn {
public static HashMap<String,String> storage = new HashMap<>();
}
To utilize this this class in your example:
Activity A
#Override
public void onCreate(Bundle savedInstanceState){
Conn.storage.put("yourImage",user_image_path_in_string);
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
String example = Conn.storage.get("yourImage");
}
if you want to use third class ( here NonActivity.class ) for some reasons, just do it like this:
create globals class like this :
package helper;
public class Globals {
private static final Globals instance = new Globals();
private GlobalVariables globalVariables = new GlobalVariables();
private Globals() {
}
public static Globals getInstance() {
return instance;
}
public GlobalVariables getValue() {
return globalVariables;
}
}
and global variables class like this :
public class GlobalVariables {
public String grabImagePathString;
}
now in activity A::
Globals.getInstance().getValue(). grabImagePathString = "something......";
and in activity B::
String gtabImagePathString = Globals.getInstance().getValue(). grabImagePathString;
Good Luck

How to pass values without using argument in android

Friends In My Application , i want to use text box value in
all other activity without passing any argument. how it's possible? Anyone
know these give me a example, thanks in advance. by Nallendiran.S
There are a few different ways you can achieve what you are asking for.
1.) Extend the application class and instantiate your controller and model objects there.
public class FavoriteColorsApplication extends Application {
private static FavoriteColorsApplication application;
private FavoriteColorsService service;
public FavoriteColorsApplication getInstance() {
return application;
}
#Override
public void onCreate() {
super.onCreate();
application = this;
application.initialize();
}
private void initialize() {
service = new FavoriteColorsService();
}
public FavoriteColorsService getService() {
return service;
}
}
Then you can call the your singleton from your custom Application object at any time:
public class FavoriteColorsActivity extends Activity {
private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_colors);
service = ((FavoriteColorsApplication) getApplication()).getService();
favoriteColors = service.findAllColors();
ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
favoriteColors);
lv.setAdapter(adapter);
}
2.) You can have your controller just create a singleton instance of itself:
public class Controller {
private static final String TAG = "Controller";
private static sController sController;
private Dao mDao;
private Controller() {
mDao = new Dao();
}
public static Controller create() {
if (sController == null) {
sController = new Controller();
}
return sController;
}
}
Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.
3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.
I hope I gave enough detail in regards to how you can do what you are hoping for.
Create it static type and than you can get it where you want.
Private TextVeiw txtvw;
Public static String myText="";
myText=txtvw.getText();
Access this variable with class name in which it defined.
MyActivity.myString

How to pass an Activity instance to another activity

Hi I have an activity named BaseActivity, which extends Activity.
from this i have to go to SettingsActivity which extends PreferenceActivity, on menu button press. To start a AsyncTask, which is in an independent class, i need an instance of BaseActivity. How can i get a BaseActivity instance in the SettingsActivity?
is there any way like,
eg:
intent.putExtra("activity_instance",BaseActivity.this);
Use getters and setters and make the class they reside as singleton class.
This is a singleton class.Using this class we can share data(ex: int,boolean,activity instance ...etc) all over the class.
public class CommonModelClass
{
public static CommonModelClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private Activity baseActivity;
public CommonModelClass()
{
// Optional Code
}
public static synchronized CommonModelClass getSingletonObject()
{
if (singletonObject == null)
{
singletonObject = new CommonModelClass();
}
return singletonObject;
}
/**
* used to clear CommonModelClass(SingletonClass) Memory
*/
public void clear()
{
singletonObject = null;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
//getters and setters starts from here.it is used to set and get a value
public Activity getbaseActivity()
{
return baseActivity;
}
public void setbaseActivity(Activity baseActivity)
{
this.baseActivity = baseActivity;
}
}
In BaseActivity class do like this.
Class BaseActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
CommonModelClass commonModelClass = CommonModelClass.getSingletonObject();
commonModelClass.setbaseActivity(BaseActivity.this);
//after using the BaseActivity instance dont forget to call commonModelClass.clear(); else it wont be garbage collected
}
}
In SettingsActivity do like this
Class SettingsActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
CommonModelClass commonModelClass = CommonModelClass.getSingletonObject();
Activity instanceBaseActivity= commonModelClass.getbaseActivity();;
}
}
please give tick if this works
You are confusing activities with class objects. The moment activity class is instantiated it obeys all activity life cycle rules, importantly system can kill this activity any time. So you have to design activities in such a way that it shouldn't be dependent on another activity instance at all but only drive the results. you can write a helper class and call it again and again if you want. if not use storages like sdcard or preference or sandbox to store the information and retrieve it from the other activity. If you want to keep some of these information in memory then subclass Application class and keep them at the application level.
Make a static Context in "Base Activity"
public class BaseActivity extends Activity{
public static Context ctxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctxt = BaseActivity.this
}
}
and in your "PreferenceActivity" activity use this way
BaseActivity.ctxt

public static variable is accessible in second activity in android?

I am working in android. I have two acitivities in my project. I have declared a public static variable in one activity like this:-
public static String name="KUNTAL";
In my second activity i am trying to use this variable, then it is generating error that this name variable is not exist.
Is this possible to use a variable anywhere in my project if it is declared as public ?
Please suggest me what mistake i have done.?
Thank you in advance...
public class Activity1 extends Activity {
public static String name="KUNTAL"; //declare static variable.
#Override
public void onCreate(Bundle savedInstanceState) {
}
}
public class Activity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Activity1.name; //way to access static variable using dot operator.
}
}
I think you must access them in a 'static way', i.e.:
String myVar= name; // wrong
String myVar= TheClassThatContainsName.name; // right
You can use the variable specified as public static in any Activity but you need to access that variable by using the Activity name where you Declared it.
For Accessing in Second Activity just use ;
Activity1.name ="Me";
means that name variable belongs to Activity1 and you are using in Acvity2
Declaring variables public static is not the recommended way of passing values between two activities. Use Intent object instead:
public class Activity1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
yourButton.setOnClicklistener(listener);
}
}
//On click of some button start Activity2:
View.onClicklistener listener = new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent mIntent = new Intent(Activity1.this,Activity2.class);
mIntent.putExtra("yourKey","yourValue");
startActivity(mIntent);
}
};
//and then in your activity2 get the value:
public class Activity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
String yourValue = getIntent().getExtras().getString("yourKey");
}
}
if you're using the same variable in more than one activity then make a class something like ActivityConsts{}, and declare and initialize this variable in there(in ActivityConsts). And access this variable from anywhere with the class name.
ex-
declare a class-
public class ActivityConsts {
//your String var
public static String name="KUNTAL";
}
now in your activity:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
String yourStringVar = ActivityConsts.name;
}
}
There is no datatype specified for your variable. Use
public static String name="KUNTAL";

Categories

Resources