I want my app to take username form user inside the first AlertDialog and publish it on the second AlertDialog, but my app crashes when I add this line of code: txt.setText(edt.getText().toString());. It is supposed to change textview to edittext value which was given on the first AlertDialog. Here are the errors.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.myapplication.MainActivity.Alert01(MainActivity.java:73)
at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:62)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
EditText edt;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
edt = (EditText) findViewById(R.id.edit_username);
txt = (TextView) findViewById(R.id.text02);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
Alert();
}
public void Alert () {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.MyDialogTheme);
View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog0, null);
builder.setMessage("Welcome ! ");
builder.setView(v);
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Alert01();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void Alert01 (){
txt.setText(edt.getText().toString());
AlertDialog.Builder builder01 = new AlertDialog.Builder(MainActivity.this,R.style.MyDialogTheme);
View v01 = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog1,null);
builder01.setView(v01);
builder01.setTitle("Congratulations ! ");
AlertDialog alert = builder01.create();
alert.show();
}
}
Move This Line inside Alert() Method after inflating layout
edt = (EditText) v.findViewById(R.id.edit_username);
Also Modify Alert01() Method
AlertDialog.Builder builder01 = new AlertDialog.Builder(MainActivity.this,R.style.MyDialogTheme);
View v01 = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog1,null);
builder01.setView(v01);
txt = (TextView) v01.findViewById(R.id.text02);
txt.setText(edt.getText().toString());