I have code to upload image and text to the server, but my code encodes the image and in the server the image should be decoded.
I want to prevent image encoding. I've tried some ways but they're not working.
I don't know how to do this. Please help me.
Here is my code:
public class Share_food extends Activity {
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String imgPath, fileName;
Bitmap bitmap;
private static int RESULT_LOAD_IMG = 1;
EditText ti,desc;
TextView tv;
String url="http://example.com/index.php";
#SuppressLint("CutPasteId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.share_food);
prgDialog = new ProgressDialog(this);
prgDialog.setCancelable(false);
ti= (EditText)findViewById(R.id.title);
desc=(EditText)findViewById(R.id.share_desc22);
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon( new ColorDrawable(getResources().getColor(android.R.color.transparent)));
//getActionBar().setTitle("");
}
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
} else {
Toast.makeText(this, "error",
Toast.LENGTH_LONG).show();
imgPath="2";
}
} catch (Exception e) {
Toast.makeText(this, "error...!", Toast.LENGTH_LONG)
.show();
}
}
public void uploadImage(View v) {
if (imgPath != null && !imgPath.isEmpty()) {
prgDialog.setMessage("process");
prgDialog.show();
encodeImagetoString();
} else {
prgDialog.setMessage("process");
prgDialog.show();
triggerImageUpload();
}
}
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
#Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
#Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("upload");
params.put("title", ti.getText().toString().trim());
//desc
//params.put("desc",desc.getText().toString().trim());
params.put("image", encodedString);
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
params.put("title", ti.getText().toString().trim());
//desc
//params.put("desc", desc.getText().toString().trim());
makeHTTPCall();
}
public void makeHTTPCall() {
prgDialog.setMessage("connecting");
AsyncHttpClient client = new AsyncHttpClient();
client.post(url,
params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
prgDialog.hide();
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
}
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(
getApplicationContext(),
"error !!!"
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prgDialog != null) {
prgDialog.dismiss();
}
}
}
you have to decode the string in receiving end and save the decoded one. post the code of receiving end too for more convenience.
Related
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
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);
}
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);
}
I have tried many things to handle this error. I was facing the same issue when i was using picasso before glide. When ever i click on "change photo" and select a photo from gallery or camera etc and want to set that selected image in the "Update Activity" in the image view. It throws out of memory exception. I am resizing the image size to 500x500 and compress it then trying to set it in the image view but it stills goes out of memory.I guess the problem is that i am not freeing this memory allocated but i searched but did not get any idea. Thanks in advance.
package com.donateblood.blooddonation;
/**
* Created by YouCaf Iqbal on 6/29/2016.
*/
public class UpdateActivity extends AppCompatActivity {
#InjectView(R.id.image)
ImageView _USERImage;
#InjectView(R.id.input_name)
EditText _nameText;
#InjectView(R.id.btnchangephoto)
Button changePhoto;
#InjectView(R.id.input_password)
EditText _passwordText;
#InjectView(R.id.input_number)
TextView _numText;
public static boolean UpdatingPhoto = false;
public String encodedPhotoString = null;
public String ChangedName = null;
public String ChangedPassword = null;
public String ChangedContactNo = null;
HashMap<String, String> ThingsTobeUpdated = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.updateactivity);
ButterKnife.inject(this);
}catch (OutOfMemoryError e){
Toast.makeText(getBaseContext(), "Sorry,Something went wrong, try again", Toast.LENGTH_SHORT).show();
}
ThingsTobeUpdated = new HashMap<>();
CheckImage();
changePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdatingPhoto = true;
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UpdateActivity.this.finish();
}
});
}
public void CheckImage() {
if (CroppingActivity.newImage != null) {
Drawable drawable = _USERImage.getDrawable();
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
bitmap.recycle();
CroppingActivity.newImage = getResizedBitmap(CroppingActivity.newImage,500,500);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
CroppingActivity.newImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Uri uri = getImageUri(CroppingActivity.newImage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Glide.with(UpdateActivity.this).load(file).override(400,400).placeholder(R.drawable.user).error(R.drawable.error)
.centerCrop().crossFade().bitmapTransform(new CropCircleTransformation(UpdateActivity.this)).into(_USERImage);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
} else {
Glide.with(UpdateActivity.this).load(getImageURL()).override(400,400).placeholder(R.drawable.user).error(R.drawable.error)
.centerCrop().crossFade().bitmapTransform(new CropCircleTransformation(UpdateActivity.this)).into(_USERImage);
}
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UpdateActivity.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(UpdateActivity.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getImageURL(){
return "http://abdulbasit.website/blood_app/images/"+LoginActivity.ImageofLoggedINUser;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_update, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String ChangesHappened = "no";
if (item.getItemId() == R.id.done_update) {
// start updating process
if(_nameText.getText().toString().equals("")){
ChangedName = null;
}else {
ChangedName = _nameText.getText().toString();
ChangesHappened = "yes";
}
if(_passwordText.getText().toString().equals("")){
ChangedPassword = null;
}else {
ChangedPassword = _passwordText.getText().toString();
ChangesHappened = "yes";
}
if(_numText.getText().toString().equals("")){
ChangedContactNo = null;
}else {
ChangedContactNo = _numText.getText().toString();
ChangesHappened = "yes";
}
if(encodedPhotoString!=null){
ChangesHappened = "yes";
}
if(ChangesHappened=="yes"){
StartUpdate();
return true;
}else {
Toast.makeText(getBaseContext(), "Nothing to update", Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
private void StartUpdate() {
ThingsTobeUpdated.put("email", LoginActivity.EmailofLoggedInUser);
if (encodedPhotoString != null) {
ThingsTobeUpdated.put("image", encodedPhotoString);
}
if (ChangedName != null) {
ThingsTobeUpdated.put("name", ChangedName);
}
if (ChangedPassword != null) {
ThingsTobeUpdated.put("password", ChangedPassword);
}
if (ChangedContactNo != null) {
ThingsTobeUpdated.put("contact", ChangedContactNo);
}
UpdateAsync updatestart = new UpdateAsync();
updatestart.execute();
}
public class UpdateAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
JSONObject json = null;
#Override
protected Void doInBackground(Void... voids) {
json = new HttpCall().postForJSON("http://abdulbasit.website/blood_app/UpdateProfile.php", ThingsTobeUpdated);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateActivity.this);
pDialog.setMessage("Updating profile...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if (json != null) {
Toast.makeText(getBaseContext(), "Profile updated, Login Again to see changes", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getBaseContext(), "Error updating profile. Try Again", Toast.LENGTH_LONG).show();
}
}
}
}
public class CroppingActivity extends AppCompatActivity {
private CropImageView mCropImageView;
public static Bitmap finalImage = null;
public static Bitmap newImage = null;
private Uri mCropImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 400);
}
public void onSetImageClick(View view) {
if(UpdateActivity.UpdatingPhoto){
newImage = mCropImageView.getCroppedImage(400, 400);
try {
Intent intent = new Intent(getApplicationContext(), UpdateActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else {
finalImage = mCropImageView.getCroppedImage(400, 400);
try {
Intent intent = new Intent(getApplicationContext(), UploadImage.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(400, 400);
if (cropped != null)
mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
#Override
public void onBackPressed() {
UpdateActivity.UpdatingPhoto = false;
super.onBackPressed();
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCropImageView.setImageUriAsync(mCropImageUri);
} else {
Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list (android) so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null && data.getData() != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
/**
* Test if we can open the given Android URI to test if permission required error is thrown.<br>
*/
public boolean isUriRequiresPermissions(Uri uri) {
try {
ContentResolver resolver = getContentResolver();
InputStream stream = resolver.openInputStream(uri);
stream.close();
return false;
} catch (FileNotFoundException e) {
if (e.getCause() instanceof ErrnoException) {
return true;
}
} catch (Exception e) {
}
return false;
}
}
can't open /data/misc/app_oom.hprof: Permission denied
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm-heap: hprofDumpHeap failed with result: -1
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm-heap: After hprofDumpHeap for process
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm: Out of memory: Heap Size=76760KB, Allocated=13818KB, Limit=98304KB, Proc Limit=98304KB
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm: Extra info: Footprint=76760KB, Allowed Footprint=76760KB, Trimmed=16KB
07-04 16:25:41.436 23278-23278/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.donateblood.blooddonation, PID: 23278
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donateblood.blooddonation/com.donateblood.blooddonation.UpdateActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653) at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donateblood.blooddonation.UpdateActivity.CheckImage(UpdateActivity.java:93)
at com.donateblood.blooddonation.UpdateActivity.onCreate(UpdateActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
im adding a camera scanning facility to a project of mine. Im using the following github https://github.com/jhansireddy/AndroidScannerDemo project
im attempting to call it from within an onclicklistener which is set within an adaptor i wrote
here is my onclicklistener
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent intent = new Intent(context, ScanActivity.class);
// ((Activity) context).startActivity(intent);
Intent intent =new Intent(context, ScanAdaptor.class);
}
}
i want it to call a class i wrote which uses startactivityforresult :
public class ScanAdaptor extends Activity {
private Context context;
private static final int REQUEST_CODE = 99;
String ba1;
public String URL = "http:";
#Override
public void onCreate(Bundle savedInstanceState) {
int REQUEST_CODE = 99;
int preference = ScanConstants.OPEN_CAMERA;
Intent intent = new Intent(this, ScanActivity.class);
intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
startActivityForResult(intent, REQUEST_CODE);
context = this;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
getContentResolver().delete(uri, null, null);
// scannedImageView.setImageBitmap(bitmap);
upload(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap convertByteArrayToBitmap(byte[] data) {
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
private void upload(Bitmap bm) {
// Image location URL
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
int flag = 0;
ba1 = Base64.encodeToString(ba, flag);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(((Activity) context));
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
Intent myIntent = new Intent(((Activity) context), MainActivity.class);
myIntent.putExtra("dir", "BS"); //Optional parameters
((Activity) context).startActivity(myIntent);
}
}
}
when this is the config nothing happens when you press the button.
its driving me mad, please help
Your onClick method doesn't launch the activity, it just creates the intent. Try this:
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ScanAdaptor.class);
((Activity) context).startActivity(intent);
}
}