我得到"尝试调用虚方法' android.text.Editable android.widget.EditText.getText()'在null对象引用"每当我点击按钮。请帮忙
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.edit);
b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
}
})
}
String tt(){
return (edt.getText()+"");
}
public class Main2Activity extends AppCompatActivity {
MainActivity ob = new MainActivity();
private WebView mywebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mywebview=(WebView)findViewById(R.id.abc);
WebSettings webSettings=mywebview.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebview.loadUrl(ob.tt());
mywebview.setWebViewClient(new WebViewClient());
}
}
答案 0 :(得分:1)
MainActivity ob = new MainActivity();
会为您提供此类的简单对象,而不是当前正在运行的实际对象,因此ob
在这种情况下无效,删除ob
相关代码并使用{{1}传递数据
在第一个Intent
MainActivity
在 b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("data",edt.getText().toString());
// ^^^^ pass data
startActivity(i);
}
})
Main2Activity
另请阅读How do I pass data between Activities in Android application?