简体   繁体   中英

how to call 2nd activity value in 1st activity?

I'm calling 2nd activity value in 1st activity but it does not show. Tell me why? If I declare public static String in 1st activity and call in 2nd activity is show perfectly but if i declare public static String value in 2nd activity and calling in 1st activity is show null tell me why??

  import android.widget.EditText;
  import android.widget.TextView;
  import android.widget.Toast;

  public class ButtonExample extends Activity
 {
   Button b1;

  String Latitude500;

 public void onCreate(Bundle savedInstanceState)
{
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

  b1 = (Button) findViewById(R.id.button1);


 Latitude500=textview.Latitude1nazeer;

 TextView t3 = (TextView) findViewById(R.id.textView2);

t3.setText(""+Latitude500);


 b1.setOnClickListener(new OnClickListener()
 {
 public void onClick(View v)
 {



  Intent intent = new Intent(ButtonExample.this, textview.class);



startActivity(intent);


 }
  });


         public class textview extends Activity {



  public static String Latitude1nazeer;


  EditText Latituden1;

     public void onCreate(Bundle savedInstanceState)
  {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.laymenu);


   Latituden1 = (EditText) findViewById(R.id.editText2);
   String ln = Latituden1.getText().toString();


   Latitude1nazeer=ln;





  }
          }




         <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mypackage"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".ButtonExample"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
     <activity android:name=".textview" > </activity>   
</application>

 </manifest>

It is Because , before assigning value to string in 2nd Activity you are reading in first activity. So it is null.

Declare like this in 2nd Activity public static String Check="check"

Print this value in 1st Activity. You came to know this

Do not do this! This is really bad practice.

The simple answer to your question is because activity 2 has not been initialised until you start it. An activity is an object of type Activity like any other object. There is nothing mysterious about activities - except, Android reserves the right to kill them if they are not the active activity.

You should not be passing anything out of an Activity unless absolutely necessary. The rule of thumb is that nothing with a lifecycle greater than an activity should reference anything in that activity. That's why Android has Intents for inter process communication between activities.

Since a static is declared in Activity A and is then referenced in Activity B, Activity B is now in the foreground. Android can destroy Activity A. If it does, then you've just leaked the entire activity and all resources it has a reference too.

There are several solutions to this but for me, the correct answer is to rethink your design. Why does one activity need direct access to anything in another activity? I'm sure there are some really strange designs which might suggest this but I can't think of any rational explanation for doing this is "normal" Android development.

Possible solutions, in my personal preferred order of correctness:

  • If the value of the string is variable, pass the value of the string between activities in the bundle with Intent. Rating - Very nice.
  • If the string is fixed, put it into strings.xml. Rating - Very Nice.
  • If it is truly global (and think really hard about that), then extend your Application class. Rating - I start to smell something
  • Create a separate class with a static string. Rating - Smells worse than my feet after a long day at the keyboard.

Please stop and think about this. Also please edit your question to explain what you are trying to do and why you are trying to do it.

Don't worry about code for now, find the right solution first then worry about the code.

[EDIT] More for possible future readers than part of the answer to this specific question.

Imagine you create your own class. That class has a user interface with a hierarchy of views. It has some bitmaps to make the UI look nice and can hold references to all kinds of data, for example strings to populate the UI. It might also have an adapter to connect to some data structures. It has a static field so that other objects can access data in an instance of this class.

Let's park the discussions about "are statics evil" and "global variables" for now.

You create an instance of this class and other objects start referencing it. It's all good so far since you control the life cycle of that object and can write your code to ensure that nothing can retain a reference to it when you want to release it.

Now imagine I told you that something outside your application could destroy that object by dereferencing it and allowing the garbage collector to collect the memory it used. The garbage collector examines the object and sees that it is dereferenced. But wait a minute, there's a static class level field which another object has a reference to. Since the static must be at class level, either as a variable or as a static method, the garbage collector will not free that object. You now have an object sitting on your heap with all of the memory it used which you can no longer reference.

Would you still think that the above was a safe solution?

The key point here is that an activity is just that. It's an object instance of the Activity class. But on Android, the object has some special properties, one of which is that Android can kill that object with no further call backs to your code.

Do not share data between activities by using static fields. Static fields only live as long as their class is loaded by the JVM and Android makes no guarantees about that. The correct way to do it is by putting the data in an Intent . Please read the Intents guide.

Add onResume() method in ButtonExample becuase this method called when your appliction get resumed or user press back button on textview

@Override
public void onResume()
{
    Log.v("Resuming", "onResume");
    t3.setText(""+Latitude500); // set text here
    super.onResume();
}

and my preference is Avoid to use of static variables for Application.you can use SharedPreferences or Intent for Sharing Data Between Application Components

Android already have method for getting the value in one activity to another activity by methode startActivityForResult(). This link can guide you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM