Skip to content Skip to sidebar Skip to footer

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 secon

Solution 1:

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.
    }
}

Solution 2:

I think you must access them in a 'static way', i.e.:

String myVar= name; // wrong
String myVar= TheClassThatContainsName.name; // right

Solution 3:

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


Solution 4:

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");

  }
}

Solution 5:

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;
 }
}

Post a Comment for "Public Static Variable Is Accessible In Second Activity In Android?"