upload the picture from gallery or camera by alertdialogue - android

this is my program, I think it is no problem about the alertdialogue.
But after I select the photo in my gallery, the picture isn't changed.
It is still the original photo that I set in the ImageView.
Could someboby help me know where the problem is?
public class MainActivity extends Activity{
ImageView img_logo;<br>
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
Uri selectedImageUri;
String selectedPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_logo= (ImageView) findViewById(R.id.homepic);
img_logo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent,
CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data.getData() != null){
selectedImageUri = data.getData();
}else{
Log.d("selectedPath1 : ","Came here its null !");
Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
}
if (requestCode == 100 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
selectedPath = getPath(selectedImageUri);
img_logo.setImageURI(selectedImageUri);
Log.d("selectedPath1 : " ,selectedPath);
}
if (requestCode == 10)
{
selectedPath = getPath(selectedImageUri);
img_logo.setImageURI(selectedImageUri);
Log.d("selectedPath1 : " ,selectedPath);
}
}
Toast toast = Toast.makeText(MainActivity.this, "hiiiii", Toast.LENGTH_LONG);
toast.show();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}

Try this way,hope this will help you to solve your problem.
public class MainActivity extends Activity {
ImageView img_logo;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private String imgPath;
private String selectedPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_logo = (ImageView) findViewById(R.id.homepic);
img_logo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), GALLERY_PICTURE);
}
}
);
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAMERA_REQUEST);
}
}
);
myAlertDialog.show();
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public String getAbsolutePath(Uri uri) {
if (Build.VERSION.SDK_INT >= 19) {
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = managedQuery(tempUri, imageColumns,
MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
} else {
return null;
}
} else {
String[] projection = {MediaStore.MediaColumns.DATA};
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if (!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
img_logo.setImageBitmap(BitmapFactory.decodeFile(getImagePath()));
selectedPath = getImagePath();
} else if (requestCode == GALLERY_PICTURE) {
img_logo.setImageBitmap(BitmapFactory.decodeFile(getAbsolutePath(data.getData())));
selectedPath = getAbsolutePath(data.getData());
}
Toast toast = Toast.makeText(MainActivity.this, "hiiiii", Toast.LENGTH_LONG);
toast.show();
}
}
}
Add this <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in AndroidManifest.xml

Related

Save photo in internal storage

I have a problem that is i take a photo i want to save it in internal storage. but i don't know how do make it.Who can suggest some solution ? thanks.
There is my code:
public class ThreeFragment extends Fragment {
private static final String TAG = ThreeFragment.class.getSimpleName();
private static int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_IMAGE_CAPTURE = 1;
View root;
GridView gridView;
String mCurrentPhotoPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_three, container, false);
dolist();
return root;
}
public void dolist() {
gridView = (GridView) root.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getActivity()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
openGallery();
break;
case 1:
takePhoto();
break;
case 2:
Log.d(TAG, "333333333333333333333");
break;
default:
break;
}
}
});
}
private void takePhoto() {
Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
private String saveToInternalSorage(Bitmap bitmap) {
ContextWrapper cw = new ContextWrapper(getActivity());
File dic = cw.getDir("TEST", Context.MODE_PRIVATE);
File mypath = new File(dic, ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return dic.getAbsolutePath();
}
public void openGallery() {
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE) {
if (resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
else if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
saveToInternalSorage(bitmap);
// setPath(saveToInternalSorage(bitmap));
}
}
}
}
*Try This :
File mImageFile is path where you want to store you camera image file.
Uri tempURI = Uri.fromFile(mImageFile);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
activity.startActivityForResult(i, CHOOSE_CAMERA_RESULT);
then in your onActivityResult
#Override
public void onActivityResultRAW(int requestCode, int resultCode, Intent data)
{
super.onActivityResultRAW(requestCode, resultCode, data);
switch(requestCode)
{
case CHOOSE_CAMERA_RESULT:
{
if (resultCode == RESULT_OK)
{
// here you image has been save to the path mImageFile.
Log.d("ImagePath", "Image saved to path : " + mImageFile.getAbsoultePath());
}
}
break;
}
}*
Try This:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
cameraIntent.putExtra("return-data", true);
mActPanelFragment.startActivityForResult(cameraIntent, ActivityConstantUtils.CAMERA_REQUEST);
// method
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory().getPath(), ActivityConstantUtils.STORED_IMAGE_PATH+"/Images/WOMCamera");
if (!file.exists()) {
file.mkdirs();
}
ActivityConstantUtils.mCurrentPhotoPath = (file.getAbsolutePath() + "/"+"IMG_"+ System.currentTimeMillis() + ".jpg");
Uri imgUri = Uri.fromFile(new File(ActivityConstantUtils.mCurrentPhotoPath));
if (file.canWrite()) {
}
return imgUri;
}
After that write code for result:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
String imagePath = getFilePath(data);
}
}
private String getFilePath(Intent data) {
String imagePath;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}

