[英]Problems sending data from one activity to another with application
就像標題中所說的,我要傳輸數據,在這種情況下,是用戶在EditText
和Spinner
上引入的信息,從一個活動轉移到另一個活動。
我正在看一本書中的教程,但是它不起作用(我認為它不完整)。 程序代碼如下:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.location=(EditText)findViewById(R.id.location);
this.cuisine=(Spinner)findViewById(R.id.cuisine);
this.grabReviews=(Button)findViewById(R.id.get_reviews_button);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.cuisine, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.cuisine.setAdapter(adapter);
this.grabReviews.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
handleGetReviews();
}
}
);
}
private void handleGetReviews() {
RestaurantsActivity application= (RestaurantsActivity) getApplication();
application.setReviewCriteriaCuisine(this.cuisine.getSelectedItem().toString());
application.setReviewCriteriaLocation(this.location.getText().toString());
Intent intent=new Intent(Constants.INTENT_ACTION_VIEW_LIST);
startActivity(intent);
}
上面的代碼不起作用。 我不明白四件事:
RestaurantsActivity
必須是實際的活動嗎?
-在互聯網上看到的所有示例中,都有一個應用程序擴展類,在此示例中沒有。
setReviewCriteria
函數丟失
-where確實Constants.INTENT_ACTION_VIEW_LIST
從何而來?
因此,您的目標是將數據發送到Restaurantsactivity? 通常,Android中的數據通過使用Intent從一個活動移交給另一個活動。
因此,首先您要創建一個意圖。 然后,使用intent.putExtra()方法將要傳輸的數據放入意圖中。 在獲取意圖的活動中,您可以使用getIntent()。getExtra()方法獲取數據(getExtra可以類似於getStringExtra()之類)。
這是一個名為“名稱”的編輯框的小示例:
public void onCreate(Bundle iBundle){
//do some stuff here
//perhaps define some Buttos and so on
//now lets start the activity
Intent intent = new Intent(currentActivityname.this, ActivityYouWantToStart.class);
intent.putExtra("name", name.getText().toString())
startActivity(intent); // you can also start an startActivityForResult() here :)
}
在接收活動中,您現在可以處理意圖(例如,在onCreate()方法中)
public void onCreate(Bundle iBundle){
String name = this.getIntent().getStringExtra("name",some default value);
}
嘗試將數據放入Bundle並使用此Bundle啟動Activity
Intent intent = new Intent(this, YourSecondActivity.class);
intent.putExtra(... HERE YOUR BUNDLE WITH DATA ...);
startActivity(intent);
希望對您有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.