gpt4 book ai didi

android - 使用 bundle 将数据从一个 Activity 传递到另一个 Activity - 不在第二个 Activity 中显示

转载 作者:IT老高 更新时间:2023-10-28 23:30:19 26 4
gpt4 key购买 nike

我目前正在尝试获取通过 REST API 调用获取的数据,将其解析为我需要的信息,然后将该信息传递给新的 Activity 。我将 loopj.com 的异步 HTTP 客户端用于 REST 客户端,然后分别将以下代码用于我的 onClickonCreate 用于当前和 future 的 Activity .

Eclipse 没有为我的任何代码传递任何错误,但是当我尝试在模拟器中运行时,当新的 Activity/ View 打开时,我什么也得不到(即空白屏幕)。我尝试在我的 REST CLIENT 中使用不同的 URL 进行编码,但我仍然什么也看不到。我什至通过注释掉 onClick 中的 try/catch 并更改 bundle.putString("VENUE_NAME",venueName 中的 venueName 来取消 API 调用);searchTerm。尽管如此,新 View 仍然出现,但没有显示任何内容。什么没有通过,或者我忘记让第二个 Activity 显示 venueName 什么?

public void onClick(View view) {
Intent i = new Intent(this, ResultsView.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String searchTerm = editText.getText().toString();


//call the getFactualResults method
try {
getFactualResults(searchTerm);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("VENUE_NAME", venueName);
//Add the bundle to the intent
i.putExtras(bundle);

//Fire the second activity
startActivity(i);
}

第二个 Activity 中的方法应该接收 Intent 并 bundle 并显示它:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//Get the message from the intent
//Intent intent = getIntent();
//String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

//Get the bundle
Bundle bundle = getIntent().getExtras();

//Extract the data…
String venName = bundle.getString(MainActivity.VENUE_NAME);

//Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(venName);

//set the text view as the activity layout
setContentView(textView);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}

感谢您的帮助。非常感谢。

最佳答案

您可以通过两种方式发送数据。这就是您目前发送它的方式。而且也没有错。

//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("VENUE_NAME", venueName);
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);

但是,在您的代码(第二个 Activity )中,您将 Bundle 中的 key 称为 MainActivity.VENUE_NAME 但代码中没有任何内容表明您有一个类它将值作为与 Bundle 一起发送的实际 key 名称返回。将第二个 Activity 中的代码更改为:

Bundle bundle = getIntent().getExtras();

//Extract the data…
String venName = bundle.getString("VENUE_NAME");

//Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(venName);

如果 Bundle 包含使用此 key 的 key ,您可以 checkin 您的第二个 Activity,并且您将知道 key 不存在于 Bundle 中。然而,上面的更正会让它为你工作。

if (bundle.containsKey(MainActivity.VENUE_NAME))    {
....
}

关于android - 使用 bundle 将数据从一个 Activity 传递到另一个 Activity - 不在第二个 Activity 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15445182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com