java.lang.NullPointerException on StartActivityForResult - java

I am new in Android programming and I am trying to implement the application which have two buttons to open a camera and make a photo and to open a gallery and select photo.
I know how to do it using the onClick() in designer mode, but the problem is, that I don't want to have everything in a one big class. So I made two different classes to handle the camera and gallery selection.
And here is my code:
public class Camera extends Activity implements Button.OnClickListener {
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap original = (Bitmap) extras.get("data");
ImageView iv = (ImageView) findViewById(R.id.oko);
iv.setImageBitmap(original);
}
}
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
Gallery class:
public class Gallery extends Activity implements Button.OnClickListener {
#Override
public void onActivityResult(int requestCode , int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode ==1) {
ImageView oko = (ImageView)findViewById(R.id.oko);
oko.setImageURI(data.getData()); // pobranie z galerii
Bitmap okobit = ((BitmapDrawable) oko.getDrawable()).getBitmap();
ImageView iv = (ImageView) findViewById(R.id.oko);
iv.setImageBitmap(okobit);
}
}
}
#Override
public void onClick(View view) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Image"), 1); // here is a NULL exception
}
}
and the method which uses those classes:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button gallery = (Button)findViewById(R.id.gallery);
gallery.setOnClickListener(new Gallery());
Button camera = (Button)findViewById(R.id.camera);
camera.setOnClickListener(new Camera());
}
And now I am wondering why do I have the null pointer exception ? Both, in startActivityForResult connected with Camera and startActivityForResult connected with Gallery
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3390)
at android.app.Activity.startActivityForResult(Activity.java:3351)
at com.example.teczowka.app.Gallery.onClick(Gallery.java:39)
my xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.teczowka.app.MainActivity"
android:background="#dbff56"
android:name="android.hardware.camera"
android:required="true">
<ImageView
android:layout_width="550dp"
android:layout_height="350dp"
android:id="#+id/oko"
android:visibility="visible" />
<Button
android:layout_width="110dp"
android:layout_height="50dp"
android:text="Recognize"
android:id="#+id/recognize"
android:layout_alignParentBottom="true" />
<Button
android:layout_width="110dp"
android:layout_height="50dp"
android:text="Gallery"
android:id="#+id/gallery"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="110dp"
android:layout_height="50dp"
android:text="Camera"
android:id="#+id/camera"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:longClickable="true"
android:onClick="onClick" />

Your other activities(Gallery & Camera) will need a layout without a layout the activity creation will fail.
I suggest you don't have Gallery and Camera extend Activity Class, but rather you can send the context of the parent activity and use it to start the activity
Update: Here is the solution, Hope it helps
Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_camera);
Button gallery = (Button) findViewById(R.id.gallery);
gallery.setOnClickListener(new Gallery(this));
Button camera = (Button) findViewById(R.id.camera);
camera.setOnClickListener(new Camera(this));
}
#Override
public void onActivityResult(int requestCode , int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode ==1) {
ImageView oko = (ImageView)findViewById(R.id.oko);
oko.setImageURI(data.getData()); // pobranie z galerii
Bitmap okobit = ((BitmapDrawable) oko.getDrawable()).getBitmap();
ImageView iv = (ImageView) findViewById(R.id.oko);
iv.setImageBitmap(okobit);
}
}
}
Gallery Class
public class Gallery implements View.OnClickListener {
private Activity mContext;
public Gallery(Activity activity){
this.mContext = activity;
}
#Override
public void onClick(View view) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
mContext.startActivityForResult(Intent.createChooser(gallery, "Select Image"), 1); // here is a NULL exception
}
}
Camera Class
public class Camera implements View.OnClickListener {
private static final int CAMERA_REQUEST = 1888;
private Activity mContext;
public Camera(Activity activity) {
this.mContext = activity;
}
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mContext.startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}

Related

new images does not show up after clicking

