I'm having some problems with my android app. My idea is to see the photo I take using my app or to choose from my custom gallery and see it. First of all I'm having problems with viewing the image, in particular I catch a null pointer exception when i try to see the bitmap, then when I try to see a photo from gallery the app crashes maybe because I'm unable to make the directory refresh properly.
Here is my code:
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fotocamera);
b=(Button)findViewById(R.id.btnSelectPhoto);
//viewImage=(ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is present.
getMenuInflater().inflate(R.menu.fotocamera, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Scatta una foto", "Scegli una foto dalla galleria", "Carica una foto", "Annulla" };
AlertDialog.Builder builder = new AlertDialog.Builder(FotocameraActivity.this);
builder.setTitle("Cosa vuoi fare?");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Scatta una foto")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoDirectory = new File(Environment.getExternalStorageDirectory()+ File.separator + "FTRRome");
File camdir = new File("/external/images/media");
boolean res = camdir.exists();
System.out.println(res);
if(!photoDirectory.exists()) {
photoDirectory.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
File f = new File(photoDirectory, (currentDateandTime+".jpg"));
lastPhoto = f;
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
System.out.println(photoDirectory.getAbsolutePath());
System.out.println(lastPhoto.getAbsolutePath());
startActivityForResult(intent, 1);
}
/*else if (options[item].equals("Scegli una foto dalla galleria")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
System.out.println(Environment.getExternalStorageDirectory());
System.out.println(photoDirectory);
//sendBroadcast (new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory()+"/FTRRome/")));
}
else if (options[item].equals("Carica una foto dalla galleria")) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
System.out.println(Environment.getExternalStorageDirectory());
System.out.println(photoDirectory);
sendBroadcast (new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory()+"/FTRRome/")));
startActivityForResult(intent, 3);
}
else if (options[item].equals("Annulla")) {
dialog.dismiss();
}
*/
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
System.out.println("Questo รจ il codice di risultato: " + requestCode);
if (requestCode == 1) {
try {
System.out.println("Creo bitmap");
Bitmap bitmap;
System.out.println("Setto bitmap options");
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
System.out.println("Setto decodifica");
bitmap = BitmapFactory.decodeFile(lastPhoto.getAbsolutePath(),bitmapOptions);
System.out.println("Chiedo visualizzazione");
viewImage.setImageBitmap(bitmap);
OutputStream outFile = null;
try {
outFile = new FileOutputStream(lastPhoto);
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();
System.out.println(selectedImage.getPath());
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 from gallery: ", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
*/
}
}
}`
Related
Hi guys, how can I upload the image to my filemanager on my webhost when I click the button rent? As of now I don't start on anything because I tried to upload it the way I upload from gallery and It didnt work. Can you help me guys? As of now I cleaned my code and this is it
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("txtCarModel", tvCarModel.getText().toString());
postData.put("txtCarType", tvCarType.getText().toString());
postData.put("txtCapacity", tvCapacity.getText().toString());
postData.put("txtPlateNumber", tvPlateNumber.getText().toString());
postData.put("image", toString());
postData.put("txtFuelType", tvFuelType.getText().toString());
postData.put("txtOwner", tvPoster.getText().toString());
if (TextUtils.isEmpty(etResDate.getText().toString())) {
Toast.makeText(this, "Insert reservation date.", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtResDate", etResDate.getText().toString());
if (TextUtils.isEmpty(etResTime.getText().toString())) {
Toast.makeText(this, "Insert reservation time.", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtResTime", etResTime.getText().toString());
if (TextUtils.isEmpty(etResLocation.getText().toString())) {
Toast.makeText(this, "Insert pickup location.", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtResLocation", etResLocation.getText().toString());
postData.put("txtRenter", pref.getString("username","").toString());
PostResponseAsyncTask taskPost = new PostResponseAsyncTask(DetailActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if (s.contains("New records created successfully")) {
Log.d(TAG, s);
Toast.makeText(DetailActivity.this, "Wait for owners approval", Toast.LENGTH_SHORT).show();
Intent in = new Intent(DetailActivity.this, RenterTabs.class);
startActivity(in);
finish();
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
taskPost.execute("http://carkila.esy.es/rent.php");
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
CustomerRegistration.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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());
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);
// Rorate to portraite
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(f.getAbsolutePath()));
bitmap = Bitmap
.createBitmap(bitmap,0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
// End rotrate to portait
//set Image view
img_user_photo.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 bitmap = (BitmapFactory.decodeFile(picturePath));
// Rorate to portraite
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(picturePath));
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
//set Image view
img_user_photo.setImageBitmap(bitmap);
}
}
}
// *****Just call method selectImage() ******
img_user_photo //Image view
I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.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(), "Image.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();
}
#SuppressLint("Assert")
#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());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} 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);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
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();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});
I have a imageview and clicking on it displays a dialog box and when clicked on each dialog item I can see a camera invoked or gallery invoked. But now after I get the image on the imageview how can I get the path of the image as an extra may be.
image_view = new ImageView(this);
image_view.setId(field_id);
image_view.setImageDrawable(getResources().getDrawable(
R.drawable.ic_launcher));
image_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
Dynamic_layout.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(), "image1.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,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} 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());
for (File temp : f.listFiles()) {
if (temp.getName().equals("image1.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
image_view.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "PHOTO" + 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();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath,
bitmapOptions));
Log.w("path of image in gallery", picturePath + "");
image_view.setImageBitmap(thumbnail);
}
}
}
Create a global variable String imagePath (outside onCreate) so all methods can access it.
Use this variable to get your path, so it can be used in the entire class :
try {
//add this
imagePath= f.getAbsolutePath();
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Now you can use imagePath anywhere in the class.
I am working on a project where I have two choices, either I click a photo and the same image is attached to the mail and can be sent. The second is I select the image from the gallery and the image selected is sent as an attachment in the mail.I am able to do the later part but have problem in attaching image after clicking it using camera.
public class MainActivity extends Activity implements OnClickListener {
Button select;
ImageView photo;
EditText et_subject, et_message;
TextView tv_attach;
String subject, message;
private static final int PICK_IMAGE = 100;
Uri URI = null;
Uri URI1= null;
int columnindex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
select = (Button)findViewById(R.id.button1);
photo = (ImageView)findViewById(R.id.imageView1);
et_subject = (EditText)findViewById(R.id.editText1);
et_message = (EditText)findViewById(R.id.editText2);
tv_attach = (TextView)findViewById(R.id.textView1);
photo.setOnClickListener(this);
select.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageView1:
selectImage();
break;
case R.id.button1:
subject = et_subject.getText().toString();
message = et_message.getText().toString();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"example#xyz.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
if (URI != null || URI1 != null)
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
startActivity(emailIntent);
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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());
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);
photo.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
URI1 = Uri.parse("file://" + 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);
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);
URI = Uri.parse("file://" + picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
photo.setImageBitmap(thumbnail);
}
}
}
}
I've tried something but seems I'm wrong.
Please help me what can be done? Can anybody make changes in the code that I've used?
I tried it and it worked for me, hope it helps!
mail_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"fake#fake.edu"});
i.putExtra(Intent.EXTRA_SUBJECT,"On The Job");
//Log.d("URI#!##!#!###!", Uri.fromFile(pic).toString() + " " + pic.exists());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
i.setType("image/png");
startActivity(Intent.createChooser(i,"Share you on the jobing"));
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(thumbnail);
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
pic = new File(root, "pic.png");
FileOutputStream out = new FileOutputStream(pic);
thumbnail.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
}
I have problem with java class android for upload a file to a remote server.
In the form I select the file on gallery image on smartphone, but the output of bitmap always show null and the form start is blocked.
Log.d("HomeActivity.class", "Output: " + bitmap);
This is beginning to make me believe my structure as a whole is not correct.
What am I missing ?
What's wrong with the code?
I would greatly appreciate any help you can give me in working this problem.
public class HomeActivity extends Activity {
Button btnSend;
Spinner area;
EditText description;
ImageView viewImage;
Button b, upload;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
b = (Button) findViewById(R.id.btnSelectPhoto);
viewImage = (ImageView) findViewById(R.id.viewImage);
upload = (Button) findViewById(R.id.button1);
area = (Spinner) findViewById(R.id.my_spinner_new);
description = (EditText) findViewById(R.id.editText);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (area.getSelectedItem().toString().trim()
.equalsIgnoreCase("Select area")) {
Toast.makeText(HomeActivity.this, "Area.",
Toast.LENGTH_SHORT).show();
} else if (description.getText().toString().length() <= 0) {
description.setError("description");
} else if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"pic", Toast.LENGTH_SHORT)
.show();
Log.d("HomeActivity.class", "Output: " + bitmap);
} else {
ProgressDialog.show(HomeActivity.this,
"Uploading" + bitmap, "Please wait...", true);
}
}
});
new Thread() {
#Override
public void run() {
String path = "http://localhost/list.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u
.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[5120 * 512];
in.read(buffer);
bo.write(buffer);
String s = bo.toString();
final Vector<String> str = new Vector<String>();
String[] line = s.split("\n");
int index = 0;
while (index < line.length) {
str.add(line[index]);
index++;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Spinner spinner = (Spinner) findViewById(R.id.my_spinner_new);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
HomeActivity.this,
android.R.layout.simple_spinner_item, str);
spinner.setAdapter(adapter);
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
Log.d("HomeActivity.class", "Valore restituito: " + 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));
Log.w("path of image from gallery......******************.........",
picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
edit#1
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (area.getSelectedItem().toString().trim()
.equalsIgnoreCase("Select area")) {
Toast.makeText(HomeActivity.this, "Area.",
Toast.LENGTH_SHORT).show();
} else if (description.getText().toString().length() <= 0) {
description.setError("description");
} else if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"pic", Toast.LENGTH_SHORT)
.show();
Log.d("HomeActivity.class", "Output: " + bitmap);
} else {
ProgressDialog.show(HomeActivity.this,
"Uploading" + bitmap, "Please wait...", true);
}
}
});
You are starting your upload thread in onCreate. And so bitmap is null. Better start your thread in an onClick handler.
By the way: Log.d("HomeActivity.class", "Output: " + bitmap);. That is awfull trying to print a bitmap. If you want to check if the bitmap is null the do so:
if ( bitmap==null )
Log.d(TAG, "bitmap==null");
else
Log.d(TAG, "we have a nice bitmap");