在android中的活动之间传递字符串

时间:2012-01-05 19:21:34

标签: android android-activity location latitude-longitude

我搜索了很多地方,但我还没有找到任何有效的解决方案,我真的需要帮助! 我正在创建一个需要将经度和纬度字符串从一个活动传递到另一个活动的应用程序。 我怎样才能做到这一点???看看我的代码: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;
    }
}

}

5 个答案:

答案 0 :(得分:34)

在您的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");
}

答案 1 :(得分:9)

几种情景:

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

答案 2 :(得分:1)

有时候,意图变得过于繁琐和恼人,而我使用更简单(可能不是最佳)的设计模式: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设置为“goodbye”,然后想要这样做:

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

如果你想从任何其他的Activity,class等访问“mystring”......并将其显示在文本框上,只需这样做:

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

正如您所看到的,您可以在任何地方写入值,并使用一行代码从任何地方读取这些值。享受!

答案 3 :(得分:0)

您的应用程序应该是多线程吗?如果这样打开了另外一堆蠕虫并且来回解析数据变成了一个非常有趣的玩法。

您是否研究过putextra和getextra函数?它们在活动之间来回运行很好的解析数据。虽然我不认为它们可以很好地与多线程应用程序一起使用。

答案 4 :(得分:0)

通常遵循最佳实践,我们可以说活动告诉您期望呼叫者带来哪些额外参数。

在您的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);
}