I have my ProfileActivity:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Button gallery = findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProfileActivity.this,GalleryActivity.class);
startActivityForResult(intent, 3);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageURI(selectedImage);
}
}
My GalleryActivity:
public class GalleryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivity(intent);
}
}
my xml file:
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
<Button
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10sp"
android:text="Load image from Gallery"
android:textAllCaps="false"
android:textSize="21sp" />
I am facing issue that when user clicked on the new image, it does not show up at the OnActivityResult().
what is the reason and how I can solve it?
After I read and implemented the code in my Android Studio, I was also confused that why did you launch a new Activity (GalleryActivity) to start the image selection. The Intent Intent.ACTION_PICK will show a pick UI.
Obviously, using your code couldn't achieve your goal.
In my opinion, just launch the picking image UI from class GalleryActivity
like this:
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TestShowGallery", "TANCOLO===> onClick() ");
// Intent intent = new Intent(TestShowGallery.this,GalleryActivity.class);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 3);
}
});
I test my code, it works.
If you really really want to do what you want, there is an approach to achieve your goal, but I don’t recommend you to do that. In order to review how to transfer data between 2 Activities, I show you an example.
You just need to change the code in class GalleryActivity
public class GalleryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GalleryActivity", "TANCOLO===> onCreate() ");
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 400);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("GalleryActivity", "TANCOLO===> requestCode = " + requestCode + ", resultCode = " + resultCode);
Log.d("GalleryActivity", "TANCOLO===> data = " + data );
if (requestCode == 400 && resultCode == RESULT_OK) {
setResult(RESULT_OK, data);
finish();
}
}
}

Opening a new activity gives null object reference

The app is supposed to open a new activity by clicking RecyclerView. but when I try to click on my RecyclerView data, it gives the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.startActivityForResult(android.content.Intent, int)' on a null object reference
at com.example.studyreminder.CustomAdapter$1.onClick(CustomAdapter.java:69)
I'm using fragments if that makes any difference.
I don't understand how to fix so if anyone knows it will be appreciated.
Class where the error is at:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.myViewHolder> {
private Context context;
private ArrayList task_id, task_subject, task_description, task_due_date;
private Activity activity;
ImageButton deleteTask;
String task;
CustomAdapter(Context context, ArrayList task_id, ArrayList task_subject, ArrayList task_description, ArrayList task_due_date){
this.context = context;
this.task_id = task_id;
this.task_description = task_description;
this.task_subject = task_subject;
this.task_due_date = task_due_date;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from (context);
View view = inflater.inflate(R.layout.to_do_list, parent, false);
return new myViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, final int position) {
holder.taskid_txt.setText(String.valueOf(task_id.get(position)));
holder.taskSubject_txt.setText(String.valueOf(task_subject.get(position)));
holder.taskDescription_txt.setText(String.valueOf(task_description.get(position)));
holder.taskDate_txt.setText(String.valueOf(task_due_date.get(position)));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return task_id.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView taskid_txt, taskSubject_txt, taskDescription_txt, taskDate_txt;
LinearLayout mainLayout;
public myViewHolder(#NonNull View itemView) {
super(itemView);
taskid_txt = itemView.findViewById(R.id.taskid_txt);
taskSubject_txt = itemView.findViewById(R.id.taskSubject_txt);
taskDescription_txt = itemView.findViewById(R.id.taskDescription_txt);
taskDate_txt = itemView.findViewById(R.id.taskDate_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
The activity I'm trying to open:
public class UpdateActivity extends AppCompatActivity {
EditText title_input, author_input, pages_input;
Button addBtn2, delete_button;
EditText descEntry2, dateEntry2;
Spinner sp2;
String id, description, dueDate, subject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
descEntry2 = findViewById(R.id.descEntry2);
dateEntry2 = findViewById(R.id.dateEntry2);
addBtn2= findViewById(R.id.addbtn2);
sp2 = findViewById(R.id.subjectEntry2);
delete_button = findViewById(R.id.delete_button);
//First we call this
getAndSetIntentData();
//Set actionbar title after getAndSetIntentData method
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setTitle(subject);
}
addBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//And only then we call this
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
description = descEntry2.getText().toString().trim();
dueDate =dateEntry2.getText().toString().trim();
subject = sp2.getSelectedItem().toString().trim();
myDB.updateData(id, subject, description, dueDate);
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialog();
}
});
}
void getAndSetIntentData(){
if(getIntent().hasExtra("id")
&& getIntent().hasExtra("subject")
&& getIntent().hasExtra("description")
&& getIntent().hasExtra("dueDate")){
//Getting Data from Intent
id = getIntent().getStringExtra("id");
subject = getIntent().getStringExtra("subject");
description = getIntent().getStringExtra("description");
dueDate = getIntent().getStringExtra("dueDate");
//Setting Intent Data
title_input.setText(subject);
author_input.setText(description);
pages_input.setText(dueDate);
Log.d("stev", subject+" "+description+" "+dueDate);
}else{
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete " + subject + " Task?");
builder.setMessage("Are you sure you want to delete this " + subject + " task?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
myDB.deleteOneRow(subject);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
XML code for the UpdateActivity:
<?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">
<TextView
android:id="#+id/addTasktxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginBottom="50dp"
android:text="#string/addTask"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/descEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/addbtn2"
android:layout_width="155dp"
android:layout_height="57dp"
android:layout_marginTop="50dp"
android:layout_marginBottom="136dp"
android:text="Update"
android:textAllCaps="false"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.488"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/dateEntry2"
/>
<Spinner
android:id="#+id/subjectEntry2"
android:layout_width="228dp"
android:layout_height="55dp"
android:popupBackground="#5c5c5c"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/dateEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/descEntry2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="50dp"
android:ems="10"
android:hint="What needs to be done?"
android:inputType="text"
app:layout_constraintBottom_toTopOf="#+id/subjectEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/dateEntry2"
android:layout_width="104dp"
android:layout_height="47dp"
android:layout_marginStart="125dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="125dp"
android:ems="10"
android:hint="#string/taskDueDate"
android:inputType="phone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/subjectEntry2" />
<Button
android:id="#+id/delete_button"
android:layout_width="156dp"
android:layout_height="51dp"
android:text="Delete"
android:textAllCaps="false"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.486"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addbtn2" />
</androidx.constraintlayout.widget.ConstraintLayout>
you have not intialized private Activity activity; in CustomAdapter constructor.
either initialize it in ctor or try the snippet below:
try replacing:
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
activity.startActivityForResult(intent, 1);
}
});
with:
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context myContext = context == null ? view.getContext() : context;
Intent intent = new Intent(, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
(activity == null ? (Activity)myContext : activity) .startActivityForResult(intent, 1);
}
});
Try with the following code. I think your activity object is null. You have not initialize your activity object
context.startActivity(intent);
//findViewById() is missing for below variable in UpdateActivity
EditText title_input, author_input, pages_input;

How can I add images from the gallery to my gridview dynamically ? I can go to the gallery but images aren't getting added to my gridview

MainActivity.java
So the button choose_img_btn will redirect you to the gallery from where you can pick images and in my arraylist I temporarily added some images using R.drawable.ids. So far I can go to my gallery and click on images but the images aren't getting added to my gridview.
I think I am making mistake in the onActivityResult Class. I need a way to add my images from gallery to my gridview, but not getting how to do it. I tried many results from stackoverflow, but it's still not working.
public class MainActivity extends AppCompatActivity{
GridView gridView;
ImageButton choose_Img_Btn;
private static final int IMAGE_PICK_CODE = 1000;
private static final int PERMISSION_CODE = 1001;
public int queue=-1;
Uri selectedImage;
String imgDecodableString;
ArrayList<Integer> myImageIds = new ArrayList<>(Arrays.asList(
R.drawable.img0,R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,
R.drawable.img5,R.drawable.img6,R.drawable.img7,R.drawable.img8,
R.drawable.img9,R.drawable.img10,R.drawable.img11,R.drawable.img12,
R.drawable.img13,R.drawable.img14,R.drawable.img15,R.drawable.img16,
R.drawable.img41,R.drawable.img17,R.drawable.img18,R.drawable.img19,R.drawable.img20,
R.drawable.img21,R.drawable.img22,R.drawable.img23,R.drawable.img24,
R.drawable.img25,R.drawable.img26,R.drawable.img27,R.drawable.img28,
R.drawable.img29,R.drawable.img43,R.drawable.img30,R.drawable.img31,R.drawable.img32,
R.drawable.img33,R.drawable.img34,R.drawable.img35,R.drawable.img36,
R.drawable.img37,R.drawable.img38,R.drawable.img39,R.drawable.img40,
R.drawable.img42,R.drawable.img44,R.drawable.img45
));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.myGrid);
choose_Img_Btn = findViewById(R.id.choose_img_btn);
// we need an adapter to set images in this grid-view
gridView.setAdapter(new ImageAdaptor(myImageIds, this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int item_pos = myImageIds.get(i);
ShowDialogBox(item_pos);
}
});
choose_Img_Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//check runtime permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
{
//permission not granted, request it
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_CODE);
}
else{
//permission already granted
pickImageFromGallery();
}
}
else{
//system OS is less then marshmallow xD
}
}
});
}
private void pickImageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
//handle request for picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/* if(resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE){
gridView.
}*/
/*
// Set up a try/catch for selecting images from the gallery.
try {
// If an image *is* selected, i.e. we make sure the user has actually selected one.
if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK
&& data != null) {
// Set
queue = 1;
//Assign the results of data.GetData() to our URI variable, selectedImage.
//gridView = data.getData();
// Set up a string to contain the name of the file in question.
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor,
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
// Move the cursor to the first row.
cursor.moveToFirst();
// ???? something to do with a database
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
}
// Stop the "You haven't picked an image!" message on displaying if we hit the back button
// to return to the Browse Photos screen from the Edit Photos screen.
else if(queue!=-1) {
return;
}
else {
Toast.makeText(this, "You haven't picked an image!",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong!", Toast.LENGTH_LONG).show();
}
*/
if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK && data != null){
Uri selectedImage = data.getData();
choose_Img_Btn.setImageURI(selectedImage);
//gridView.setAdapter(new ImageAdaptor(myImageIds, this));
ImageView i = new ImageView(this);
i.setImageURI(selectedImage);
myImageIds.add(i.getId());
}
}
//handle request for runtime permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_CODE: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//permission was granted
pickImageFromGallery();
}
else{
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
}
}
public void ShowDialogBox(int item_pos){
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
//Getting Custom Dialog Views
TextView Image_name = dialog.findViewById(R.id.txt_Image_name);
ImageView image = dialog.findViewById(R.id.img);
Button btn_full = dialog.findViewById(R.id.btn_full);
Button btn_close = dialog.findViewById(R.id.btn_close);
String title = getResources().getResourceName(item_pos);
//Extract only name
int index = title.indexOf("/");
String name = title.substring(index+1, title.length());
Image_name.setText(name);
image.setImageResource(item_pos);
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
btn_full.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FullView.class);
intent.putExtra("img_id", item_pos);
startActivity(intent);
}
});
dialog.show();
}
}
ImageAdaptor Class
public class ImageAdaptor extends BaseAdapter {
private List<Integer> mThumbIds;
private Context context;
public ImageAdaptor(List<Integer> mThumbIds, Context context) {
this.mThumbIds = mThumbIds;
this.context = context;
}
#Override
public int getCount() {
return mThumbIds.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return mThumbIds.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = (ImageView) convertView;
if(imageView == null){
imageView = new ImageView(context);
imageView.setLayoutParams(new ViewGroup.LayoutParams(350,450));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
// imageView.setImageResource(mThumbIds.get(position));
Glide.with(context).load(mThumbIds.get(position)).into(imageView);
return imageView;
}
First of all, for getting multiple images from a gallery you need to add intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true); when you are creating intent to open the gallery.
//select image
public void Select_Image() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
startActivityForResult(Intent.createChooser(intent, "Select Image"), select_image_code);
}
After then, add all selected images URI to ArrayList<Uri> uriArrayList;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == select_image_code && resultCode == RESULT_OK && data.getClipData() != null) {
int image_count = data.getClipData().getItemCount();
for (int i = 0; i < image_count; i++) {
uriArrayList.add(data.getClipData().getItemAt(i).getUri());
}
gridview_adapter.notifyDataSetChanged();
}
}
Full Example:
1) activity_main2.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity2">
<Button
android:id="#+id/BTN_select_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp"
android:fontFamily="sans-serif"
android:text="Select Image"
android:textAllCaps="false"
android:textSize="20dp" />
<GridView
android:id="#+id/img_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
android:scrollbars="vertical" />
</LinearLayout>
2) gridview_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="vertical">
<ImageView
android:id="#+id/Grid_imageview"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#color/black" />
</LinearLayout>
3) MainActivity2.java
package com.demo.temp;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
Button button;
GridView gridView;
private final int select_image_code = 0;
ArrayList<Uri> uriArrayList;
Gridview_Adapter gridview_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button = findViewById(R.id.BTN_select_image);
gridView = findViewById(R.id.img_gridview);
uriArrayList = new ArrayList<>();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Select_Image();
}
});
gridview_adapter = new Gridview_Adapter(uriArrayList);
gridView.setAdapter(gridview_adapter);
}
//select image
public void Select_Image() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Image"), select_image_code);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == select_image_code && resultCode == RESULT_OK && data.getClipData() != null) {
int image_count = data.getClipData().getItemCount();
for (int i = 0; i < image_count; i++) {
uriArrayList.add(data.getClipData().getItemAt(i).getUri());
}
gridview_adapter.notifyDataSetChanged();
}
}
}
4) Gridview_Adapter.java
package com.demo.temp;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
public class Gridview_Adapter extends BaseAdapter {
ArrayList<Uri> uriArrayList;
public Gridview_Adapter(ArrayList<Uri> uriArrayList) {
this.uriArrayList = uriArrayList;
}
#Override
public int getCount() {
return uriArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gridview_adapter,parent,false);
ImageView imageView = convertView.findViewById(R.id.Grid_imageview);
imageView.setImageURI(uriArrayList.get(position));
}
return convertView;
}
}