Saving an image to custom folder with custom name

I am trying to build an app that captures an image ans saves the image to a custom folder with a custom name but i am unable to perform it.
Here is the code that I have written please go through the code and correct me where i am wrong.
public class MainActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private Builder alertDialogBuilder;
final Context context = this;
String name_str;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
Button searchButton = (Button) this.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);
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult1(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
imageView.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
final Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
//Creating Alert Dialog Box
AlertDialog.Builder askname = new AlertDialog.Builder(MainActivity.this);
final EditText inputname = new EditText(this);
askname.setMessage("Enter Name");
askname.setView(inputname);
askname.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
name_str = inputname.getEditableText().toString();
Toast.makeText(context,name_str,Toast.LENGTH_LONG).show();
dialog.dismiss();
/*if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//photo = BitmapFactory.decodeByteArray(data,0,data.length);
imageView.setImageBitmap(photo);*/
String file ="/DCIM/VisitingCards/";
File folder = new File(Environment.getExternalStorageDirectory() + file);
System.out.println("File name is :"+folder);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
//ON success
System.out.println("Directory Present");
System.out.println("In Success Case");
try {
FileOutputStream out = new FileOutputStream(folder);
photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//ON failure
System.out.println("Directory not Present");
System.out.println("In Failure Case");
}
System.out.println("Before the Dialog builder");
}
});
askname.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.dismiss();
}
}); //End of alert.setNegativeButt
askname.show();
}
}
}
you should ask image name before intent and then used putExtra.
hope it may help you

Selected image from Gallery but it doesnt show in my image button

I'm making a function which is when I select "Choose from gallery" in an alert dialog box, the selected image inside gallery will appear in the imagebutton. I don't know what's wrong with my code.
I used these website as an example to do it http://geekonjava.blogspot.sg/2014/03/upload-image-on-server-in-android-using.html and http://www.c-sharpcorner.com/UploadFile/e14021/capture-image-from-camera-and-selecting-image-from-gallery-o/ . There isn't any code errors or logcat errors. Can someone help me with this?
Here is my code:
public static class CardFrontFragment extends Fragment implements OnClickListener{
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String uploadServerUri = null;
private String imagepath = null;
private ImageButton upload;
public CardFrontFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.card_front, container, false);
upload = (ImageButton) layout.findViewById(R.id.fileUpload);
upload.setOnClickListener(this);
uploadServerUri = Constants.serverUrl + "api/FileUpload";
return layout;
}
#Override
public void onClick(View arg0) {
if(arg0 == upload)
{
selectImage();
}
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
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();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
upload.setImageBitmap(bitmap);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
And these are the permissions that i have declared in androidmanifest.xml :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try invalidating your imagebutton. That way you tell the UI that it should be redrawn, because a value changed.
Try changing your onActivityResult to
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
upload.setImageURI(selectedImageUri);
}
}

Browse a image from SD card to show it in image view in android?

