2012-01-05 32 views
9

Tôi đã tìm kiếm khá nhiều địa điểm nhưng tôi chưa từng tìm ra giải pháp nào hiệu quả, và tôi thực sự cần trợ giúp! Tôi đang tạo một ứng dụng cần truyền một chuỗi kinh độ và vĩ độ từ hoạt động này sang hoạt động khác. Làm cách nào tôi có thể thực hiện việc này ??? Hãy xem mã của tôi ở đây: LocationActivity.java cần truyền chuỗi cho hoạt động khác và một chuỗi khác mà tôi không dán vào đây. Và chuỗi mà cần phải được thông qua được đặt tên: "latLongString"Truyền chuỗi giữa các hoạt động trong android

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) { 
    } 
}; 


} 

Các hoạt động khác:

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; 
    } 
} 

}

+1

Bạn nên sử dụng putExtra() và chức năng getExtras() (hoặc getString) từ tiếp cận mục đích hạng trả lời ở đây: [PutExtra/GetExtra] [1] [1]: http: // stackoverflow. com/questions/5265913/how-to-use-putextra-and-getextra-cho-chuỗi-dữ liệu –

Trả lời

33

Trong lớp LocationActivity của bạn:

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

Trong lớp FindAndroidActivity

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

Couple của kịch bản:

  1. Nếu bạn muốn chuyển chuỗi khi bạn bắt đầu hoạt động mới, sau đó thêm nó vào Intent bắt đầu và truy xuất nó trong hoạt động mới 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. Nếu bạn muốn vượt qua chuỗi khi bạn trở về từ một hoạt động, sau đó sử dụng startActivityForResult và thực hiện các sự kiện onActivityResult
    http://micropilot.tistory.com/1577

  3. Kịch bản thứ 3, đi qua các chuỗi giữa hai các hoạt động chạy cùng một lúc là không thể vì chỉ có một hoạt động có thể chạy (ở phía trước) tại một thời điểm.

0

là ứng dụng của bạn phải được đa luồng? Nếu như vậy sẽ mở ra một toàn bộ các sâu và phân tích cú pháp dữ liệu khác nhau sẽ trở thành một cuộc đấu tranh khá thú vị.

Bạn đã xem xét các hàm putextra và getextra chưa? Họ làm việc phân tích dữ liệu tuyệt vời qua lại giữa các hoạt động. Mặc dù tôi không nghĩ rằng những người làm việc tốt với các ứng dụng đa luồng ra khỏi hộp.

1

Đôi khi, Mục đích trở nên quá cồng kềnh và khó chịu, thay vào đó tôi sử dụng mẫu thiết kế dễ dàng hơn (có thể không tối ưu): Singleton. Một singleton hoạt động giống như một hộp lưu trữ chung có thể truy cập được bằng mã nằm ở bất kỳ đâu trong ứng dụng của bạn, nơi các giá trị được lưu trữ trong khi vòng đời của ứng dụng đang hoạt động. Bạn cũng có thể đặt các phương thức ở đó. Một singleton là một lớp chỉ có thể được khởi tạo một lần, và có thể được sử dụng như một kho của bạn cho tất cả các biến mà bạn cần truy cập từ mọi nơi. Bạn có thể đặt/nhận bất kỳ biến nào trên singleton từ bất kỳ hoạt động hoặc lớp học nào, ngay cả ngữ cảnh! Như tôi đã nói có thể có những lựa chọn tốt hơn, nhưng tôi không có thời gian để trừng phạt bản thân mình với ý định, con trỏ null và những gì không. Tạo một lớp mới với mã sau, gọi nó là mySingleton hoặc bất kỳ thứ gì và bắt đầu cài đặt/nhận các biến từ mọi nơi!:

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ây giờ, cho phép nói rằng bạn muốn thiết lập mystring để "tạm biệt" trên Hoạt động B, sau đó muốn làm điều này:

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

Nếu bạn muốn truy cập "mystring" từ bất kỳ khác hoạt động, giai cấp, vv ... và hiển thị nó trên một textbox chỉ làm điều này:

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

Như bạn thấy, bạn có thể viết giá trị bất cứ nơi nào và đọc những giá trị đó từ bất cứ nơi nào, với một dòng mã. Thưởng thức!

+0

Trong 'MySingleton.getInstance(). setMystring (" hello ");' đó là nơi bạn đang đề cập đến thiết lập chuỗi để 'goodbye', tôi nghĩ nó nên là' MySingleton.getInstance(). setMystring ("goodbye"); '. Tôi đã thử điều này nhưng chuỗi của tôi không thay đổi thành 'goodbye', nó vẫn là' hello'. –

+0

@KamalpreetGrewal rằng giá trị "hello" sẽ chỉ tồn tại qua vòng đời của ứng dụng, điều đó có nghĩa là nếu bạn đóng ứng dụng hoặc hệ điều hành Android giết ứng dụng của bạn, giá trị đó sẽ biến mất. Sử dụng sharedpreferences để làm cho chuỗi tồn tại "vĩnh viễn". – Josh

Các vấn đề liên quan