How to show Image programmatically in custom alert dialog

When you click on button camera should open After capturing the image it should show in customAlertDialog with two options save and cancel
here is my code:
public class MainActivity extends AppCompatActivity{
Button photo;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
photo = (Button) findViewById(R.id.btn_photo);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
}
}
}
Do this call from where you want to call camera::
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 101);
When you come back after capturing picture from camera. It will call "onActivityResult()" and do code like this:
public void onActivityResult(int requestcode,int resultcode,final Intent intent) {
super.onActivityResult(requestcode, resultcode, intent);
if (resultcode == RESULT_OK) {
if (requestcode == 101) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("Save", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here. Because image is already saved but if you want to save it other place then do code.
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Do here code for for deleting image using uri
}
});
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.go_pro_dialog_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.show();
final ImageView image = (ImageView) dialog.findViewById(R.id.goProDialogImage);
Bitmap photo = (Bitmap) intent.getExtras().get("data");
image.setImageBitmap(photo); //Edited here
}
}
}
Now create a XML layout name as "go_pro_dialog_layout.xml"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/goProDialogImage"
android:layout_width="300dp"
android:layout_height="300dp"
/>
</LinearLayout>
And here you are done with whole code..and happy coding.

How to set Bitmap ImageView in MainActivity from result Crop Activity?

