小编典典

使用捆绑包将数据从一个活动传递到另一个活动-在第二个活动中不显示

json

我目前正在尝试获取通过REST
API调用获取的数据,将其解析为所需的信息,然后将该信息传递给新活动。我使用的是异步HTTP客户端从loopj.com为REST客户端,然后使用我下面的代码onClick,并onCreate为当前和未来的活动,分别。

Eclipse不会为我的任何代码传递任何错误,但是当我尝试在模拟器中运行时,当新的活动/视图打开时,我什么也没得到(即白屏)。我尝试在REST
CLIENT中使用其他URL进行编码,但仍然看不到任何内容。我甚至通过注释掉try / catch
onClick并更改venueNamebundle.putString("VENUE_NAME", venueName);来使API调用脱离方程式searchTerm。仍然会出现新视图,但什么也不会显示。没有通过什么,或者我忘记了使第二个活动显示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);
}

第二个活动中应接收意图并捆绑并显示它的方法:

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

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


阅读 228

收藏
2020-07-27

共1个答案

小编典典

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

//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)中,您key将Bundle称为,MainActivity.VENUE_NAME但代码中没有任何内容表明您有一个类,该类返回的值是key与Bundle一起发送的实际名称。将第二个活动中的代码更改为此:

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

您可以使用它在第二个活动中签入捆绑包中是否包含密钥,并且您会知道key捆绑包中不存在密钥。但是,上面的更正将使其为您工作。

if (bundle.containsKey(MainActivity.VENUE_NAME))    {
    ....
}
2020-07-27