开发者

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 ?

Pleas开发者_StackOverflow中文版e 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"; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