How can I save and get a image from my database - java

I take a picture and save the path into my SQLite database but it only saves 0 kb file and when I try to open it with the gallery it is not opening
this is my main activity:
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
Button btnTakePicture;
ImageView imageView;
String pathToFile;
Intent takePictureIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTakePicture = findViewById(R.id.btnTakePicture);
final EditText txtname = (EditText) findViewById(R.id.txtname);
Button mcbutton = (Button) findViewById((R.id.mcbutton));
Button listbutton = (Button) findViewById((R.id.listbutton));
final DataBase db = new DataBase(getApplicationContext());
try {
db.onCreate(db.getWritableDatabase());
} catch (Exception ex) {
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
btnTakePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
dispatchTakePictureIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mcbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname = txtname.getText().toString();
if (fname == null) {
Toast.makeText(getApplicationContext(), "Please enter something!!", Toast.LENGTH_SHORT).show();
return;
} else if (pathToFile == null) {
Toast.makeText(getApplicationContext(), "Please take a picture!!", Toast.LENGTH_SHORT).show();
return;
} else {
Model model = new Model(fname, pathToFile);
long id = db.ekleModel(model);
if (id > 0) {
Toast.makeText(getApplicationContext(), "Food Registration Perfect! ID = " + id, Toast.LENGTH_LONG).show();
txtname.setText("");
} else {
Toast.makeText(getApplicationContext(), "Please Enter a Food Name", Toast.LENGTH_LONG).show();
}
}
}
});
listbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Random.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
private void dispatchTakePictureIntent() throws IOException {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createPhotoFile();
} catch (IOException ex) {
}
}
}
private File createPhotoFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(storageDir, imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
pathToFile = image.getAbsolutePath();
return image;
}
and this is my other activity where I get the problem,
everything is supposed to work but I don't know why bitmap decode returns null...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random);
final EditText txtMulti = (EditText)findViewById(R.id.txtMulti);
final ImageView imageView = (ImageView)findViewById(R.id.imageView);
DataBase db = new DataBase(getApplicationContext());
List<Model> modellist = new ArrayList<Model>();
modellist = db.gelModelListesi();
StringBuilder sb = new StringBuilder();
for(Model _model: modellist){
String icerik = "";
icerik = "ID: "+_model.getId()+"Yemek Adı: "+_model.getFoodname()+ "\n\n";
File imgFile = new File(_model.getImagePath());
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getPath());
imageView.setImageBitmap(myBitmap);
}
sb.append(icerik);
}
txtMulti.setText(sb);
}

Related

I am uploading two different images in android upload in server through volley

public class MainRegister extends AppCompatActivity {
ImageView imageView, imageView2;
Button buttonUploadImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//initializing views
txtName = (EditText) findViewById(R.id.txtName);
imageView = (ImageView) findViewById(R.id.imageView);
imageView2 = (ImageView) findViewById(R.id.imageView2);
buttonUploadImage = (Button) findViewById(R.id.buttonUploadImage);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
finish();
startActivity(intent);
return;
}
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
findViewById(R.id.buttonUploadImage2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent j = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(j, 200);
}
});
findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadBitmap();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == 200 && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
try {
MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Bitmap bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView2.setImageBitmap(bitmap2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap() {
final Bitmap bitmap = imageView.getDrawingCache();
final Bitmap bitmap2 = imageView2.getDrawingCache();
final String name = txtName.getText().toString().trim();
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Registration is in Process Please wait...");
pDialog.show();
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, ConnectionActivity.UPLOAD_URL,
new Response.Listener < NetworkResponse > () {
#Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map < String, String > getParams() throws AuthFailureError {
Map < String, String > params = new HashMap < > ();
params.put("name", name);
return params;
}
#Override
protected Map < String, DataPart > getByteData() {
Map < String, DataPart > params = new HashMap < > ();
long imagename = System.currentTimeMillis();
params.put("pic", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
params.put("pic1", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap2)));
return params;
}
};
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
In this section text is upload but i'm trying to upload 2 different images through volley but image does not upload in this code. what is wrong in this code?
if(isset($_FILES['profile']['name']) && isset($_FILES['govtid']['name']) && isset($_POST['name']) && isset($_POST['email']) && isset($_POST['mobile']) && isset($_POST['bank']) && isset($_POST['bank'])){
//uploading file and storing it to database as well

Upload image from camera and gallery to firebase

As the title says, I am trying to upload images from both camera and gallery to firebase. But I have problems in both.
When I try to upload my image from the camera I get:
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
Even though my firebase rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
But when I try using the gallery I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.varroxsystems.plant.newPlant.Fileuploader(newPlant.java:192)
at com.varroxsystems.plant.newPlant.access$100(newPlant.java:57)
at com.varroxsystems.plant.newPlant$2.onClick(newPlant.java:162)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
And I get no data in the firebase real time database nor in the firebase storage.
But I use this exact code on another application and it works just fine.
Does anyone know what am I doing wrong?
Code:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plants = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plants.setPlname(pname);
plants.setPldate(pdate);
plants.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plants);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
}
}
private String getExtension(Uri uri)
{
ContentResolver cr=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void askFileReadPermission() {
if (ContextCompat.checkSelfPermission(newPlant.this,
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.CAMERA) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.CAMERA)||ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
alert();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile && writeExternalFile)
{
alert();
} else {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
private void alert() {
new androidx.appcompat.app.AlertDialog.Builder(newPlant.this)
.setTitle(null)
.setMessage("Where would you like to get your picture from?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Open Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dispatchTakePictureIntent();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton("Open Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
gallery.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(gallery,"Select Picture"), GALLERY_REQUEST_CODE);
}
})
.setIcon(android.R.drawable.ic_menu_camera)
.show();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
File f = new File(currentPhotoPath);
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(f).getPath());
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
uri = Uri.fromFile(f);
mediaScanIntent.setData(uri);
this.sendBroadcast(mediaScanIntent);
System.out.println(databaseHelper.getProfilesCount());
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
if (requestCode == GALLERY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
if (data != null){
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri curi = item.getUri();
uri = item.getUri();
File imageFile = new File(getRealPathFromURI(newPlant.this, curi));
//mArrayUri.add();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(curi);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
// DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
// Cursor cursor22 = mDatabaseHelper.GetPath();
// while (cursor22.moveToNext()){
// System.out.println("SELECTED " + cursor22.getString(i));
// }
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
Log.v("LOG_TAG", "Selected Images ");
}else {
//Toast.makeText(profuctadd.this,"NO IMAGE EXCEPTION",Toast.LENGTH_LONG).show();
System.out.println(data.getData());
if (data.getData()!=null){
Uri contentUri = data.getData();
uri = data.getData();
System.out.println("CONTENT URI "+contentUri);
File imageFile = new File(getRealPathFromURI(newPlant.this, uri));
System.out.println("FILE "+imageFile);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(uri);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
//DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
//Cursor cursor22 = mDatabaseHelper.GetPath();
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
// }
}
}
}
}
private String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
return "";
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private String getFileExt(Uri contentUri) {
ContentResolver c = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(c.getType(contentUri));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
Toast.makeText(newPlant.this,ex.getMessage(),Toast.LENGTH_LONG).show();
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.varroxsystems.plant.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}

