Inflate Layout to alert dialog android studio - java

I have the following method where I am trying to inflate layout in altert dialog but nothing happen. I am building todo app and i want to show dialog when i click on add image button.
I need your help to fix that problem.
Any help would be greatly appreciated :)
imageButton.setOnClickListener(v -> {
Toast.makeText(MainActivity.this, "Button add clicked ", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewInput = inflater.inflate(R.layout.note_input,null,false);
EditText editTitle = viewInput.findViewById(R.id.edit_text);
EditText editDescription = viewInput.findViewById(R.id.edit_description);
new AlertDialog.Builder(MainActivity.this)
.setView(viewInput)
.setTitle("Add Note")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = editTitle.getText().toString();
String description = editDescription.getText().toString();
Note note = new Note(title,description);
boolean isInserted = new NoteHandler(MainActivity.this).create(note);
if(isInserted){
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
loadNotes();
}
else{
Toast.makeText(MainActivity.this, "Unable to save the note", Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
});
});
XML FILE
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Note title"
app:layout_constraintBottom_toTopOf="#+id/edit_description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/edit_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:hint="Note description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

new AlertDialog.Builder(MainActivity.this)
.setView(viewInput)
.setTitle("Add Note")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = editTitle.getText().toString();
String description = editDescription.getText().toString();
Note note = new Note(title,description);
boolean isInserted = new NoteHandler(MainActivity.this).create(note);
if(isInserted){
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
loadNotes();
}
else{
Toast.makeText(MainActivity.this, "Unable to save the note", Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
}).show();//Need to ad .show() right here

Related

Custom dialog not showing properly in other devices

So I am developing one android application in which I have created one custom dialog box. but the problem arises that, this dialog box is showing correct in my phone and on emulator also. But it can't get display properly on redmi or other phones.
Here is screenshot on my mobile device
and [![On other device][2]][2]
On other device
[2]: https://i.stack.imgur.com/b3H4J.jpg
Here is my code:-
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFF538"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Would you like to continue"
android:textColor="#color/black"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/bld"
android:layout_width="269dp"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<EditText
android:id="#+id/txt_input"
android:layout_width="382dp"
android:layout_height="69dp"
android:layout_marginTop="10dp"
android:background="#drawable/back"
android:hint="Why are you sending this request?"
android:maxLength="100"
android:textSize="20sp" />
<!-- In given textview we have used maxlength =100
because we have to display small information so we use limited characters.-->
<TextView
android:layout_width="wrap_content"
android:layout_height="117dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="11dp"
android:text="Your request will display publicly in blood request section.And if your any request is present in Blood Request will be deleted"
android:textColor="#FF0303"
android:textSize="20dp" />
<Button
android:id="#+id/btn_okay"
android:layout_width="134dp"
android:layout_height="60dp"
android:layout_weight="0"
android:layout_marginTop="10dp"
android:backgroundTint="#color/black"
android:text="yes"
android:textColor="#ffffff"
android:textSize="18sp" />
<Button
android:id="#+id/btn_cancel"
android:layout_width="136dp"
android:layout_height="60dp"
android:layout_gravity="right"
android:layout_marginTop="-58dp"
android:layout_weight="0"
android:backgroundTint="#color/black"
android:gravity="center"
android:text="no"
android:textColor="#ffffff"
android:textSize="18sp" />
</LinearLayout>
donor.java
private void alertDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(Bloodbank.this);
View mView = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
Button btn_cancel = (Button) mView.findViewById(R.id.btn_cancel);
Button btn_okay = (Button) mView.findViewById(R.id.btn_okay);
TextView bld = (TextView) mView.findViewById(R.id.bld);
bld.setText("selected blood group is "+item);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Request dismissed", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
SQLiteDatabase db = dbHandler.getWritableDatabase();
String sql1 = "delete from request where time < date('now','-2 day') AND Username = '" + MainActivity.getValue() + "'";
db.execSQL(sql1);
String sql = "select Name,contactNo from request where Username = '" + MainActivity.getValue() + "'";
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "your request is pending. Please delete that first.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
while (cursor.moveToNext());
}
catch (Exception e) {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "Please select blood group first", Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
}
});
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
}
Try to change these lines
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
With these line
int width = (int) (getResources().getDisplayMetrics().widthPixels * 0.90);
int height = (int) (getResources().getDisplayMetrics().heightPixels * 0.60);
if (alertDialog.getWindow() != null) {
alertDialog.getWindow().setLayout(width, height);
}
alertDialog.show();

