Android image is not uploading in ftp server - java

Uploading image from android phone to Ftp server, It is not uploading my image into Ftp server it shows windows leaked error,it shows sdcard path but the image is not uploading into the ftp folder can anyone please help me.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSetImage = (Button) findViewById(R.id.btnSelectPhoto);
upload = (Button) findViewById(R.id.upload_btn);
btnSetImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Uploading",
"Please wait...", true);
dialog.setCancelable(true);
//File f = new File("file:///android_asset/launcher.png");
// Log.i("do in image ", tempPath);
new doFileUpload().execute();
}
});
}
class doFileUpload extends AsyncTask<Void, Void, String> {
// Log.i("do in image ", path);
String hostName = "xxxxx";
String username = "dsdadg";
String password = "adasdh";
InputStream in = null;
protected String doInBackground(Void... unsued) {
String loc = tempPath.toString();
Log.i("location in async ", loc);
try {
FTPClient ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/ftp/gallery/"); // FTP folder path
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Success");
}
File f1 = new File("/sdcard/Image/003.JPG");
in = new FileInputStream(f1);
ftp.storeFile("/ftp/gallery/", in);
ftp.enterLocalPassiveMode();
System.out.println("SUCCESS");
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return hostName;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[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, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
ivImage.setImageBitmap(bm);
path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
tempPath = getPath(selectedImageUri, MainActivity.this);
Log.i("temporary path", tempPath);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
ivImage.setImageBitmap(bm);
}
}
//return urlPosting;
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}

Related

Upload a photo from camera or gallery in android

Having the following error:
android.os.FileUriExposedException: file:///storage/emulated/0/temp.jpg exposed beyond app through ClipData.Item.getUri()
when I choose Option Camera from chosen AlertDialog
And the following error when I try to choose a photo from Gallery:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0 (Is a directory)
The Gallery opens up, but I can't choose an image to set it to my ImageView
Here is the code:
public class MainActivity extends AppCompatActivity {
private Button contactsButton, galleryButton;
public static final int Gallery_Code = 100;
public static final int Contacts_Code = 101;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsButton = findViewById(R.id.buttonContacts);
galleryButton = findViewById(R.id.buttonGallery);
imageView = findViewById(R.id.imageView);
contactsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkPermission(Manifest.permission.READ_CONTACTS, Contacts_Code);
}
});
galleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
}
private void uploadImage() {
final String[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Upload Photo");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
File[] files = f.listFiles();
if (files != null) {
for (File temp : files) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
imageView.setImageBitmap(thumbnail);
}
}
}
private void checkPermission(String readContacts, int contacts_code) {
if (ContextCompat.checkSelfPermission(MainActivity.this, readContacts)
== PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{readContacts},
contacts_code);
} else {
Toast.makeText(MainActivity.this,
"Permission already granted",
Toast.LENGTH_SHORT)
.show();
if (contacts_code == Contacts_Code) {
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super
.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == Gallery_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Gallery Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else {
Toast.makeText(MainActivity.this,
"Gallery Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == Contacts_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Contacts Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Toast.makeText(MainActivity.this,
"Contacts Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
}
} }

Failed to pass image to another class

I'm trying to pass an image to another class through intent, but it only works for captured image, not for image selected from gallery.
This is where the camera function get started.In ImageFitScreen.java, it has a ok button used to return back to the previous activity.
ImageFitScreen.java
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));
//pic = f;
// Toast.makeText(getApplicationContext(), Uri.fromFile(f) +"", Toast.LENGTH_LONG).show();
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){
dialog.dismiss();
finish();
}
return true;
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
//h=0;
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
//pic = photo;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inDither = true;
bitmapOptions.inSampleSize=8;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
Global.img = bitmap;
b.setImageBitmap(bitmap);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
//p = path;
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
//pic=file;
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
// h=1;
//imgui = selectedImage;
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ******", picturePath + "");
b.setImageBitmap(thumbnail);
}
}
else
{
finish();
}
ok.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Previous Activity
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); // image can be displayed
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
b.setOnClickListener(new View.OnClickListener() { // save button
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
returnIntent.putExtra("c",c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
**The image can be returned to Previous Activity ** since it can display in viewImage. In previous activity, it also has a button back to Activity A.
Activity A
c = (TextView) claims.findViewById(R.id.textView49);
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), EditClaims.class);
intent.putExtra("name", name);
intent.putExtra("result", result);
intent.putExtra("description", description);
byte[]data=getBitmapAsByte(getActivity(), Global.img);
intent.putExtra("data",data);
startActivity(intent);
}
else {
Toast.makeText(getActivity().getApplicationContext(), "null", Toast.LENGTH_LONG).show();
}
}
} );
public static byte[]getBitmapAsByte(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, outputStream);
return outputStream.toByteArray();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int button = data.getIntExtra("k1", 0);
if (button == 1) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description=data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as=Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
}
else if(requestCode==CAMERA_REQUEST_CODE)
{
}
Activity B (Activity)
if(getIntent().hasExtra("data")) {
// ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("data"),0,getIntent().getByteArrayExtra("data").length);
viewImage.setImageBitmap(b);
}
Global.java
public class Global {
static Bitmap img;
}
When it intent to Activity B, my app will exit automatically. But it will works if the image is captured image. Is it because the size too large? I have no ide on this.Can someone help me? Thanks a lot!
You shouldn't put bitmap into Bundle. The best way is saving image on storage and pass path uri between activities.
byte [] recieve = getIntent().getByteArrayExtra("key",defaultValue);

