Prevent User from closing alert Dialog if EditText is empty - java

I'm using AlertDialog Box with EditText where user input his name. I would like to prevent the alertDialog from closing when EditText is Empty.
Below is my code
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
I tried to insert
if(TextUtils.isEmpty(name)) {
input_field.setError("Your message");
return;
}
Inside the AlertDialog Box like this, but it didn't work
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
if(TextUtils.isEmpty(name)) {
input_field.setError("Your message");
return;
}
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
Below is the image file, I have
and the image what I would like to get
Thanks in advance.

Use setCancelable(false).
Just set this
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
builder.setCancelable(false);

You see the AlertDialog use a default click listener which after forwarding the click call dismiss by default.
In your case you have to override the default click listener from dialog itself to define your custom behavior for dialog:
//Create the AlertDialog with a reference to edit it later
final AlertDialog dialog = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Check if your condition is met, Dismiss once everything is OK.
dialog.dismiss();
}
});
}
});
dialog.show();

Try this sample i made. First you have to create a layout for your dialog, just customize it according to your needs.
//R.layout.new_message_dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/checker_txt_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/pin_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send message to?"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<EditText
android:id="#+id/pin_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Name"
android:inputType="text"
android:padding="10dp"
android:layout_marginTop="10dp"
android:cursorVisible="false"
android:singleLine="true" />
<TextView
android:id="#+id/pin_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:padding="10dp"
android:text="Confirm"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/colorAccent" />
</LinearLayout>
Then inflate the view and set it to your builder.
View view = getLayoutInflater().inflate(R.layout.new_message_dialog, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setView(view);
TextView tvConfirmBtn = view.findViewById(R.id.pin_btn);
final EditText txtName = view.findViewById(R.id.pin_txt);
final AlertDialog dialog = builder.create();
dialog.show();
tvConfirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = txtName.getText().toString().trim();
if (name.isEmpty()) {
txtName.setError("Please provide a name.");
txtName.requestFocus();
} else {
//do something here
dialog.dismiss();
}
}
});

Related

Seekbar is null, even though it exists

My goal is to access a seekbar. I tried many things, even pulling the Seekbar seekingbar before the override, but I get always the null toast. R.layout.firstLayout, R.layout.secondLayout, R.id.seekingbar, they all exist.
This is my abbreviated code
public class MainActivity extends AppCompatActivity {
SeekBar seekingbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekingbar = (SeekBar) findViewById(R.id.seekingbar);
LayoutInflater inflater = getLayoutInflater();
final View firstLayout = inflater.inflate(R.layout.firstLayout, null);
final View secondLayout = inflater.inflate(R.layout.secondLayout, null);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton("Forward", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
AlertDialog dialog2 = new AlertDialog.Builder(MainActivity.this)
.setView(secondLayout)
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (seekingbar == null)
{
Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_LONG).show();
}
}
}).create();
dialog2.show();
}
}).create();
dialog.show();
}
});
}
}
firstLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/seekbarll"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
tools:context=".MainActivity">
<SeekBar
android:id="#+id/seekingbar"
style="#style/Widget.AppCompat.SeekBar.Discrete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:min="0"
android:progress="3" />
</LinearLayout>
Try to find the seekBar in the firstLayout after declaring it:
"firstLayout.findViewById(R.id.seekbar)"

Adding new object to custom array adapter with help of AlertDialog

I'm trying to add new Client with help of dialog, but it looks like my edit text does not exist.
It looks like all ids are right and all is good with activity live cycle, but I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference at dartdev.intent.MainActivity$3.onClick(MainActivity.java:122)
On the line:
String nameValue = clientName.getText().toString().trim();
Can anyone explain what went wrong?
MainActivity.java
public class MainActivity extends Activity{
ArrayList<Client> clientListItems = new ArrayList<Client>();
ClientAdapter clientAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
initClients();
clientAdapter = new ClientAdapter(this, clientListItems);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(clientAdapter);
Button buttonView = (Button)findViewById(R.id.addListItem);
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setAddingDialog();
}
});
}
/*
#Override
protected void onStart() {
super.onStart();
Button buttonView = (Button)findViewById(R.id.addListItem);
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//listItems.add(0, Utils.hashGenerator(25));
//adapter.notifyDataSetChanged();
//DialogFragment newFragment = new AddingDialog();
//newFragment.show(getFragmentManager(), "adding");
setAddingDialog();
}
});
}
*/
void initClients(){
clientListItems.add(new Client("alex", 1265, new Wallet("151516456464564654", 4564.56), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("mike", 26, new Wallet("465456445644123231", 1645.2), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("tray", 145, new Wallet("12315465489789", 0.00), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("vincent", 999, new Wallet("3213546549789", 1000000.01), R.drawable.ic_launcher_foreground));
clientListItems.add(new Client("venom", 666, new Wallet("321154654654798", 145.6), R.drawable.ic_launcher_foreground));
}
void setAddingDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
Dialog alertDialog = builder.create();
final EditText clientName = (EditText) alertDialog.findViewById(R.id.newClientName);
final EditText clientId = (EditText) alertDialog.findViewById(R.id.newClientId);
final EditText clientWallet = (EditText) alertDialog.findViewById(R.id.newClientWallet);
final EditText clientBalance = (EditText) alertDialog.findViewById(R.id.newClientBalance);
builder.setView(inflater.inflate(R.layout.dialog_add_new_client, null))
.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
.show();
}
}
dialog_add_new_client.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="match_parent">
<EditText
android:id="#+id/newClientName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="name"
android:inputType="text" />
<EditText
android:id="#+id/newClientId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="id"
android:inputType="number" />
<EditText
android:id="#+id/newClientWallet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="walletNumber"
android:inputType="text" />
<EditText
android:id="#+id/newClientBalance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="balance"
android:inputType="numberDecimal" />
</LinearLayout>
Move this code:
Dialog alertDialog = builder.create();
final EditText clientName = (EditText) alertDialog.findViewById(R.id.newClientName);
final EditText clientId = (EditText) alertDialog.findViewById(R.id.newClientId);
final EditText clientWallet = (EditText) alertDialog.findViewById(R.id.newClientWallet);
final EditText clientBalance = (EditText) alertDialog.findViewById(R.id.newClientBalance);
after
builder.setView(inflater.inflate(R.layout.dialog_add_new_client, null))
.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
When you assign your EditTexts, the dialog custom view is not yet inflated, so they are all null. And also you need to call findViewById on the inflated view and not on the alert dialog.
Don't call show() while you set your custom layout but only in the end, after your textviews initialization, by calling:
alertDialog.show();
EDIT
Declare your EditTexts as global fields of your activity, so they don't need to be final.
Summing up, change your setAddingDialog() this way:
private EditText clientName;
private EditText clientId;
private EditText clientWallet;
private EditText clientBalance;
void setAddingDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_add_new_client, null);
builder.setView(dialogView)
.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
Dialog alertDialog = builder.create();
clientName = (EditText) dialogView.findViewById(R.id.newClientName);
clientId = (EditText) dialogView.findViewById(R.id.newClientId);
clientWallet = (EditText) dialogView.findViewById(R.id.newClientWallet);
clientBalance = (EditText) dialogView.findViewById(R.id.newClientBalance);
alertDialog.show();
}
UPDATE
You need to call findViewById on the inflated view and not on the alert dialog. Check the code I updated.
Just add your dialog layout before this-:
builder.setContentView(R.layout.dialog_add_new_client);
final EditText clientName = (EditText) alertDialog.findViewById(R.id.newClientName);
final EditText clientId = (EditText) alertDialog.findViewById(R.id.newClientId);
final EditText clientWallet = (EditText) alertDialog.findViewById(R.id.newClientWallet);
final EditText clientBalance = (EditText) alertDialog.findViewById(R.id.newClientBalance);
builder.setPositiveButton("add", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nameValue = clientName.getText().toString().trim();
int idValue = Integer.valueOf(clientId.getText().toString().trim());
String walletValue = clientWallet.getText().toString().trim();
double balanceValue = Double.valueOf(clientBalance.getText().toString().trim());
clientListItems.add(new Client(nameValue, idValue, new Wallet(walletValue, balanceValue), R.drawable.ic_launcher_foreground));
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
.show();
}
}
You need to add layout content first then initialize the edittexts.

