gpt4 book ai didi

java - Intent 问题

转载 作者:行者123 更新时间:2023-12-02 03:14:34 25 4
gpt4 key购买 nike

我在 Intents 方面遇到了一些困难,但我在这段代码中不断收到错误。我不断收到致命异常..

 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.bac1.problemcodereference/com.example.bac1.problemcodereference.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference 

我的项目代码:

public class MainActivity extends AppCompatActivity implements Serializable    {
private String cPcode;
Button help , sub;
EditText codetext;
Intent intent = new Intent (this, Main2Activity.class);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sub = (Button) findViewById(R.id.submit);
help = (Button) findViewById(R.id.help);



sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = codetext.getText().toString();
MainActivity onew = new MainActivity();
onew.setcPcode(text);
intent.putExtra("stuff",onew);
startActivity(intent);
}
});}

最佳答案

在这一行

Intent intent = new Intent (this, Main2Activity.class);

您的 Activity 尚未完全构建,因此请在 oncreate 函数之后或内部使用此调用,因为 this 意味着 context 将为 null 因此出现异常

所以会这样

public class MainActivity extends AppCompatActivity implements Serializable    {
private String cPcode;
Button help , sub;
EditText codetext;
Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent (this, Main2Activity.class);
sub = (Button) findViewById(R.id.submit);
help = (Button) findViewById(R.id.help);



sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = codetext.getText().toString();
MainActivity onew = new MainActivity();
onew.setcPcode(text);
intent.putExtra("stuff",onew);
startActivity(intent);
}
});}

另一个问题是为什么要传递 mainActivity 的新对象,所以更好的选择是创建一个单独的 POJO 类并使用它来存储数据

关于java - Intent 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40493912/

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