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);
Related
I have an activity that contain a grid view which contain 3 card view each has an image view I want to setonclick mistenr that put the taken iamge from camera to the selected image view.
How can I fix this? By the way I'm using the same code for the three image view the issue is in the in activityresult method and I can't change it.
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".inspection.ImageActivity">
<View
android:id="#+id/bg_top_header9"
android:layout_width="match_parent"
android:layout_height="193dp"
android:background="#drawable/ic_bg_topheader"
app:layout_constraintBottom_toTopOf="#+id/gridLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="110dp"
android:alignmentMode="alignMargins"
android:columnCount="1"
android:columnOrderPreserved="false"
android:padding="14dp"
android:rowCount="3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.343"
app:layout_editor_absoluteX="0dp">
<androidx.cardview.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#color/whiteCardColor"
app:cardCornerRadius="20dp"
app:cardElevation="5dp">
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_img" />
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#color/whiteCardColor"
app:cardCornerRadius="20dp"
app:cardElevation="5dp">
<ImageView
android:id="#+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_img" />
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:background="#color/whiteCardColor"
app:cardCornerRadius="20dp"
app:cardElevation="5dp">
<ImageView
android:id="#+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_img" />
</androidx.cardview.widget.CardView>
</GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
and this is the java class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
bgTopHeader9 = findViewById(R.id.bg_top_header9);
gridLayout = findViewById(R.id.gridLayout);
img1 = findViewById(R.id.img1);
img2 = findViewById(R.id.img2);
img3 = findViewById(R.id.img3);
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton(R.string.takepic, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNegativeButton("Delete", (dialog, which) -> {
if (imgFile.exists()) {
if (imgFile.delete())
Toast.makeText(ImageActivity.this, mCurrentPhotoPath + "deleted",
Toast.LENGTH_SHORT).show();
img1.setImageResource(R.drawable.ic_img);
}
}).setNeutralButton("Cancle ", (dialog, which) -> dialog.cancel());
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (!(img1.getDrawable() == getResources().getDrawable(R.drawable.ic_img))) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
}
});
img2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton(R.string.takepic, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNegativeButton("Delete", (dialog, which) -> {
if (imgFile.exists()) {
if (imgFile.delete())
Toast.makeText(ImageActivity.this, mCurrentPhotoPath + "deleted", Toast.LENGTH_SHORT).show();
img2.setImageResource(R.drawable.ic_img);
}
}).setNeutralButton("Cancle ", (dialog, which) -> dialog.cancel());
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (!(img2.getDrawable() == getResources().getDrawable(R.drawable.ic_img))) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
}
});
img3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton(R.string.takepic, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNegativeButton("Delete", (dialog, which) -> {
if (imgFile.exists()) {
if (imgFile.delete())
Toast.makeText(ImageActivity.this, mCurrentPhotoPath + " deleted", Toast.LENGTH_SHORT).show();
img3.setImageResource(R.drawable.ic_img);
}
}).setNeutralButton(R.string.cancle_string, (dialog, which) -> dialog.cancel());
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (!(img3.getDrawable() == getResources().getDrawable(R.drawable.ic_img))) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
}
});
}
private void Showimage() {
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IndexOutOfBoundsException {
try {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton("cancel ", (dialog, which) -> {
dialog.cancel();
}).setNegativeButton("Delete ", (dialog, which) -> {
img1.setImageResource(R.drawable.ic_img);
option = false;
});
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (imgFile.exists()) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
});
}
private void captureImage() throws IOException {
option = true;
String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(this, perms)) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoFile = createImageFile();
Uri photoURI = FileProvider.getUriForFile(ImageActivity.this, "com.xdev.pfe.utils.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
} else {
EasyPermissions.requestPermissions(this, "We need permissions because this and that", 123, perms);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == RESULT_OK) {
#SuppressWarnings("unused") Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton("save ", (dialog, which) -> {
File imgFile = new File(mCurrentPhotoPath);
if (imgFile.exists()) {
byte[] imageData = null;
try {
final int THUMBNAIL_SIZE = 1024;
FileInputStream fis = new FileInputStream(imgFile);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
} catch (Exception ex) {
}
Bitmap bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
img1.setImageBitmap(bmp);
System.out.println(paths);
}
}).setNegativeButton(R.string.recapture_string, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNeutralButton(R.string.cancle_string, (dialog, which) -> dialog.cancel());
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
imgFile = new File(mCurrentPhotoPath);
if (imgFile.exists()) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
} else {
Toast.makeText(ImageActivity.this, "Request cancelled or something went wrong.", Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = ImageActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /*directory*/
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#Override
public void onPermissionsGranted(int requestCode, #NonNull List<String> perms) {
}
#Override
public void onPermissionsDenied(int requestCode, #NonNull List<String> perms) {
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
new AppSettingsDialog.Builder(this).build().show();
}
}
}
Send different requestCode for different imageView click, And onActivityResult check the request code set image data to your imageView
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, 100);
}
});
capturedImageButton1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, 101);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch (this.resultCode){
case 100:
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
capturedImageButton.setImageBitmap(bitmap);
break;
case 101:
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
capturedImageButton1.setImageBitmap(bitmap);
break;
default:
break;
}
}
}
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();
}
}
});
Currently I create an app which has the camera function that allows users to select their image or do capturing.I get the tutorial from https://stackoverflow.com/a/22165449/5261462. But I want the selected image intent to another page instead of just displaying on imageView. The image need to fix the screen and can add caption at below like whatsapp.
This is what I've tried so far.
Everything start from Project1.java, with the imagebutton.
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ImageFitScreen i = new ImageFitScreen();
i.selectImage();
}
});
}
ImageFitScreen.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fit_screen);
b = (ImageView) findViewById(R.id.imageView3);
t = (EditText) findViewById(R.id.editText38);
u = (EditText) findViewById(R.id.editText39);
}
public void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ImageFitScreen.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
image_fit_screen
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="574dp"
android:layout_height="523dp"
android:id="#+id/imageView3"
android:layout_x="6dp"
android:layout_y="0dp" />
<EditText
android:layout_width="388dp"
android:layout_height="wrap_content"
android:id="#+id/editText38"
android:layout_x="8dp"
android:layout_y="435dp" />
<EditText
android:layout_width="386dp"
android:layout_height="wrap_content"
android:id="#+id/editText39"
android:hint="Add a caption"
android:layout_x="2dp"
android:layout_y="410dp" />
</AbsoluteLayout>
But I get error as below when the imageButton in Project1.java is clicked.
11-03 11:44:44.800 31219-31219/com.example.project.project
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 31219
java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:164)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:103)
at android.support.v7.app.AlertDialog.resolveDialogTheme(AlertDialog.java:108)
at android.support.v7.app.AlertDialog$Builder.(AlertDialog.java:269)
at com.example.project.project.ImageFitScreen.selectImage(ImageFitScreen.java:77)
at com.example.project.project.Project1$2.onClick(Project1.java:80)
at android.view.View.performClick(View.java:4654)
at android.view.View$PerformClick.run(View.java:19438)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
(ImageFitScreen.java:77)
AlertDialog.Builder builder = new
AlertDialog.Builder(ImageFitScreen.this);
(Project1.java:80)
i.selectImage();
I am seriously in dire need of some advice. Can someone please please assist me with some advice. PLEASE : )?
From what I understood, ImageFitScreen is an activity and should be started using an Intent i.e.
Intent i = new Intent(Project1.this,ImageFitScreen.class);
startActivity(i);
If you look at the exception, it tells you that context is null ie. ImageFitScreen.this is null at the line
AlertDialog.Builder builder = new AlertDialog.Builder(ImageFitScreen.this);
This is because, activity will only have a context if it is started by the activitymanager. We use intent to ask activitymanger to start an activity. Hope it helps you.
UPDATE:
You can use ImageFitScreen to hold imageview and edittext for caption. Then start ImageFitScreeen when you need the user to pick an image. And onCreate of ImageFitScreen you can start selectImage() function ie.
Project1.java
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(Project1.this,ImageFitScreen.class);
startActivity(i);
}
});
}
ImageFitScreen.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fit_screen);
b = (ImageView) findViewById(R.id.imageView3);
t = (EditText) findViewById(R.id.editText38);
u = (EditText) findViewById(R.id.editText39);
selectImage();
}
public void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ImageFitScreen.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
finish();
}
}
});
builder.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
dialog.dismiss();
}
return true;
}
});
builder.show();
}
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();
I have Activity_A an Activity_B.
I use onActivityResult and i have a problem:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=3, result=-1, data=Intent { (has extras)
}} to activity {com.example.sellcar/com.example.sellcar.View_Offer}:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
I guess that I can not pass this way 'result' from alertDialog to onActivityResult.
I do not know how to solve this problem :/
Please help
Activity_A:
bBUTTON.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity_A.this,Activity_B.class);
startActivityForResult(intent, 3);
}
});
...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK){
String pId = data.getStringExtra("MyData");
Toast.makeText(Activity_A.this,pId,Toast.LENGTH_LONG).show();
}
}
Activity_B:
AlertDialog.Builder builder=new AlertDialog.Builder(View_Sell.this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
Intent intent = new Intent();
intent.putExtra("MyData", ostatnioDodanaSprzedaz);
setResult(RESULT_OK, intent);
onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
AlertDialog ad = builder.create();
ad.show();
Try to replace:
setResult(RESULT_OK, intent);
onBackPressed();
on:
if (getParent() == null) {
setResult(RESULT_OK, intent);
} else {
getParent().setResult(RESULT_OK, intent);
}
finish();
You can follow the Observer pattern.
First, create an Interface in the Activity class itself:
public interface ResultListener {
void onResultSet(String text);
}
Then, create an object of ResultListener globally:
ResultListener = rl;
Implement the onResultSet(String text) method inside the onCreate method:
rl = new ResultListener() {
#Override
public void onPositiveResult(String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
};
Next, create the AlertDialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
tl.onResultSet(ostatnioDodanaSprzedaz);
// onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
builder.show();
Here's how the final code will look:
public class MainActivity extends Activity {
ResultListener rl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
rl = new ResultListener() {
#Override
public void onPositiveResult(String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
rl.onResultSet(ostatnioDodanaSprzedaz);
// onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
builder.show();
} //onCreate closed
public interface ResultListener {
void onResultSet(String text);
}
} //MainActivity Class closed