Cannot take picture or choose image from gallery

Sorry guys, I'm very new to android and now need to create a simple camera in my android studio.
When I choose an image from gallery or take a picture, it will crashed.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.camera_main, container, false);
b=(Button)claims.findViewById(R.id.btnSelectPhoto);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
return claims;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Claims.this.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) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity. RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
LogCat Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=2, result=-1, data=Intent { dat=content://com.sec.android.gallery3d.provider/picasa/item/5843197728949359042 (has extras) }} to activity {com.example.project.project/com.example.project.project.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3752)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3795)
Can someone explain to me why would this happen and how to fix it?
Thanks a lot :)
you can using this method
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_REQUEST_CODE = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String IMG_FILE_NAME = "tempImg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// From Gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_REQUEST_CODE);
// Take a Picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(GetOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public static File GetOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory() + "/" + HConstants.IMG_FILE_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ IMG_FILE_NAME + ".jpg");
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == IMAGE_REQUEST_CODE){
fileUri = data.getData();
Log.i(getClass().getName(), "fileUri" + fileUri);
}else{
Log.i(getClass().getName(), fileUri);
}
}
}
}
Getting Image from Gallery.
Try the following code.Hopefully it will work
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) 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);
}
});
}
#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));
}
}
}
Taking Picture
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
Also add the permissions in Manifest File:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Save Image to SD Card in android

I am new to android, I am trying to create an a app to take a photo or upload to the screen (which I have currently working) and then save the image to the SD card by clicking on a button. when I chick on the save button the app stops working, any help will be appreciated. Below is my code
public class Upload extends Fragment {
private Button bt_browse;
private ImageView iv_photo;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String uploadImagePath = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.upload,
container, false);
bt_browse = (Button) rootView.findViewById(R.id.button1);
iv_photo = (ImageView) rootView.findViewById(R.id.iv_photo);
bt_browse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
return rootView;
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[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, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv_photo.setImageBitmap(bm);
uploadImagePath = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
iv_photo.setImageBitmap(bm);
uploadImagePath = tempPath;
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
//automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
OnMenuItemClickListener SaveImageClickListener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Bitmap bitmap;
OutputStream output;
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_camera);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Save Image Example");
dir.mkdirs();
File file = new File(dir, "myimage.png");
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
};
}
Have you got the WRITE_EXTERNAL_STORAGE permission on your manifest file? If not, add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Android - Why won't my Toast message show?

My toast doesn't show up and I am confused because I think I made it correctly, I don't understand. As you can see its a program that shows three buttons, the first one activates a download which is supposed to open the PDFs file automatically - if there is no pdf reader a toast should pop up saying there isn't a reader. the other buttons take to a new screen and operate as a back button.
public class myactivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mProgressDialog = new ProgressDialog(myactivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Button Section = (Button) findViewById(R.id.Section);
Section.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent Section = new Intent(view.getContext(),
Section.class);
startActivity(Section);
}
});
Button Back = (Button) findViewById(R.id.Back);
Back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_OK);
finish();
}
});
startBtn = (Button) findViewById(R.id.Search);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/document.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
}
private void showPdf() {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
}
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
The above code show toast only if you have not declared the activity in your manifeast file but not when the pdf is not present. You must use FileNotFoundException for your requirement.
Updated:::
try{
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}

Categories

Resources