简体   繁体   English

如何在第一个活动中调用第二个活动值?

[英]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?? 如果我在第一个活动中声明了公共静态字符串,并在第二个活动中调用,则可以很好地显示出来;但是,如果我在第二个活动中声明了公共静态字符串值,并在第一个活动中,调用显示了null,请告诉我为什么?

  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" 在第2个活动中这样声明: 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. 您问题的简单答案是,活动2在启动之前尚未初始化。 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. 活动没有什么神秘之处-除非活动不是活动的,否则Android保留杀死它们的权利。

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. 这就是Android在活动之间进行流程间通信的意图的原因。

Since a static is declared in Activity A and is then referenced in Activity B, Activity B is now in the foreground. 由于在活动A中声明了一个静态变量,然后在活动B中对其进行了引用,因此活动B现在位于前台。 Android can destroy Activity A. If it does, then you've just leaked the entire activity and all resources it has a reference too. Android可以销毁ActivityA。如果确实如此,那么您就泄漏了整个活动以及它也具有引用的所有资源。

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. 我敢肯定有些真正奇怪的设计可能会暗示这一点,但是我无法想到任何合理的解释都是“正常的” Android开发。

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. 如果字符串的值是可变的,请使用Intent在捆绑包中的活动之间传递字符串的值。 Rating - Very nice. 评分-非常好。
  • If the string is fixed, put it into strings.xml. 如果字符串是固定的,则将其放入strings.xml。 Rating - Very Nice. 评分-非常好。
  • If it is truly global (and think really hard about that), then extend your Application class. 如果它确实是全球性的(并且对此进行认真思考),则扩展您的Application类。 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. 它具有一些位图,可以使UI看起来不错,并且可以保存对各种数据的引用,例如用于填充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. 这是Activity类的对象实例。 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. 但是在Android上,对象具有一些特殊的属性,其中之一就是Android可以杀死该对象,而无需进一步调用代码。

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. 静态字段仅在JVM加载其类的情况下存在,Android对此不做任何保证。 The correct way to do it is by putting the data in an Intent . 正确的方法是将数据放入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 ButtonExample添加onResume()方法,因为当您恢复应用或用户在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 我的偏好是避免对Application使用静态变量。您可以使用SharedPreferences或Intent在应用程序组件之间共享数据

Android already have method for getting the value in one activity to another activity by methode startActivityForResult(). Android已经有了通过startActivityForResult()方法将一个活动中的值转换为另一个活动中的值的方法。 This link can guide you. 链接可以指导您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将第1个活动的值传递给android中的第2个活动 - Pass the value from 1st activity to 2nd activity in android 完成第二个活动(由第一个活动调用)后如何在第一个活动中调用onCreate方法 - How to call onCreate method in 1st activity after finishing 2nd activity(which is called by the 1st activity) 如何从第二活动到第一活动获取数据 - How to get data from 2nd Activity to 1st Activity 第一项活动第二项活动获得纬度经度地理位置。 如何将信息转移回第一活动? - 1st activity 2nd activity to get the latitude longitude geo-location. How to transfer info back to 1st activity? 从第一个活动转到第二个活动时出错 - error when going from 1st activity to 2nd activity 从第一个活动拨打电话后,第二个活动没有通话 - 2nd Activity doesn't call after calling from 1st Activity 无法通过getIntent()将第一个活动的textview值传递给第二个活动的textview - Unable to pass 1st activity's textview value to 2nd activity's textview through getIntent() 从第一个活动中获取意图后如何刷新第二个活动 - How to refresh 2nd activity after intent from 1st activity 如何保存从第一个活动传递到第二个活动的意图数据 - how to save intent data passed from 1st activity to 2nd activity 按下后如何将数据从第二个活动传递到第一个活动? - android - How to pass data from 2nd activity to 1st activity when pressed back? - android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM