使用Bundle将数据从一个活动传递到另一个活动-在第二个活动中未显示

19

我目前正在尝试通过REST API调用获取数据,解析我需要的信息,然后将该信息传递给新活动。我使用loopj.com的Asynchronous HTTP Client作为REST客户端,然后对当前和未来的活动分别使用下面的代码作为我的onClickonCreate

Eclipse没有报告任何代码错误,但当我尝试在模拟器中运行时,新活动/视图打开时我什么也看不到(即空白屏幕)。我已经尝试在REST CLIENT中使用不同的URL进行编码,但仍然没有显示任何内容。我甚至通过在onClick中注释掉try/catch并将bundle.putString("VENUE_NAME", venueName);中的venueName更改为searchTerm来排除了API调用的影响。然而,新视图出现了,但没有任何内容显示。是什么没有被传递,或者我忘记了什么让第二个活动显示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);
}

第二个活动中应接收意图和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);
    }
}

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

8个回答

31

你可以使用两种方式发送数据。目前你正在使用的就是其中一种方式,这样做没有任何问题。

//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,但是代码中没有任何提示你有一个类可以返回实际的key名称与Bundle一起发送的值。请将第二个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,从而知道 Bundle 中没有该 key。但是上面的更正将使其对您起作用。

您可以在第二个 Activity 中使用以下代码检查 Bundle 是否包含 key,从而知道 Bundle 中没有该 key。但是上述纠正方法可以使其正常工作。

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

1
这是一个非常精炼但又详细的答案。感谢您清晰地写出来。它帮助我快速理解如何使用bundles。 - raddevus
谢谢。这个例子对我很有帮助。 - Edwinfad

5

I think if you replace

String venName = bundle.getString(MainActivity.VENUE_NAME); 

使用

String venName = bundle.getString("VENUE_NAME");

应该可以正常工作。

以下是我处理从一个活动到另一个活动的数据传输的方法:

将数据发送给名为“Projectviewoptions”的活动:

Bundle b = new Bundle();
          b.putString("id", str_projectid);
          Projectviewoptions pv = new Projectviewoptions();

接收数据:

idbundle = getArguments();
String myid = idbundle.getString("id");

"key"的值在两个端点必须相同;在这种情况下,是"id"。
通过intent发送数据的另一种方法是:
发送:
Intent intent = new Intent(getActivity(),ViewProjectDetails.class);
                            intent.putExtra("id", myid);
                            startActivity(intent);

接收:

String id = getIntent().getExtras().getString("id");

4
你在错误地访问你已经添加到bundle中的key。除了使用MainActivity.VENUE_NAME来获取字符串,尝试直接传递你在bundle中添加的key名称,如下所示:
除了以下方式获取字符串:
   //Get the bundle
     Bundle bundle = getIntent().getExtras();
    //Extract the data…
   String venName = bundle.getString(MainActivity.VENUE_NAME);        

尝试按以下键名获取字符串:

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

1
发送捆绑包。
Bundle bundle = new Bundle();
bundle.putString("Name",Object); //This is for a String
i.setClass(CurrentClass.this, Class.class);
i.putExtras(bundle);
startActivity(i);

接收捆绑包

Bundle bundle = null;
bundle = this.getIntent().getExtras();
String myString = bundle.getString("Name");//this is for String  

这里的 "i" 是什么?请解释一下它的含义。 - Ashish Shahi
如果您定义了Intent i = new Intent();,而且已经尝试过这个方法,请解释一下您的答案。 - Ashish Shahi

0
package com.example.mytest;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import static com.example.mytest.MainActivity.STATIC_VARIABLE;

public class MainActivity2 extends AppCompatActivity {
   EditText editText1;
    Button button1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        editText1 = (EditText) findViewById(R.id.editText1);
        button1 = (Button) findViewById(R.id.button1);
        Bundle extras=null;
         extras=this.getIntent().getExtras();
        if(extras!=null) {
          String recieved =extras.getString("TAG");
          editText1.setText(String.valueOf(recieved));
        }
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
  Intent backIntent = new Intent(MainActivity2.this, MainActivity.class);
                String input= editText1.getText().toString();
                backIntent.putExtra("TAG2",input);
               STATIC_VARIABLE=3;
//    setResult(RESULT_OK,intent);
//                startActivityForResult(intent, 2);
                startActivity(backIntent);


            }
        });
    }


    }

0

确保您用作将项目放入Bundle中的键的字符串与用于提取它的键相同。在您的情况下,也许MainActivity.VENUE_NAME与"VENUE_NAME"不同。


0

没有必要使用Bundle来传递字符串(或任何原始数据类型)。
您可以在调用活动中使用i.putExtra("key", "value");,并在被调用的活动中使用
String s = getIntent().getStringExtra("key");


0
Intent loginIntent = new Intent(LoginActivity.this, HomeActivity.class);

Bundle bundle = new Bundle(); 


bundle.putString("user_id", userId);

i.putExtras(bundle);

startActivity(loginIntent);

LoginActivity.this.finish();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接