how to put taken image in specific image view - java

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;
}
}
}

Related

ImageView not Clickable in DialogFragment

I have an ImageView for which I wanted to implement the onClickListener. But when I click on the image, nothing happens. Event the Logcat does not show any errors.
Something is happening with the clickability attribute.
My XML code:
<ImageView
android:id="#+id/img2"
android:layout_width="104dp"
android:layout_height="126dp"
android:layout_weight="1"
android:padding="8dp"
android:scaleType="centerCrop"
android:clickable="true"
android:src="#drawable/ic_person_black_24dp"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="-3dp"
tools:layout_editor_absoluteY="14dp"
android:focusable="true" />
Code in Fragment:
public class DialogFrag extends DialogFragment {
private ImageView img2;
private static final int IMAGE_PICK_CODE = 1000;
private final int CODE_MULTIPLE_IMG_GALLERY = 2;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#NonNull
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_layout, container, false);
img2 = (ImageView) view.findViewById(R.id.img2);
img2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int CODE_IMG_GALLERY = 1;
if (requestCode == CODE_IMG_GALLERY && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
if(imageUri!=null){
img2.setImageURI(imageUri);
}
}
if (requestCode == CODE_IMG_GALLERY && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
if(imageUri!=null){
img2.setImageURI(imageUri);
}
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
return builder
.setTitle("Заполните анкету")
.setView(R.layout.dialog_layout)
.setPositiveButton("OK", null)
.setNegativeButton("Отмена", null)
.create();
}
}
Where is my mistake?
Help please)
Please override the onViewCreated() and use the view object
kotlin code:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
img2 = view.findViewById(R.id.img2);
// Implement onclicklistener
}
This should be of any help I guess.

Button click event not working when set X and Y coordinates

I have create simple image view and set a frame and set button is x and y coordinates before set x and y coordinates this time button click event work but set x and y coordinates not working button click event.
My Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView viewImage;
private Button btnCapture;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
private Uri mCapturedImageURI;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnCapture.setX(850);
btnCapture.setY(300);
btnCapture.setOnClickListener(this);
viewImage = (ImageView) findViewById(R.id.viewImage);
viewImage.setOnTouchListener(new Touch(getApplicationContext()));
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE &&
resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
viewImage.setImageBitmap(bitmap);
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor =
getContentResolver().query(mCapturedImageURI, projection, null,
null, null);
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
viewImage.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnCapture:
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Select Image");
Button dialogButton = (Button) dialog.findViewById(R.id.btnExit);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button btnChoosePath = (Button) dialog.findViewById(R.id.btnChoosePath);
btnChoosePath.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
activeGallery();
dialog.dismiss();
}
});
Button btnTakePhoto = (Button) dialog.findViewById(R.id.btnTakePhoto);
btnTakePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activeTakePhoto();
dialog.dismiss();
}
});
dialog.show();
break;
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/camera_icon" />
<RelativeLayout
android:id="#+id/FrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="matrix" />
</FrameLayout>
<ImageView
android:id="#+id/abc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/aa" />
</RelativeLayout>
can you please replace onClick(View view) method with following.
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnCapture:
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Select Image");
Button dialogButton = (Button) dialog.findViewById(R.id.btnExit);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button btnChoosePath = (Button) dialog.findViewById(R.id.btnChoosePath);
btnChoosePath.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
activeGallery();
dialog.dismiss();
}
});
Button btnTakePhoto = (Button) dialog.findViewById(R.id.btnTakePhoto);
btnTakePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activeTakePhoto();
dialog.dismiss();
}
});
dialog.show();
break;
}
}
Edited Answer.
Change the following thing in you MainActivity.class
btnCapture.setX(300);
btnCapture.setY(850);
and replace your xml file with the following.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/FrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="matrix" />
</FrameLayout>
<ImageView
android:id="#+id/abc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/blue_squre" />
</RelativeLayout>
<ImageButton
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
And One thing in your xml you use btnCapture id for Button. and you create the object of ImageButton in your .class file. how its works for you i don't know. but i change it try it.

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);

Intent to a new page when an image is selected

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();
}

How to add a textview and a button, dynamically in a ListView in android?

In my app I have a ListView for listing some textviews and buttons ,also have an ImageView on the top,i have added parallax scrollview between this,now I want to add some textviews and buttons dynamically in the ListView . I have this code ;but it is not working.I am a beginner,so I could not find the actual problem. Can anybody help me out,and Please excuse my language problem?
MainActivity.java
public class MainActivity extends Activity {
private int lastTop = 0;
//ImageView image;
ListView listView;
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
ArrayAdapter adapter;
ArrayList<String> items = new ArrayList<>();
public void parallax(final View v) {
final Rect r = new Rect();
v.getLocalVisibleRect(r);
if (lastTop != r.top) {
lastTop = r.top;
v.post(new Runnable() {
#Override
public void run() {
v.setY((float) (r.top / 2.0));
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
//Dynamic textvieww
final LinearLayout lm = (LinearLayout) findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT);
//Create four
for(int j=0;j<=4;j++)
{
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(" Product"+j+" ");
ll.addView(product);
// Create TextView
TextView price = new TextView(this);
price.setText(" $"+j+" ");
ll.addView(price);
// Create Button
final Button btn = new Button(this);
// Give button an ID
btn.setId(j+1);
btn.setText("Add To Cart");
// set the layoutParams on the button
btn.setLayoutParams(params);
final int index = j;
// Set click listener for button
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("TAG", "index :" + index);
Toast.makeText(getApplicationContext(),
"Clicked Button Index :" + index,
Toast.LENGTH_LONG).show();
}
});
//Add button to LinearLayout
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
}
//EOF Dynamic
View view = getLayoutInflater().inflate(R.layout.header, null, false);
//Image view block
Button buttonLoadImage = (Button) view.findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
this.imageView = (ImageView)view.findViewById(R.id.imgView);
Button photoButton = (Button) view.findViewById(R.id.button2);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
//imageview block end
// image = (ImageView) view.findViewById(R.id.image);
listView.addHeaderView(view);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
parallax(imageView);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
parallax(imageView);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
activity_main.xml
<FrameLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.zoid.parallaxtutorial.MainActivity">
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
</LinearLayout>
</FrameLayout>
header.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="#+id/imgView"
android:layout_width="wrap_content"
android:layout_height="200dip"
android:scaleType="centerCrop" ></ImageView>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<Button android:id="#+id/buttonLoadPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Load Picture"
android:layout_gravity="center"></Button>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Picture"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
See this Example it may useful to add data dynamically in list view in android

Categories