How can I fix my app crash after take a photo in android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
How can I fix my app crash after take a photo in android, I am currently making an application to report to the streets via photos, but I have a problem when the user has taken a picture through the camera, when I press the application button to crash, the following reports of crashes that occur
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.dbothxrpsc119.soppeng/com.dbothxrpsc119.soppeng.LaporanActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4332)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4376)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at com.dbothxrpsc119.soppeng.LaporanActivity.setPic(LaporanActivity.java:262)
at com.dbothxrpsc119.soppeng.LaporanActivity.onCaptureImageResult(LaporanActivity.java:271)
at com.dbothxrpsc119.soppeng.LaporanActivity.onActivityResult(LaporanActivity.java:206)
at android.app.Activity.dispatchActivityResult(Activity.java:7351)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4328)
... 9 more
for the reportactivity code snippet as follows
public class LaporanActivity extends AppCompatActivity {
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private EditText edPesanKirim;
private Button btnUpload;
private ImageView ivImage;
private String userChoosenTask;
String mCurrentPhotoPath;
Uri photoURI;
public static final String UPLOAD_KEY = "image";
public static final String TAG = "Laporan";
private Bitmap bitmap;
private SQLiteDatabase db;
private Cursor c;
String pesan,nama,ktpsim,alamat,hp;
Boolean sudahUpload = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_laporan);
db=openOrCreateDatabase("User", Context.MODE_PRIVATE, null);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
edPesanKirim = (EditText) findViewById(R.id.edPesanKirim);
btnUpload = (Button) findViewById(R.id.btnUpload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//check jika data belum lengkap
c = db.rawQuery("SELECT * FROM users",null);
boolean exists = (c.getCount() > 0);
if(exists) {
c.moveToFirst();
pesan = edPesanKirim.getText().toString();
nama = c.getString(1);
ktpsim = c.getString(2);
alamat = c.getString(3);
hp = c.getString(4);
if (!c.getString(0).equals("") || !c.getString(1).equals("") || c.getString(2).equals("")
|| c.getString(3).equals("") || c.getString(4).equals("")) {
if (!pesan.equals("")) {
if (sudahUpload.equals(true)) {
uploadImage("gambar");
} else {
uploadImage("pesan");
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan isi gambar dan pesan terlebih dahulu",Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
startActivity(intent);
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
startActivity(intent);
}
c.close();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Ambil Photo"))
cameraIntent();
else if(userChoosenTask.equals("Pilih dari Galery"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Ambil Photo", "Pilih dari Galery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(LaporanActivity.this);
builder.setTitle("Tambah Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(LaporanActivity.this);
if (items[item].equals("Ambil Photo")) {
userChoosenTask ="Ambil Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Pilih dari Galery")) {
userChoosenTask ="Pilih dari Galery";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Pilih File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
photoFile.delete();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("Photo",ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.dbothxrpsc119.soppeng.fileprovider",
photoFile);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "DebotHaxor_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
//mCurrentPhotoPath = "file:" + image.getAbsolutePath();
mCurrentPhotoPath = image.getAbsolutePath();
//mCurrentPhotoPath = image;
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = photoURI;
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setPic() {
// Get the dimensions of the View
int targetW = ivImage.getWidth();
int targetH = ivImage.getHeight();
//Log.d("Photo","Set Pic "+mCurrentPhotoPath);
Bitmap real_bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap_view = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
ivImage.setImageBitmap(bitmap_view);
Log.d("Photo","Tampilkan Foto "+ mCurrentPhotoPath);
//resize
Bitmap resized;
resized = Bitmap.createScaledBitmap(bitmap_view,(int)(real_bitmap.getWidth()*0.4), (int)(real_bitmap.getHeight()*0.4), true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
bitmap = resized;
}
private void onCaptureImageResult() {
galleryAddPic();
setPic();
sudahUpload = true;
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
bitmap = bm;
sudahUpload = true;
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(String mode){
class UploadImage extends AsyncTask<Bitmap,Void,String> {
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LaporanActivity.this, "Kirim Pesan", "Mohon tunggu...",true,true);
loading.setCanceledOnTouchOutside(false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
String msg = "";
if (s.equals("ok")) {
msg = "Pesan sukses terkirim";
clearForm();
} else {
msg = getString(R.string.api_error);
}
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Bitmap... params) {
HashMap<String,String> data = new HashMap<>();
if (params.length > 0) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
data.put(UPLOAD_KEY, uploadImage);
}
data.put("pesan", pesan);
data.put("device_id", Utility.uniqDevice(LaporanActivity.this));
String uri = "https://"+ getString(R.string.api_url) + "/path/kirim_pesan";
String result = rh.sendPostRequest(uri,data);
return result;
}
}
UploadImage ui = new UploadImage();
if (mode.equals("gambar"))
ui.execute(bitmap);
else
ui.execute();
}
private void clearForm() {
ivImage.setImageResource(R.drawable.ic_menu_gallery);
edPesanKirim.setText("");
btnSelect.setFocusable(true);
}
}
I believe that the problem is that you create uri for a file to store photo but didn't put it in intent. Please, try following:
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.dbothxrpsc119.soppeng.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(intent, REQUEST_CAMERA);
}

Selecting multiple photos from gallery and returning them in the grid view

I asked a question a couple of days ago that I'm building an app that converts multiple photos from gallery or camera to convert them to a gif file. Someone replied with the following code:
// For multiple images
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
adapter.clear();
viewSwitcher.setDisplayedChild(1);
String single_path = data.getStringExtra("single_path");
imageLoader.displayImage("file://" + single_path, imgSinglePick);
} else if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
viewSwitcher.setDisplayedChild(0);
adapter.addAll(dataT);
}
}
When I replace the intent for selecting photos with that intent and onActivityResult code it gets me lots of errors and highlights the code red starting with action.Action_multiple_pick as if there is no such thing in java.
My actual code:
public class MainActivity extends AppCompatActivity {
/**
* this is the destination of the new GIF file, it will be saved directly in the SD card
* (internal storage) in a file named "test.gif"
*/
private static final String IMAGE_PATH = "/sdcard/test.gif";
private static final int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private boolean zoomOut = false;
private Button btnSelect;
private LinearLayout root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (root.getChildCount() == 0) {
return;
}
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(IMAGE_PATH);
outStream.write(generateGIF());
outStream.close();
Toast.makeText(MainActivity.this,
"GIF saved to " + IMAGE_PATH, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outStream != null) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
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);
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/* video/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[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 == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
// the following code causes a crash "NullPointerException" :
// Point point = null; // --> the reason for the crash
// getWindowManager().getDefaultDisplay().getSize(point);
// int width = point.x;
// int height = point.y;
//
// ivImage.setMinimumWidth(width);
// ivImage.setMinimumHeight(height);
//
// ivImage.setMaxWidth(width);
// ivImage.setMaxHeight(height);
// ivImage.getLayoutParams().width = 20; // --> another crash happens here
// ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.WRAP_CONTENT,
GridLayout.LayoutParams.MATCH_PARENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
// setContentView(root);
// ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut = false;
} else {
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
private byte[] generateGIF() {
ArrayList<Bitmap> bitmaps = new ArrayList<>();
View v;
ImageView iv;
for (int i = 0; i < root.getChildCount(); i++) {
v = root.getChildAt(i);
if (v instanceof ImageView) {
iv = (ImageView) v;
bitmaps.add(((BitmapDrawable) iv.getDrawable()).getBitmap());
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
Please help me out

Create folder and store Image by camera

please read my code ask solution how to create folder
public class CameraActivity extends ActionBarActivity {
private static final int ACTION_TAKE_IMAGE = 1;
Button btnImage;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView = (ImageView)findViewById(R.id.imageView);
btnImage= (Button) findViewById(R.id.buttonCapture);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takeVideoIntent, ACTION_TAKE_IMAGE);
}
});
}
#onActivityResult start
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
try
{
AssetFileDescriptor imageAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = imageAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"/Vipul/RecordImage/");
if (!root.exists()) {
System.out.println("No directory");
root.mkdirs();
}
File file;
file=new File(root,"IMG_"+System.currentTimeMillis()+".jpg" );
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if(requestCode == ACTION_TAKE_IMAGE && resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
Bitmap imageBitmap = (Bitmap) bundle.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
}
this code work 2.3 capture Image but work and not create folder not store in my specific folder please ask your answer
UPDATE
//declare
int num = 0;
//.....//
//*onclik button
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Create folder
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "Myfolder");
imagesFolder.mkdirs();
//Asign name for image
File image = new File(imagesFolder, "Pic" + (num +1) + ".png");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//launch camera app with result code (forResult)
startActivityForResult(cameraIntent, 1);
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK)
{
//create bitmap with image
Bitmap bMap = BitmapFactory.decodeFile(
Environment.getExternalStorageDirectory() +
"/Myfolder/" + "Pic" + num + ".png");
//Add bitmap to ImageView
//Show on screen
imageView.setImageBitmap(bMap);
}
To use different name for image everytime you can use method getTimeInMillis() as Calendar mCalendar = Calendar.getInstance();
String n = ""+mCalendar.getTimeInMillis();
String fname = "Pic-" + n.substring(5) + ".png";
//Asign name for image
File image = new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);
try this code
public class CameraActivity extends ActionBarActivity {
// private static final int ACTION_TAKE_IMAGE = 1;
Button btnImage;
ImageView imageView;
File image;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView = (ImageView) findViewById(R.id.imageView);
btnImage = (Button) findViewById(R.id.buttonCapture);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Create folder
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "Vipul/image");
imagesFolder.mkdirs();
//Asign name for image
String fname = "Pic-" + System.currentTimeMillis() + ".png";
image= new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//launch camera app with result code (forResult)
startActivityForResult(cameraIntent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
}
}
}
final solution

Categories