AlertDialog Builder OnItemSelectedListener

I have a tyny, but annoying problem with the AlertDialog Builder.
I want to handle an item select in a custom made AlertDialog, but OnItemSelectedListener doesn't seem to pick my clicks.
Custom Dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:background="#AAFFFFFF"
android:orientation="vertical">
<TextView
android:text="English"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_english"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingLeft="10dp"
android:onClick="onLanguageButtonClicked" />
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#000000" />
<TextView
android:text="عربى"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_arabic"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingRight="10dp"
android:onClick="onLanguageButtonClicked" />
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#2e2e2e"/>
<TextView
android:text="کوردی "
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_kurdish"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingRight="10dp"
android:onClick="onLanguageButtonClicked" />
</LinearLayout>
On button click I open the dialog and handle it:
public void onClickDrawer(View view) {
switch (view.getId()) {
case R.id.button_account_language:
handleLanguageDialog();
break;
case R.id.button_account_currency:
handleCurrencyDialog();
break;
default:
break;
}
}
And the handler:
private void handleLanguageDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.dialog_language);
builder.setOnItemSelectedListener(new AdapterView.
OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Log.i("info", "pressed" + Integer.toString(position));
restartInLocale(new Locale(preferences.getString("locale","")));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
builder.setNegativeButton("CANCEL", new DialogInterface
.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
Is this the correct approach or am I missing something?
Thank you in advance!
I don't this is correct Approach, you are making it very much complex. If I am not wrong then you are trying to show Language selection dialog for that you should follow the below given steps.
Create string-array inside strings.xml resource file
<string-array name="lang">
<item>English</item>
<item>عربى</item>
</string-array>
When you want to show alert dialog write down below code
private void handleLanguageDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color)
.setItems(R.array.lang, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch(which)
{
case 0:// English
break;
case 1:// عربى
break;
}
}
});
return builder.create();
}
This is the simplest way to show list of languages in alert dialog and without any positive or negative button .
It looks a bit off. It should look like this:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
https://developer.android.com/guide/topics/ui/dialogs.html
private void handleLanguageDialog() {
ArrayList<String> listItems = new ArrayList<>();
listItems.add("English");
listItems.add("Arabic");
new AlertDialog.Builder(this)
.setTitle("title")
.setCancelable(false)
.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).show();
}
Try to use setOnItemClick listener on the list/spinner view whichever you are using to display the list instead of builder itself. Like if you are using spinner to show the list use-
final Spinner spinner = (Spinner) layout.findViewById(R.id.spinner); spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int item = spinner.getSelectedItemPosition();
commandWriter(item);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Try this: add click listener to the language item in your Dialog
onItemSelected() is applied for listview or spinner items your Dialog layout dialog_language does not have those.
Try this code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater =getLayoutInflater();
View myview = inflater.inflate(R.layout.dialog_language, null);
// Inflate and set the layout for the dialog
builder.setView(myview);
TextView english = (TextView) myview.findViewById (R.id.lang_english);
english.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do some stuff
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.i("info", "pressed" + Integer.toString(position));
restartInLocale(new Locale(preferences.getString("locale","")));
}
});
TextView arabic = (TextView) myview.findViewById (R.id.lang_arabic);
arabic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do other stuff
}
});
// Add action buttons
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();

Preview captured Image NullpointerException

