【问题标题】:Passing strings between activities in android在android中的活动之间传递字符串
【发布时间】:2012-02-03 15:04:32
【问题描述】:

我已经搜索了很多地方,但我还没有找到任何有效的解决方案,我真的需要帮助! 我正在制作一个需要将经度和纬度字符串从一个活动传递到另一个活动的应用程序。 我怎样才能做到这一点???看看我的代码:LocationActivity.java 需要将字符串传递给另一个活动和另一个我没有粘贴到这里的活动。并且需要传递的字符串命名为:“latLongString”

LocationActivity.java:

import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class LocationActivity extends Activity {
private String Location;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LocationManager locManager;
    locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
    Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    updateWithNewLocation(location);
    if(location != null)                                
    {
        double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    }  
  }


private void updateWithNewLocation(Location location) {
    TextView myLocationText = (TextView)findViewById(R.id.LocationWord);
    String latLongString = "";
    if (location != null) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        latLongString = "Lat:" + lat + "\nLong:" + lng;
        //This is where i need to pass the string to the other activity

    } else {
        latLongString = "No location found";
    }
     myLocationText.setText("Your Current Position is:\n" +
            latLongString);
}

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        updateWithNewLocation(location);
    }

    public void onProviderDisabled(String provider) {
        updateWithNewLocation(null);
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
};


}

其他活动:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Locale;

import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.gsm.SmsMessage;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.location.LocationManager;
import android.location.LocationListener;

public class FindAndroidActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button Nextbutton1, Nextbutton2, Nextbutton3, TestLocationService, EditSettings;
TextView Cordinates, Adress, FindAndroid, TextView;
EditText LocationWord;
private LocationManager locManager;
private LocationListener locListener;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.firsttimescreen);
       Nextbutton1 = (Button)findViewById(R.id.Nextbutton1);
       Nextbutton1.setOnClickListener(this);
}
public void onClick(View src) {
    switch(src.getId()) {
    case R.id.Nextbutton1:
        setContentView(R.layout.setup);
        Nextbutton2 = (Button)findViewById(R.id.Nextbutton2);
        TestLocationService = (Button)findViewById(R.id.TestLocationService);
        TestLocationService.setOnClickListener(this);
        Nextbutton2.setOnClickListener(this);
        break;
    case R.id.Nextbutton2:
        setContentView(R.layout.setup1);
        Nextbutton3 = (Button)findViewById(R.id.Nextbutton3);
        LocationWord = (EditText)findViewById(R.id.LocationWord);
        LocationWord.requestFocus(View.FOCUS_DOWN);
        Nextbutton3.setOnClickListener(this);
        break;
    case R.id.Nextbutton3:
        setContentView(R.layout.main);
        EditSettings = (Button)findViewById(R.id.EditSettings);
        EditSettings.setOnClickListener(this);
        break;
    case R.id.TestLocationService:
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            String value = extras.getString("KEY");             
        }
        Cordinates = (TextView)findViewById(R.id.Cordinates);
        Cordinates.setText(value);
            //This does not work because the string "value" isn't availible outside the braces,
            //obviously. How do i make it availible there???
        break;
    case R.id.EditSettings:
        setContentView(R.layout.setup1);
        Nextbutton3 = (Button)findViewById(R.id.Nextbutton3);
        LocationWord = (EditText)findViewById(R.id.LocationWord);
        LocationWord.requestFocus(View.FOCUS_DOWN);
        Nextbutton3.setOnClickListener(this);
        break;
    }
}

}

【问题讨论】:

标签: android android-activity location latitude-longitude


【解决方案1】:

在您的 LocationActivity 类中:

Intent i = new Intent(this, FindAndroidActivity.class);
i.putExtra("KEY",YourData);

在 FindAndroidActivity 类中

Bundle extras = getIntent().getExtras();
if(extras !=null) {
    String value = extras.getString("KEY");
}