Hello I use this https://github.com/chemalarrea/CropImage to crop Photo from camera. But there not set result to ImageView, so
I modified main.xml like here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="#string/hello" />
<Button android:id="#+id/button" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Take picture" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mImageView" />
</LinearLayout>
this is MainActivity.class
public class MainActivity extends Activity {
private static final int PICK_FROM_CAMERA = 1;
private Uri mImageCaptureUri;
private ImageView mImageView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doTakePhotoAction();
}
});
mImageView = (ImageView) findViewById(R.id.mImageView);
}
private void doTakePhotoAction() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", false);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_FROM_CAMERA:
Intent intent = new Intent(this, CropImage.class);
intent.putExtra("image-path", mImageCaptureUri.getPath());
intent.putExtra("scale", true);
startActivity(intent);
break;
}
}
}
so How to set Bitmap ImageView in MainActivity from result Crop Activity ?
From looking the code here:
https://github.com/chemalarrea/CropImage/blob/master/src/com/droid4you/util/cropimage/CropImage.java
Do something along the lines of this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_FROM_CAMERA:
if (data != null && "inline-data".equals(data.getAction())) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.getParcelable("data");
mImageView.setImageBitmap(imageBitmap);
}
else {
Intent intent = new Intent(this, CropImage.class);
intent.putExtra("image-path", mImageCaptureUri.getPath());
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
break;
}
}
Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == PICK_FROM_CAMERA ) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.getParcelable("data");
mImageView.setImageBitmap(imageBitmap);
}
}

Categories

Resources