编辑,这是第一个活动的 完整 代码:
public class login extends AppCompatActivity {
dbhelper mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mydb = new dbhelper(this);
Button btn = (Button) findViewById(R.id.Buttonregis);
btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent i = new Intent(login.this,Reg.class);
startActivity(i);
}
});
Button lgn = (Button) findViewById(R.id.btlogin);
lgn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//AMBIL CONTENT EDIT_TEXT
EditText txtusername = (EditText)findViewById(R.id.ETusername);
EditText txtpassword = (EditText)findViewById(R.id.ETpassword);
//CONVERT EDIT_TEXT MENJADI STRING
String user = txtusername.getText().toString();
String pass = txtpassword.getText().toString();
//PANGGIL FUNGSI VALIDasi DARI kelas dbhelper
if(mydb.checkvalid(user,pass) == true){
Intent i = new Intent(login.this,Menu.class);
i.putExtra("nama",user);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(), "Wrong ID/password", Toast.LENGTH_SHORT).show();
}
}
});
编辑,这是我从第二个活动中撤出的方式:
public class Menu extends AppCompatActivity {
dbhelper mydb;
Intent intent = getIntent();
String user = intent.getExtras().getString("nama");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Button babout = (Button) findViewById(R.id.btabout);
babout.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent about = new Intent(Menu.this,About.class);
startActivity(about);
}
});
Button bprofile = (Button) findViewById(R.id.btprofile);
bprofile.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent profile = new Intent(Menu.this,Profile.class);
//profile.putExtra("bknnama",user);
startActivity(profile);
}
});
//select
Button bcheck = (Button) findViewById(R.id.btcheck);
bcheck.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent check = new Intent(Menu.this,Reg.class);
startActivity(check);
}
});
Button bnovel = (Button) findViewById(R.id.btnovel);
bnovel.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent about = new Intent(Menu.this,Novel_list.class);
startActivity(about);
}
});
}
} 系统声明没有错误,但是当我打开应用程序并按相应的按钮进入另一个活动时,我的应用程序被迫关闭。
当我将Intent代码放入注释时,该应用程序再次可以正常运行,但是我需要将用户字符串传递给另一个活动。
编辑 这是logcat的回复
由于:java.lang.NullPointerException:尝试调用虚拟 方法'android.os.Bundle android.content.Intent.getExtras()'在 空对象引用
答案 0 :(得分:0)
代码错误。您必须在OnCreate方法中获得意图:
{{1}}
希望有帮助。关于Cs
答案 1 :(得分:-1)
从此更改代码
Intent intent = getIntent();
String user = intent.getExtras().getString("nama");
到
Intent intent = getIntent();
String user = intent.getStringExtra("nama");
答案 2 :(得分:-3)
确保在AndroidManifest.xml中声明了Menu.class