【讨论】:

    【解决方案2】:

    几个场景:

    1. 如果您想在启动新活动时传递字符串,则将其添加到起始 Intent 并在新活动的onCreate 中检索。
      Sending arrays with Intent.putExtra

      // Sending activity  
      String latLong = "test";  
      Intent i = new Intent(sendingClass.this, receivingClass.class);  
      i.putExtra("latLong", latLong);  
      startActivity(i);  
      
      // Receiving activity  
      Bundle extras = getIntent().getExtras();  
      String latLong = extras.getString("latLong");  
      
    2. 如果您想在活动返回时传递字符串,则使用startActivityForResult 并实现onActivityResult 事件
      http://micropilot.tistory.com/1577

    3. 第三种情况,在同时运行的两个活动之间传递字符串是不可能的,因为一次只能运行一个活动(在前台)。

    【讨论】:

      【解决方案3】:

      有时,Intent 变得过于繁琐和烦人,相反,我使用了一种更简单(可能不是最佳)的设计模式:Singleton。 单例的工作方式就像一个通用存储盒,可以通过位于应用程序中任何位置的代码访问,在应用程序的生命周期处于活动状态时存储值。你也可以把方法放在那里。 单例是一个只能实例化一次的类,可以用作您需要从任何地方访问的所有变量的一站式仓库。您可以从任何活动或类,甚至上下文中设置/获取单例上的任何变量! 正如我所说,也许有更好的选择,但我没有时间用意图、空指针等来惩罚自己。 使用以下代码创建一个新类,将其命名为 mySingleton 或其他任何名称,然后开始从任何地方设置/获取变量!:

      public class MySingleton extends Application{ 
          private volatile static appSingleton mInstance = null;
          private String mystring;   
      
      private appSingleton(){  
         mystring="hello"; //initialize your var here
         //Add all the variables you need, here.
      public static MySingleton getInstance(){  //Singleton's core
              if(mInstance == null){
                  mInstance = new MySingleton();
                  }
              return mInstance;
              }
      
      //Place Set and Get methods here
      public String getMystring(){return this.mystring;}
      public void setMystring(String s){mystring = s;}
      //Add get/setmethods for your other variables here
      } //Thats it
      

      现在,假设您想在活动 B 上将 mystring 设置为“再见”,然后确实要这样做:

      MySingleton.getInstance().setMystring("hello");
      

      如果您想从任何其他 Activity、类等访问“mystring”并将其显示在文本框上,只需执行以下操作:

      MyTextBox.setText(MySingleton.getInstance().getMystring());
      

      如您所见,只需一行代码,您就可以在任何地方写入值并从任何地方读取这些值。享受吧!

      【讨论】:

      • MySingleton.getInstance().setMystring("hello"); 中,您提到将字符串设置为goodbye,我认为应该是MySingleton.getInstance().setMystring("goodbye");。我试过了,但我的字符串没有变成goodbye,它仍然是hello
      • @KamalpreetGrewal 说“hello”值只会在应用程序的生命周期中存在,这意味着如果您关闭应用程序或 Android 操作系统杀死您的应用程序,该值将消失。使用 sharedpreferences 使字符串“永久”保持。
      【解决方案4】:

      您的应用程序应该是多线程的吗?如果是这样的话,就会打开另一个蠕虫罐,来回解析数据就变成了一个非常有趣的杂耍。

      您是否研究过 putextra 和 getextra 函数?他们很好地在活动之间来回解析数据。虽然我不认为那些开箱即用的多线程应用程序效果很好。

      【讨论】:

        【解决方案5】:

        通常要遵循的最佳实践,我们可以说活动告诉您它期望调用者提供哪些额外参数。

        在您的 LocationActivity 类中:

        Intent i = new Intent(this, FindAndroidActivity.class);
        i.putExtra(FindAndroidActivity.EXTRA_KEY,YourData);
        

        在 FindAndroidActivity 类中

        //Declare this on top of all params
        public static final String EXTRA_KEY = "KEY";
        
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            String value = extras.getString(EXTRA_KEY);
        }
        

        【讨论】:

          猜你喜欢
          • 2011-05-24
          • 1970-01-01
          • 2014-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多