am use activity as a dialog.In that i have button to browse and select the image to show it in image view.
My Dialog activity code and browse image
public class Update_profile extends Activity{
private Uri mImageCaptureUri;
private static final int PICK_FROM_FILE = 1;
private View rootView;
Button save,browse_image;
ImageView profile_pic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(0));
setContentView(R.layout.update_profile);
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
});
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.rootView=findViewById(R.id.update_profile_details);
profile_pic = (ImageView)findViewById(R.id.update_profile_picture);
save = (Button)findViewById(R.id.save);
browse_image = (Button)findViewById(R.id.browse_image);
browse_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
Bitmap bitmap = null;
String path = "";
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); //from Gallery
Log.v("Path", ""+path);
if (path == null)
path = mImageCaptureUri.getPath(); //from File Manager
Log.v("Path", ""+path);
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
} else {
path = mImageCaptureUri.getPath();
Log.v("Path", ""+path);
bitmap = BitmapFactory.decodeFile(path);
}
profile_pic.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#SuppressLint("NewApi")
#Override
public boolean onTouchEvent(MotionEvent event) {
Rect rect = new Rect();
rootView.getHitRect(rect);
if (!rect.contains((int)event.getX(), (int)event.getY())){
setFinishOnTouchOutside(false);
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return true;
}
}
My manifest code to change the activity as a dialog
<activity
android:name="test.Update_profile"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Dialog"
android:windowSoftInputMode="stateHidden" >
</activity>
When am using above browse images code in ordinary activity means it fetch the images and show it in image view but in this dialog activity.its now able to pick the image.I want to pic the image from dialog activity.am not able to solve this issue.Can any one know please help me to solve this issue.
if u want to retrive direct from gallary then use this code
http://viralpatel.net/blogs/pick-image-from-galary-android-app/
this is my method for getting all file from sdcard and u just save this in one datacontroller class ohk dude
private void getallimages()
{
String[] STAR = { "*" };
final String[] columns = { MediaStore.Images.Thumbnails._ID , MediaStore.Images.Media.DATA};
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = ((Activity) cntx).managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
int imgNameIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
imageItem.id = id;
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
lastId = id;
imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(cntx.getContentResolver(), id,MediaStore.Images.Thumbnails.MICRO_KIND, null);
imageItem.selection = false; //newly added item will be selected by default
controller.images.add(imageItem);
}
}
this is ImageItem wrapper class
public class ImageItem {
public boolean selection=true;
public int id;
public Bitmap img;
public String filePath;
public String fileType;
}
You can try this :
public class EMView extends Activity {
ImageView img,img1;
int column_index;
Intent intent=null;
// Declare our Views, so we can access them later
String logo,imagePath,Logo;
Cursor cursor;
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;
String selectedImagePath;
//ADDED
String filemanagerstring;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img= (ImageView)findViewById(R.id.gimg1);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
//UPDATED
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
img.setImageURI(selectedImageUri);
imagePath.getBytes();
TextView txt = (TextView)findViewById(R.id.title);
txt.setText(imagePath.toString());
Bitmap bm = BitmapFactory.decodeFile(imagePath);
img1.setImageBitmap(bm);
}
}
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
}

StartActivityForResult from Fragmnet

I have two ImageView and two buttons. When button pressed - Dialog started. Positive answer - picture from galery, negative - from camera. First i write this in Activity(this code is work good):
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
String path = null;
if (DialogFlag == 0) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case GALLERY_REQUEST:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
path = getRealPathFromURI(selectedImage);
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
if (DialogFlag == 1) {
Uri uri;
if (requestCode == CAMERA_RESULT) {
Cursor cursor = getContentResolver().query(
Media.EXTERNAL_CONTENT_URI,
new String[] { Media.DATA, Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor
.getColumnIndex(Media.DATA)));
path = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case IDD_TWO_BUTTONS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Зображення з ")
.setCancelable(false)
.setPositiveButton("Галереї",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
DialogFlag = 0;
Intent photoPickerIntent = new Intent(
Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent,
GALLERY_REQUEST);
dialog.cancel();
}
})
.setNeutralButton("Камери",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
DialogFlag = 1;
Intent cameraIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,
CAMERA_RESULT);
dialog.cancel();
}
}
)
.setNegativeButton("Відміна",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
}
);
return builder.create();
default:
return null;
}
}
But when i try to make this in fragment i get some problem.
public class MyDialogFragment extends DialogFragment {
public static MyDialogFragment newInstance(int title) {
MyDialogFragment frag = new MyDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.plus_icon)
.setTitle(title).setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent i =getActivity().getIntent();
i.putExtra("key", true);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//AddExerciseFragment.doNegativeClick();
Intent i =getActivity().getIntent();
i.putExtra("key", false);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
.create();
}
}
onActivityResult in AddExerciseFragment
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
String path = null;
switch (requestCode) {
case DIALOG_FRAGMENT:
boolean check = imageReturnedIntent.getBooleanExtra("key", true);
if (check) {
doPositiveClick();
if (resultCode == RESULT_OK && requestCode == GALLERY_REQUEST) {
Uri selectedImage = imageReturnedIntent.getData();
path = getRealPathFromURI(selectedImage);
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
} else {
doNegativeClick();
Uri uri;
Cursor cursor = getActivity().getContentResolver().query(
Media.EXTERNAL_CONTENT_URI,
new String[] { Media.DATA, Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor
.getColumnIndex(Media.DATA)));
path = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
break;
}
}
public void doPositiveClick() {
DialogFlag = 0;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
// dialog.cancel();
}
public void doNegativeClick() {
DialogFlag = 1;
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_RESULT);
}
void showDialog() {
DialogFragment newFragment = MyDialogFragment
.newInstance(R.string.name);
newFragment.show(getFragmentManager(), "dialog");
}
But i have next:
If i want to set image from galery-it start galery, but i can not choose picture there
From camera i can set picture only once and only for one imageView
when i am in galery and press button "back" - i get error.

Categories

Resources