Error Messages not showing inside Alert Dialog Box

I would like to show an error message within an alert dialog box for password reset, however no error message shows inside the dialog pop up.
Alert Dialog Box
When clicking "Reset" the dialog box will close. However, entering in a valid email does show the toast message "Reset Email Sent"
The validations are 1) leaving the email address empty , 2)not giving a proper email
Login.java
//onclick for forgot password
forgotPText = findViewById(R.id.forgotPassText);
forgotPText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start alert dialog
View view = inflater.inflate(R.layout.reset_popup,null);
reset_alert.setTitle("Forgot Password ?")
.setMessage("Enter Email For Password Reset Link.")
.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//validate the email address is not empty or not valid email
EditText email = view.findViewById(R.id.reset_popup_Email);
String emailChar = email.getText().toString();
if (email.getText().toString().isEmpty()){
email.setError("Required Field!");
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()){
email.setError("Please provide valid email!");
email.requestFocus();
return;
}
//send reset link
firebaseAuth.sendPasswordResetEmail(email.getText().toString())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//FirebaseUser user = firebaseAuth.getCurrentUser();
//updateUI(user);
Toast.makeText(LoginActivity.this
, "Reset Email Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}).setNegativeButton("Cancel",null)
.setView(view)
.create().show();
}
});
Use this code:
forgotPText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start alert dialog
LayoutInflater inflater = getLayoutInflater();
AlertDialog.Builder reset_alert = new AlertDialog.Builder(MainActivity.this);
View view = inflater.inflate(R.layout.reset_popup,null);
reset_alert.setView(view);
EditText email = view.findViewById(R.id.email);
TextView tv_cancel = view.findViewById(R.id.tv_cancel);
TextView tv_submit = view.findViewById(R.id.tv_submit);
tv_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
new Handler().postDelayed(new Runnable() {
#Override
public void run() { alertDialog.dismiss(); }}, 200);
}
});
email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
tv_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
String emailChar = email.getText().toString();
if (email.getText().toString().isEmpty()){
email.setError("Required Field!");
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()){
email.setError("Please provide valid email!");
email.requestFocus();
return;
}
//send reset link
firebaseAuth.sendPasswordResetEmail(email.getText().toString())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//FirebaseUser user = firebaseAuth.getCurrentUser();
//updateUI(user);
Toast.makeText(LoginActivity.this
, "Reset Email Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
});
alertDialog = reset_alert.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
});
//////// reset_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/reset_alert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Forgot Password?"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/des"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:textColor="#color/black"
android:text="Enter Email For Password Reset Link."
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/reset_alert" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Email Address"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/des" />
<TextView
android:id="#+id/tv_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Cancel"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/tv_submit"
app:layout_constraintTop_toBottomOf="#+id/email" />
<TextView
android:id="#+id/tv_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_marginEnd="353dp"
android:text="Reset"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email" />
</androidx.constraintlayout.widget.ConstraintLayout>

is there a way to interact with a custom layout inflated in an Alert Dialog?

