【发布时间】:2018-09-28 12:34:03
【问题描述】:
有我的在我需要快点的时候花点时间的问题..
我只是打算将信息从我的主要活动转移到其他活动。 但数据不会转到其他活动。
请稍等片刻。
MainActivity.class
public class MainActivity extends AppCompatActivity {
public static final String KEY = "KEY";
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
intent.putExtra(KEY, "FONCTIONNE");
startActivity(intent);
});
}
}
OtherActivity.class
import static com.example.marguerite.experiences.MainActivity.KEY;
public class OtherActivity extends AppCompatActivity {
Button button;
TextView textView;
String text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
button = findViewById(R.id.button);
textView = findViewById(R.id.textview);
text = getIntent().getStringExtra(KEY);
textView.setText(text);
button.setOnClickListener(v ->finish());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.marguerite.experiences">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:fullBackupContent="@xml/backup_descriptor">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OtherActivity" />
</application>
</manifest>
错误事件
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.marguerite.experiences, PID: 8496
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.marguerite.experiences/com.example.marguerite.experiences.OtherActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.marguerite.experiences.OtherActivity.onCreate(OtherActivity.java:26)
at android.app.Activity.performCreate(Activity.java:7136)
就是这样。我当然忘记了一些东西,但我看过的所有教程都使用相同的简单技术。
【问题讨论】:
-
请发帖
activity_other.xml。看起来TextView在那里不存在。 -
将 textview id 更改为实际的。我认为复制粘贴错误
标签: java android android-intent error-handling