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
Related
The onActivityResult() did not called when I select image from camera or gallery and my activity crashed, my code is below:
private void selectImage() {
final CharSequence[] options = { "cam", "gallery","cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(FragmentActivity4.this);
builder.setTitle("add");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(FragmentActivity4.this);
if (options[item].equals("cam"))
{
if(result){
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("gallery"))
{
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
startActivityForResult(chooserIntent, 2);
}
else if (options[item].equals("cancel")) {
ivImage.setImageDrawable(ContextCompat.getDrawable(FragmentActivity4.this, R.drawable.plusrred));
dialog.dismiss();
}
}
});
builder.show();
}
and in my onActivityResult():
#Override
protected 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);
ivImage.setImageBitmap(bitmap);
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.03), (int)(bitmap.getHeight()*0.03), true);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.PNG, 0, baos1);
byte[] imgBytes = baos1.toByteArray();
base64String1 = Base64.encodeToString(imgBytes, Base64.DEFAULT);
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.PNG, 0, 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 = FragmentActivity4.this.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+"");
ivImage.setImageBitmap(thumbnail);
Bitmap thumbnail1 = Bitmap.createScaledBitmap(thumbnail,(int)(thumbnail.getWidth()*0.03), (int)(thumbnail.getHeight()*0.03), true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail1.compress(Bitmap.CompressFormat.PNG,0, baos);
byte[] imgBytes = baos.toByteArray();
base64String1 = Base64.encodeToString(imgBytes,
Base64.DEFAULT);
}
}
My activity extends AppCompatActivity.
Could you please tell me where is the problem?
Here you have
startActivityForResult(chooserIntent, 2);
and in your onActivityResult method you don't include 2 in your if statement. I think the problem is in that.
Your RequestCode is 2.
Change this:
if (requestCode == 1) {
With this:
if (requestCode == 2) {
using custom camera how can we show the preview of the fullsize image after the image is being clicked from camera clicked and in preview if we can show whether to accept the image or discard the image before saving it to SD card.(Hint: As used in watsapp)
You will get image in byte[], you can convert this byte[] into bitmap and can show it in ImageView
Bitmap bitmap = BitmapFactory.decodeByteArray(yourbytearray, 0, yourbytearray.length);
The complete code according to your requirement is given below. Just follow this.Here uImage is Bitmap and imageView is the imageview where your image will be displayed.
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddownRecipeFromHome.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();
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
#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();
uImage = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(uImage);
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);
uImage.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();
uImage = (BitmapFactory.decodeFile(picturePath));
Log.e("path of imag", ""+picturePath);
imageView.setImageBitmap(uImage);
}
else if (requestCode == 3) {
try {
Log.e("testing", "return data is " + data.getData());
String filePath = Environment.getExternalStorageDirectory()
+ "/" + TEMP_PHOTO_FILE;
System.out.println("path " + filePath);
uImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
uImage.compress(Bitmap.CompressFormat.PNG, 100, bao);
ba = bao.toByteArray();
imageView.setImageBitmap(uImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}
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");