I have a code which inflates a custom layout inside an Alert Dialog.
The Custom Layout consists of an EditText and a Button. What is the correct way to display the EditText String inside a Toast by clicking the Button ?
I have tried the below code but it doesn't seem to work.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("Fetch", (dialog, which) -> {
}).setNeutralButton("Cancel", (dialog, which) -> {
});
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.custom_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.show();
dialog.setOnShowListener(d -> {
EditText dialogNameEditText = dialog.findViewById(R.id.dialog_name_edittext);
Button dialogPrintButton = dialog.findViewById(R.id.dialog_print_button);
dialogPrintButton.setOnClickListener(v1 -> {
Toast.makeText(
TestActivity.this,
dialogNameEditText.getText().toString(),
Toast.LENGTH_SHORT
).show();
});
});
custom_layout.xml file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/dialog_name_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorDark"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:padding="10dp"
android:textColor="#color/colorWhite"
android:textColorHint="#color/colorLight" />
<Button
android:id="#+id/dialog_print_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:text="Print"
android:textColor="#color/colorLight" />
</LinearLayout>
Originally answered
Create a separate function for toast
public void show_toast(){
Toast.makeText(
TestActivity.this,
dialogNameEditText.getText().toString(),
Toast.LENGTH_SHORT
).show();
}
and in onclicklistener call it
dialog.setOnShowListener(d -> {
EditText dialogNameEditText = dialog.findViewById(R.id.dialog_name_edittext);
Button dialogPrintButton = dialog.findViewById(R.id.dialog_print_button);
dialogPrintButton.setOnClickListener(v1 -> {
show_toast();
});
});
Try this simple code. it will work.
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_layout);
EditText dialogNameEditText = dialog.findViewById(R.id.dialog_name_edittext);
Button dialogPrintButton = dialog.findViewById(R.id.dialog_print_button);
dialogPrintButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,dialogNameEditText.getText(), Toast.LENGTH_SHORT).show();
}
});
dialog.show();

Exception When handling Custom AlertDialog with ButterKnife

Hello guys iam realy Confused i spent over 17 hours try to fix this Problem but
No hope
Am try to show Custom Dialog with > AlertDialog.Builder when i Click Button but when i run the App and click the button it gives me this Exception
i tried ButterKnife #OnClick Anotation and Casting the Item Inside the Dialog Function like Button item = findviewById(R.id.ItemID);
i search for questions has same problem like mine but useless till i found
this question Multiple injections but i found that its really very old May 29, 2014
The Exception
05-23 21:15:56.630 8769-8769/com.w4ma.soft.tamenly E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.w4ma.soft.tamenly, PID: 8769
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost.ShowCommentDialog(ShowThePost.java:133)
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost.onClick(ShowThePost.java:159)
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost_ViewBinding$1.doClick(ShowThePost_ViewBinding.java:52)
at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6221)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Here is my code
ShowThePost.java
#Nullable #BindView(R.id.priceSuggested) EditText txtSuggestprice;
#Nullable #BindView(R.id.txtnotes) EditText txtNotes;
#Nullable #BindView(R.id.btnClose) Button btnclose;
#Nullable #BindView(R.id.btnCommentDone) Button btndone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_the_post);
ButterKnife.bind(this);
}
public void ShowCommentDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
view = getLayoutInflater().inflate(R.layout.create_comment,null);
alert.setCancelable(false);
alert.setView(view);
final AlertDialog dialog = alert.create();
// final Dialog dialog = new Dialog(context);
// dialog.setContentView(R.layout.create_comment);
// dialog.setCancelable(false);
// dialog.setTitle("This is Dialog");
// EditText txtSuggestprice = findViewById(R.id.priceSuggested);
// EditText txtNotes = findViewById(R.id.txtnotes);
// Button btnDonee = (Button)findViewById( R.id.btnCommentDone);
// Button btnClosee =(Button)findViewById(R.id.btnClose);
//
// btndone.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
//
// }
// });
// btnclose.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// dialog.dismiss();
//
// }
// });
final String Notes = txtNotes.getText().toString();
final String Description = txtSuggestprice.getText().toString();
alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toasty.success(context,"Done" + Notes + Description, Toast.LENGTH_LONG).show();
}
}).setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
btndone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
});
btnclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Closed", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
#OnClick(R.id.fabComment)
public void ShowDialog(){
ShowCommentDialog();
}
CreatComment.xml this is the Custom Dialog which should Inflate to the Dialog
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="#dimen/_12sdp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Comment"
android:textSize="#dimen/_22sdp"
android:textColor="#000"
android:textAlignment="center"
android:layout_margin="#dimen/_9sdp"
android:typeface="serif"/>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:background="#color/lightgray"
android:padding="#dimen/_4sdp"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_4sdp">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/priceSuggested"
android:layout_margin="#dimen/_5sdp"
android:hint="Suggest Price"
android:inputType="number"
android:typeface="serif"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_4sdp">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/_5sdp"
android:hint="Notes"
android:id="#+id/txtnotes"
android:typeface="serif"/>
</android.support.design.widget.TextInputLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Done"
android:background="#drawable/btncommentstyle"
android:id="#+id/btnCommentDone"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close"
android:layout_marginTop="#dimen/_4sdp"
android:background="#drawable/btncommentstyle"
android:id="#+id/btnClose"/>
</LinearLayout>
</android.support.v7.widget.CardView>
The exception is caused by this line:
final String Notes = txtNotes.getText().toString();
As described in the reason, the txtNotes member is null, which means that the binding did not work (probably the view with txtnotes id was not found).
From what I see, you call ButternKnife.bind() for the activity which has the activity_show_the_post layout as content view. But the view with txtnotes id is actually in the create_comment layout, of which ButterKnife knows nothing about, and doesn't even exist at that time. Thus, the binding fails, no reference to txtnotes is created and you later get a NPE.
You need to bind the views for create_comment.xml too
view = getLayoutInflater().inflate(R.layout.create_comment,null);
Butterknife.bind(view,this);
alert.setCancelable(false);
alert.setView(view);
final AlertDialog dialog = alert.create();