public void openDialogToAddReminder(final Context context, final DbHelper dbHelper, final int Rem_id, final int Med_id) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(context);
final View mView = layoutInflaterAndroid.inflate(R.layout.add_reminders_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.myDialog));
alertDialogBuilder.setView(mView);
captureImage = (ImageButton) mView.findViewById(R.id.capture_image);
captureImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage(context);
}
});
alertDialogBuilder
.setCancelable(false)
.setPositiveButton(dialog_title, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
public void selectImage(final Context context) {
final CharSequence[] items = { "Take Photo", "Choose from Gallery",
"Cancel" };
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= Utility.checkPermission(context);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent(context);
} else if (items[item].equals("Choose from Gallery")) {
userChoosenTask ="Choose from Gallery";
if(result)
galleryIntent(context);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void galleryIntent(Context context)
{
Log.i("Context ",context.toString());
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
public void cameraIntent(Context context)
{
Intent takingPictureCameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takingPictureCameraintent.resolveActivity(context.getPackageManager())!=null)
startActivityForResult(takingPictureCameraintent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
public void onCaptureImageResult(Intent data)
{
try{
Bundle extras=data.getExtras();
Bitmap thumbnail = (Bitmap) extras.get("data");
Log.i("Image Camera Bitmap ",thumbnail.toString());
ByteArrayOutputStream bytes=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90,bytes);
captureImage.setImageBitmap(thumbnail);
saveToGallery(thumbnail);
}
catch (Exception e){e.printStackTrace();}
}
add_reminders_dialog.xml
<?xml version = "1.0" encoding="utf-8"?>
<RelativeLayout android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_vertical_margin"
android:layout_marginTop="#dimen/activity_horizontal_margin"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/r1"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.CardView
android:id="#+id/cardview_medicine_image"
android:layout_marginTop="20dp"
app:contentPadding="#dimen/activity_horizontal_margin"
android:layout_below="#+id/cardview_medicine_time"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="match_parent"
android:layout_height="170dp"
android:background="#424242"
android:padding="10dp"
android:clickable="true"
android:src="#drawable/icon_camera"
android:scaleType="fitCenter"
android:id="#+id/capture_image"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
Getting NullPointerException here:
captureImage.setImageBitmap(thumbnail);
I don't know why I am getting captureImage null. As I have define it globally. Why it is null as I have defined it inside the dialog box.
Well your captureImage belongs to the view of your first alert dialog (the one created in openDialogToAddReminder method.
I suspect that upon clicking on the captureImage to select the image, this dialog gets dismissed so it destroys the captureImage reference, hence when the onActivityResult is called there is no more captureImage object.
You can check the above if you set a dismiss listener on your AlertDialog.Builder e.g.
alertDialogBuilder.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
Log.d("onDismiss");
}
});
place this code right above:
AlertDialog alertDialog = alertDialogBuilder.create();
EDIT:
If you receive on your logcat: "onDismiss" this means that my assumption is correct. Try to resolve it by:
alertDialog.setCanceledOnTouchOutside(false);

Alert Dialog - how to implement Cancel and Okay button

I have got this Alert Dialog which has these two buttons (Ok and Cancel). I want to know how I go about implementing it.
So When you click on the cancel button it should close the alert dialog and return back to the fragment I am currently on. And if I click on the Ok button it should replace the current alert dialog and place it with another one.
this is my code below for the confimration. java file;
public class confirmation extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inf = getActivity().getLayoutInflater();
final View theDIalog = inf.inflate(R.layout.example_xml, null);
builder.setView(theDIalog);
AlertDialog dialog = builder.create();
theDIalog.findViewById(R.id.makeaTransferOk).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Okay button is clicked", Toast.LENGTH_SHORT).show();
}
});
theDIalog.findViewById(R.id.makeaTransferCancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
return dialog;
}
}
this is my code for the example_xml;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffc0c0c0">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="#+id/makeaTransferCancel"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:id="#+id/makeaTransferOk"/>
</RelativeLayout>
Please could someone help me
Try this code for the functionality you have mentioned above:
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//put your code that needed to be executed when okay is clicked
dialog.cancel();
}
});
builder1.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("your message ");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //<-- change it with ur code
}
} );
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
} );
alertDialog.show();
builder.setPositiveButton(text, new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}).setNegativeButton(text, new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}).create();

Categories