0

我需要将从“活动 A”创建的字符串传递给“活动 B”,以便可以在 TextView 中显示它。问题是代码导致Android没有响应,它与在线其他教程相同。

感谢您的任何反馈。

活动 A.onCreate()

check_button = (Button) findViewById(R.id.check_button);
    check_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            Intent i = new Intent(AddActivity.this, DetailActivity.class);
            String hash = text_hash.toString();
            i.putExtra("hash" , hash);
            startActivity(i);
        }
    });

活动 B.onCreate()

Bundle extras = getIntent().getExtras();
if (extras != null)
{
    passedHash = (String) getIntent().getExtras().getString("hash");
    hash.setText(passedHash);
}

堆栈跟踪:

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
4

4 回答 4

1

根据您的日志,您似乎没有在 Activity B 中初始化 TextView。在将文本设置为 TextView 之前执行此操作:

TextView hash = (TextView)findViewById(R.id.hash_textview);
于 2016-05-10T16:47:29.040 回答
0

如果text_hashTextViewEditText则使用使用

String hash = text_hash.getText().toString();

ActivityBonCreate() 使用这个:

String newString;
if (savedInstanceState != null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("hash");
    }
}

编辑 从您的错误日志中,您没有在 ActivityB 中初始化 TextView。首先,您必须初始化该 TextView,然后设置 Text。

于 2016-05-10T16:40:41.133 回答
0

好的,所以我需要使用 X.getText().toString(); 通过阅读堆栈跟踪,我发现在尝试设置文本之前,我还需要在 TextView 上找到 ViewByID。

谢谢阅读。

于 2016-05-10T16:48:22.783 回答
0

您的 textView 对象是空引用的,您需要在开始调用该 TextView 的任何方法之前在 oncreate 中初始化散列变量...

例子:

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    TextView hash = (TextView)findViewById(R.id.hash_textview);

之后,您可以调用 settext 方法

 hash.setText(passedHash);
于 2016-05-10T17:28:43.940 回答