How to make a "Don't show this warning message again " dialog pop-up box

I'm trying to create an Dialog to show an introduction message in my application, with a "Don't show this again" CheckBox below it.
I do not know how to make code.
<MainActivity.java>
#Override
protected void onStart()
{
super.onStart();
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Warning!");
Button button = (Button) dialog.findViewById(R.id.okay);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
This is my java code
and this is my layout.xml code
<dialog.xml>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10.0dip" >
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/brick_warning"
android:textSize="15dp" />
</RelativeLayout>
<CheckBox
android:id="#+id/dont_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dont_show"
android:textSize="13dp" />
<LinearLayout
style="?android:attr/buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/okay"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/dialog_continue" />
</LinearLayout>
</LinearLayout>
have a great day :)
Hai sorry for late answer but in your problem
you can easily solve it using shared preferences
heres the link:
and the code:
AlertDialog.Builder adb= new
AlertDialog.Builder(this);
LayoutInflater adbInflater =
LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate
(R.layout.activity_main, null);
check = (CheckBox)
eulaLayout.findViewById(R.id.skip);
adb.setView(eulaLayout);
adb.setTitle("Example:");
adb.setMessage(Html.fromHtml("Type your
text here: "));
adb.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface
dialog, int which) {
String checkBoxResult = "NOT
checked";
if (check.isChecked())
checkBoxResult = "checked";
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor
editor = settings.edit();
editor.putString("noshow",
checkBoxResult);
// Commit the edits!
// sunnovalthesis();
editor.commit();
return;
} });
adb.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface
dialog, int which) {
String checkBoxResult = "NOT
checked";
if (check.isChecked())
checkBoxResult = "checked";
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor =
settings.edit();
editor.putString("noshow",
checkBoxResult);
// Commit the edits!
// sunnovalthesis();
editor.commit();
return;
} });
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
String noshow = settings.getString
("noshow", "NOT checked");
if (noshow != "checked" ) adb.show();
HAPPY CODING!

Categories

Resources