This question already has answers here:
How to resize image before loading to ImageView to avoid OOM issues
(4 answers)
Closed 3 years ago.
The below code uploads 4 images from a phone/tab gallery to a server
and writes the paths to a DB. On testing it, it is currently It is
uploading all 4 images if they are 150kb and below. The problem comes
in when i try to upload 1Mb images. The app crashes on loading the
second image to iv. I have read this Android Bitmaps but i cant
figure out how to implement it in my code. Kindly help.
public class MainActivity extends AppCompatActivity {
Bitmap bitmap1;
Bitmap bitmap2;
Bitmap bitmap3;
Bitmap bitmap4;
boolean check = true;
Button SelectImageGallery1;
Button SelectImageGallery2;
Button SelectImageGallery3;
Button SelectImageGallery4;
Button UploadImageServer;
ImageView imageView1;
ImageView imageView2;
ImageView imageView3;
ImageView imageView4;
EditText imageName1;
EditText imageName2;
EditText imageName3;
EditText imageName4;
ProgressDialog progressDialog;
String GetImageNameEditText1;
String GetImageNameEditText2;
String GetImageNameEditText3;
String GetImageNameEditText4;
String ImageName1 = "image_name1";
String ImageName2 = "image_name2";
String ImageName3 = "image_name3";
String ImageName4 = "image_name4";
String ImagePath1 = "image_path1";
String ImagePath2 = "image_path2";
String ImagePath3 = "image_path3";
String ImagePath4 = "image_path4";
String ServerUploadPath = "http://ny.com/multiple4/uploadmultiple4.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView3 = (ImageView) findViewById(R.id.imageView3);
imageView4 = (ImageView) findViewById(R.id.imageView4);
imageName1 = (EditText) findViewById(R.id.editTextImageName1);
String strImageName1 = imageName1.getText().toString();
if (TextUtils.isEmpty(strImageName1)) {
imageName1.setError("Image Name Must Be Entered");
}
imageName2 = (EditText) findViewById(R.id.editTextImageName2);
String strImageName2 = imageName2.getText().toString();
if (TextUtils.isEmpty(strImageName2)) {
imageName2.setError("Image Name Must Be Entered");
}
imageName3 = (EditText) findViewById(R.id.editTextImageName3);
String strImageName3 = imageName3.getText().toString();
if (TextUtils.isEmpty(strImageName3)) {
imageName3.setError("Image Name Must Be Entered");
}
imageName4 = (EditText) findViewById(R.id.editTextImageName4);
String strImageName4 = imageName4.getText().toString();
if (TextUtils.isEmpty(strImageName4)) {
imageName4.setError("Image Name Must Be Entered");
}
SelectImageGallery1 = (Button) findViewById(R.id.buttonSelect1);
SelectImageGallery2 = (Button) findViewById(R.id.buttonSelect2);
SelectImageGallery3 = (Button) findViewById(R.id.buttonSelect3);
SelectImageGallery4 = (Button) findViewById(R.id.buttonSelect4);
UploadImageServer = (Button) findViewById(R.id.buttonUpload);
SelectImageGallery1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image1 From Gallery"), 1);
}
});
SelectImageGallery2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image4 From Gallery"), 2);
}
});
SelectImageGallery3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image3 From Gallery"), 3);
}
});
SelectImageGallery4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image4 From Gallery"), 4);
}
});
UploadImageServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetImageNameEditText1 = imageName1.getText().toString();
GetImageNameEditText2 = imageName2.getText().toString();
GetImageNameEditText3 = imageName3.getText().toString();
GetImageNameEditText4 = imageName4.getText().toString();
ImageUploadToServerFunction();
}
});
}
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView1.setImageBitmap(bitmap1);
} catch(IOException e) {
e.printStackTrace();
}
}
if (RC == 2 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 =
MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView2.setImageBitmap(bitmap2);
} catch(IOException e) {
e.printStackTrace();
}
}
if (RC == 3 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
byte[] imageAsBytes = null;
try {
bitmap3 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 =
MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView3.setImageBitmap(bitmap3);
} catch(IOException e) {
e.printStackTrace();
}
}
if (RC == 4 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
bitmap4 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 =
MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView4.setImageBitmap(bitmap4);
} catch(IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage1(Bitmap bitmap1) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage1 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage1;
}
public String getStringImage2(Bitmap bitmap2) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage2 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage2;
}
public String getStringImage3(Bitmap bitmap3) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap3.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage3 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage3;
}
public String getStringImage4(Bitmap bitmap4) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap4.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage4 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage4;
}
public void ImageUploadToServerFunction() {
final String imageName1 = GetImageNameEditText1.trim();
final String imageName2 = GetImageNameEditText2.trim();
final String imageName3 = GetImageNameEditText3.trim();
final String imageName4 = GetImageNameEditText4.trim();
final String imageView1 = getStringImage1(bitmap1);
final String imageView2 = getStringImage2(bitmap2);
final String imageView3 = getStringImage3(bitmap3);
final String imageView4 = getStringImage4(bitmap4);
class AsyncTaskUploadClass extends AsyncTask <Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "Image is Uploading", "Please Wait", false, false);
}
#Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
// Dismiss the progress dialog after done uploading.
progressDialog.dismiss();
// Printing uploading success message coming from server on android app.
Toast.makeText(MainActivity.this, string1, Toast.LENGTH_LONG).show();
// Setting image as transparent after done uploading.
ImageView cleared1 = (ImageView) findViewById(R.id.imageView1);
cleared1.setImageResource(android.R.color.transparent);
ImageView cleared2 = (ImageView) findViewById(R.id.imageView2);
cleared2.setImageResource(android.R.color.transparent);
ImageView cleared3 = (ImageView) findViewById(R.id.imageView3);
cleared3.setImageResource(android.R.color.transparent);
ImageView cleared4 = (ImageView) findViewById(R.id.imageView4);
cleared4.setImageResource(android.R.color.transparent);
}
#Override
protected String doInBackground(Void...params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap <String, String> HashMapParams = new HashMap <String, String> ();
HashMapParams.put(ImageName1, imageName1);
HashMapParams.put(ImageName2, imageName2);
HashMapParams.put(ImageName3, imageName3);
HashMapParams.put(ImageName4, imageName4);
HashMapParams.put(ImagePath1, imageView1);
HashMapParams.put(ImagePath2, imageView2);
HashMapParams.put(ImagePath3, imageView3);
HashMapParams.put(ImagePath4, imageView4);
String FinalData = imageProcessClass.ImageHttpRequest(ServerUploadPath, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new
AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
public class ImageProcessClass {
public String ImageHttpRequest(String
requestURL, HashMap <String, String> PData) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url;
HttpURLConnection httpURLConnectionObject;
OutputStream OutPutStream;
BufferedWriter bufferedWriterObject;
BufferedReader bufferedReaderObject;
int RC;
url = new URL(requestURL);
httpURLConnectionObject = (HttpURLConnection)
url.openConnection();
httpURLConnectionObject.setReadTimeout(19000);
httpURLConnectionObject.setConnectTimeout(19000);
httpURLConnectionObject.setRequestMethod("POST");
httpURLConnectionObject.setDoInput(true);
httpURLConnectionObject.setDoOutput(true);
OutPutStream = httpURLConnectionObject.getOutputStream();
bufferedWriterObject = new BufferedWriter(
new OutputStreamWriter(OutPutStream, "UTF-8"));
bufferedWriterObject.write(bufferedWriterDataFN(PData));
bufferedWriterObject.flush();
bufferedWriterObject.close();
OutPutStream.close();
RC = httpURLConnectionObject.getResponseCode();
if (RC == HttpsURLConnection.HTTP_OK) {
bufferedReaderObject = new BufferedReader(new
InputStreamReader(httpURLConnectionObject.getInputStream()));
stringBuilder = new StringBuilder();
String RC2;
while ((RC2 = bufferedReaderObject.readLine()) != null) {
stringBuilder.append(RC2);
}
}
} catch(Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private String bufferedWriterDataFN(HashMap <String, String> HashMapParams) throws UnsupportedEncodingException {
StringBuilder stringBuilderObject;
stringBuilderObject = new StringBuilder();
for (Map.Entry < String, String > KEY: HashMapParams.entrySet()) {
if (check) check = false;
else stringBuilderObject.append("&");
stringBuilderObject.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));
stringBuilderObject.append("=");
stringBuilderObject.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
}
return stringBuilderObject.toString();
}
}
}
Out Of Memory might occur if you are trying to set a bitmap resource as an image to an ImageView because the resource itself might not be that big, as you said 1MB, but when actually it is being inflated its size will be a lot bigger, for the way bitmaps works when its data is extracted in order to be reproduced.
I'm referring to the Loading Large Bitmaps Efficiently content in the Android Developers platform in order to give you a better overview of my suggestions, but you might want also to go a bit broader to get an idea around loading Bitmaps in Android.
I'd suggest you to try to work with the class BitmapFactory.Options in order to minimize the virtual memory used as cache to load the bitmap resources.
Eventually you will need to:
read the Bitmap dimensions and type
load a scaled down version, or an appropriate version in memory for your ImageView expectations (in size)
Related
I am very new to this. This is my first app, so I don't know all of the terms, or even how to explain it properly. But I am creating an affective app in Android Studio using Microsoft Cognitive API to test images to see what emotion the individuals in them display (happy, sad, neutral) then displaying the result as a text output.
I am wondering how to write code so that if the resulting text is 'neutral', the user is automatically sent to the activity_body activity, or else if the result is 'happiness', the user is automatically sent to the activity_mind activity. [](https://i.stack.imgur.com/m5ZpU.png)
package com.example.breastiesapp;
import...
public class MainActivity extends AppCompatActivity {
public Button button;
private ImageView imageView;
private TextView resultText;
private static final int REQUEST_CAMERA_CODE = 300;
private static final int REQUEST_PERMISSION_CODE = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
resultText = findViewById(R.id.resultText);
/**
* this takes the user to the body activity
*/
button = (Button) findViewById(R.id.bodyBTN);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, BodyActivity.class);
startActivity(intent);
}
});
/**
* this takes the user to the Mind activity
*/
button = (Button) findViewById(R.id.mindBTN);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MindActivity.class);
startActivity(intent);
}
});
}
public void getImage(View view) {
if(checkPermission()) {
Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
choosePhotoIntent.setType("image/*");
launchGalleryImageGetter.launch(choosePhotoIntent);
}
else {
requestPermission();
}
}
ActivityResultLauncher<Intent> launchGalleryImageGetter
= registerForActivityResult(
new ActivityResultContracts
.StartActivityForResult(),
result -> {
if (result.getResultCode()
== Activity.RESULT_OK) {
Intent data = result.getData();
if (data != null
&& data.getData() != null) {
Uri selectedImageUri = data.getData();
Bitmap selectedImageBitmap;
try {
selectedImageBitmap
= MediaStore.Images.Media.getBitmap(
this.getContentResolver(),
selectedImageUri);
imageView.setImageBitmap(selectedImageBitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
});
ActivityResultLauncher<Intent> launchCameraGetter
= registerForActivityResult(
new ActivityResultContracts
.StartActivityForResult(),
result -> {
if (result.getResultCode()
== Activity.RESULT_OK) {
Intent data = result.getData();
if (data != null
&& data.getData() != null) {
Bitmap takenImageBitmap;
takenImageBitmap
= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(takenImageBitmap);
}
}
});
public void getEmotion(View view) {
final String TAG = "getEmotion";
Log.i(TAG, "example printing to logcat from getEmotion()");
GetEmotionCall emotionCall = new GetEmotionCall(imageView);
emotionCall.execute();
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, REQUEST_PERMISSION_CODE);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
return result == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED;
}
public void getCameraImage(View view) {
if(checkPermission()) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//startActivityForResult(takePictureIntent, REQUEST_CAMERA_CODE);
launchCameraGetter.launch(takePictureIntent);
}
}
else {
requestPermission();
}
}
private class GetEmotionCall extends AsyncTask<Void, Void, String> {
private final ImageView img;
GetEmotionCall(ImageView img) {
this.img = img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
resultText.setText("Getting results...");
}
#Override
protected String doInBackground(Void... params) {
// set up a http client for making the API call
HttpClient httpclient = HttpClients.createDefault();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
// this URI comes from the API itself and can be modified to change what is requested
org.apache.hc.core5.net.URIBuilder builder = new URIBuilder("https://canadacentral.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=false&returnFaceLandmarks=false&returnFaceAttributes=emotion,age,gender,headPose,smile,facialHair,glasses,hair,makeup&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection_01");
//URIBuilder builder = new URIBuilder("https://canadacentral.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion,age,gender,headPose,smile,facialHair,glasses,hair,makeup&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection");
URI uri = builder.build();
// make a new POST request since we need to send our image to the API server
org.apache.hc.client5.http.classic.methods.HttpPost request = new HttpPost(uri);
// required type for uploading a file
request.setHeader("Content-Type", "application/octet-stream");
// enter your subscription key here
request.setHeader("Ocp-Apim-Subscription-Key", "0d3836e987594b01856f42d");
// Request body. setEntity method converts the image to base64
request.setEntity(new ByteArrayEntity(toBase64(img), ContentType.APPLICATION_OCTET_STREAM));
// getting a response and assigning it to the string res
ClassicHttpResponse response = (ClassicHttpResponse) httpclient.execute(request);
Log.i("doInBackground", response.toString());
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity);
Log.i("doInBackground",res);
return res;
}
catch (Exception e){
return "null";
}
}
#Override
protected void onPostExecute(String result) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(result);
String emotions = "";
for(int i = 0;i<jsonArray.length();i++) {
JSONObject jsonParentObject = new JSONObject(jsonArray.get(i).toString());
JSONObject jsonObject = jsonParentObject.getJSONObject("faceAttributes");
JSONObject scores = jsonObject.getJSONObject("emotion");
double max = 0;
String emotion = "";
for (int j = 0; j < scores.names().length(); j++) {
if (scores.getDouble(scores.names().getString(j)) > max) {
max = scores.getDouble(scores.names().getString(j));
emotion = scores.names().getString(j);
}
}
emotions += emotion + "\n";
}
resultText.setText(emotions);
} catch (JSONException e) {
resultText.setText("No emotion detected. Try again later");
}
}
}
public byte[] toBase64(ImageView imgPreview) {
Bitmap bm = ((BitmapDrawable) imgPreview.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
return baos.toByteArray();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Put the if conditions in you try block when emotions are retrived and then based on conditions you can navigate to other activities
try {
jsonArray = new JSONArray(result);
String emotions = "";
for(int i = 0;i<jsonArray.length();i++) {
JSONObject jsonParentObject = new JSONObject(jsonArray.get(i).toString());
JSONObject jsonObject = jsonParentObject.getJSONObject("faceAttributes");
JSONObject scores = jsonObject.getJSONObject("emotion");
double max = 0;
String emotion = "";
for (int j = 0; j < scores.names().length(); j++) {
if (scores.getDouble(scores.names().getString(j)) > max) {
max = scores.getDouble(scores.names().getString(j));
emotion = scores.names().getString(j);
}
}
emotions += emotion + "\n";
}
resultText.setText(emotions);
if(emotions=="neutral"){
Intent intent = new Intent(MainActivity.this,activity_body.class);
startActivity(intent);
}
else if(emotions=="happiness") {
Intent intent = new Intent(MainActivity.this,activity_mind.class);
startActivity(intent);
}
}
catch (JSONException e) {
resultText.setText("No emotion detected. Try again later");
}
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);
}
This is my code for storing image in ImageView but i want to store image name in My TextView Object Please help how to do this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
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;
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public static final String UPLOAD_URL = "http://192.168.1.101:8080/ImageUpload/upload2.php";
public static final String UPLOAD_KEY = "image";
public static final String TAG = "MY MESSAGE";
private int PICK_IMAGE_REQUEST = 1;
private Button buttonChoose;
private Button buttonUpload;
private Button buttonView;
private ImageView imageView;
private Bitmap bitmap;
//private Uri filePath;
private static Uri filePath;
private TextView tv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonView = (Button) findViewById(R.id.buttonViewImage);
imageView = (ImageView) findViewById(R.id.imageView);
tv1 = (TextView)findViewById(R.id.textView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
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(){
class UploadImage extends AsyncTask<Bitmap,Void,String> {
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Uploading Image", "Please wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
String result = rh.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if(v == buttonUpload){
uploadImage();
}
}
}
RequestHandler.java
public class RequestHandler {
public String sendGetRequest(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
StringBuilder sb = new StringBuilder();
while((result = bufferedReader.readLine())!=null){
sb.append(result);
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
When i clicked on choose file it take me to gallery for selecting an image file now from here i want that when i selected image the name of image shows in my textview please describe me how to do this.
Try below code,hope that it's works for you
You can get file name from URI using below code :
File file = getFile(context,filePath);
String imageName = file.getName();
TextView.setText(imageName);
here is the getFile function,
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
From your question I interpreted that you want the image name, so here is a code to get the image name from the path you have.
Rather you can store all the image name and path in a separate hashmap and can get any image name with the corresponding image path later.
public static String getImages(Context context) {
Uri uri;
Cursor cursor;
int column_index_data, column_index_file_name;
String PathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.TITLE };
//get you a cursor with which you can search all images in your device
cursor = context.getContentResolver().query(uri, projection, null,
null, null);
//get the column index of the Path of the image
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
//get the column index of the name of the image
column_index_file_name = cursor
.getColumnIndexOrThrow(MediaStore.MediaColumns.TITLE);
while (cursor.moveToNext()) {
PathOfImage = cursor.getString(column_index_data);
String name = cursor.getString(column_index_file_name);
Log.e("Manojit",PathOfImage+"\n"+name);
if(PathOfImage.equals(filepath)){
//here you will get the title of the image
//from the result set the content of the Textview
return cursor.getString(column_index_file_name);}
}
return null;
}
I'm fetching user's profile picture from facebook and I want to send it to ProfileActivity.java so that it can be displayed on user profile.
The problem is that the image is not getting sent from SignUpScreen.java to ProfileActivity.java. Though I am able to send name & email from one to another.
Here's SignUpScreen.java file's code:
public class SignUpScreen extends AppCompatActivity {
Button facebookLoginButton;
CircleImageView mProfileImage;
TextView mUsername, mEmailID;
Profile mFbProfile;
ParseUser user;
Bitmap bmp = null;
public String name, email, userID;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_sign_up_screen);
TextView textView = (TextView) findViewById(R.id.h);
Typeface typeface = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/Pac.ttf");
textView.setTypeface(typeface);
mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
mUsername = (TextView) findViewById(R.id.userName);
mEmailID = (TextView) findViewById(R.id.aboutUser);
mFbProfile = Profile.getCurrentProfile();
//mUsername.setVisibility(View.INVISIBLE);
//mEmailID.setVisibility(View.INVISIBLE);
facebookLoginButton = (Button) findViewById(R.id.facebook_login_button);
facebookLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpScreen.this, mPermissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
getUserDetailsFromFacebook();
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
saveNewUser();
}
}, 5000);
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
});
}
public void saveNewUser() {
user = new ParseUser();
user.setUsername(name);
user.setEmail(email);
user.setPassword("hidden");
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(SignUpScreen.this, "SignUp Succesful", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SignUpScreen.this, "SignUp Unsuccesful", Toast.LENGTH_LONG).show();
Log.d("error when signingup", e.toString());
}
}
});
}
private void getUserDetailsFromFacebook() {
final GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
//Log.d("response", "response" + object.toString());
Intent profileIntent = new Intent(SignUpScreen.this, ProfileActivity.class);
Bundle b = new Bundle();
try {
name = response.getJSONObject().getString("name");
mUsername.setText(name);
email = response.getJSONObject().getString("email");
mEmailID.setText(email);
userID = response.getJSONObject().getString("id");
new ProfilePicAsync().execute(userID);
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
profileIntent.putExtra("user_pic", bmp);
startActivity(profileIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
class ProfilePicAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String imageURL;
String id = userID;
imageURL = "https://graph.facebook.com/"+ id +"/picture?type=large";
try {
bmp = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
e.printStackTrace();
Log.d("Loading picture failed", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mProfileImage.setImageBitmap(bmp);
}
}
}
Here's ProfileActivity.java file's code:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
CircleImageView mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
TextView mUsername = (TextView) findViewById(R.id.userName);
TextView mEmailID = (TextView) findViewById(R.id.aboutUser);
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("user_pic");
mProfileImage.setImageBitmap(bitmap);
mUsername.setText(bundle.getString("userName"));
mEmailID.setText(bundle.getString("userEmail"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Please let me know what is going wrong here.
In your getUserDetailsFromFacebook() method you have called new ProfilePicAsync().execute(userID) to get the image. But it seems that before you could fetch the image ,startActivity(profileIntent) probably gets called.
First be sure that you have fetched the image from facebook before you call startActivity(profileIntent).
EDIT
Add this to your getUserDetailsFromFacebook() ,
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
profileIntent.putExtra("user_pic", byteArray);
startActivity(profileIntent);
Add this to your ProfileActivity.java ,
byte[] byteArray = getIntent().getByteArrayExtra("user_pic");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mProfileImage.setImageBitmap(bmp);
This is not a right way to pass image from Activity to Activity within same application. You can easily send the path by intent and load it into other Activity.
To save a bitmap in Activity A, use
FileOutputStream out = null;
try {
out = new FileOutputStream(FILENAME); //FILENAME is your defined place to store image
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Now you have FILENAME global string which is accessible from Activity B.
Just load it where its needed.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(FILENAME, options);
mProfileImage.setImageBitmap(bitmap);
it works for me.
OneActivity.java
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(StartPage.this, SecondActivity.class);
Toast.makeText(StartPage.this, "You have setted this wallpaper for Monday", Toast.LENGTH_LONG).show();
intent.putExtra("pic", byteArray);
//intent.putExtra("resourseInt", bm);
startActivity(intent);
SecondActivity.Java
byte[] byteArray;
Bitmap bmp,
byteArray = getIntent().getByteArrayExtra("pic");
bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
myWallpaperManager.setBitmap(bmp);
In my widget, I have an imageView that collect an image from the user gallery and then sets that image up as the background in another activity. It works fine, but when I try to add an image file that is too big (such as an image from the camera) or upload many image files, I get an "out of memory" error. After looking around stackoverflow for a while, I noticed that everyone pretty much used the basic method of:
public static Bitmap decodeSampleImage(File f, int width, int height) {
try {
System.gc(); // First of all free some memory
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int requiredWidth = width;
final int requiredHeight = height;
// Find the scale value (as a power of 2)
int sampleScaleSize = 1;
while (o.outWidth / sampleScaleSize / 2 >= requiredWidth && o.outHeight / sampleScaleSize / 2 >= requiredHeight)
sampleScaleSize *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = sampleScaleSize;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (Exception e) {
Log.d(TAG, e.getMessage()); // We don't want the application to just throw an exception
}
return null;
}
I also noticed that people have recycled unused bitmaps as well. I understand how this works but I don't know where I should put it in my coding.
Here are my two classes (Personalize.java where the imageView to collect the background is. It has the imageView and two buttons (one for choosing an image from the gallery where it then displays that image into the imageView and the other to then set that image as the background).
First here is Personalize.java:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Personalize extends Activity implements View.OnClickListener {
Button button;
ImageView image; //the imageview for setting the background
ImageView image2; //the imageview for setting the icon (not focusing on)
Button btnChangeImage;
Button btnChangeImageForIcon;
Button btnSetBackground;
private static final int SELECT_PICTURE = 1;
private static final int SELECT_PICTURE_2 = 2;
private String selectedImagePath;
Bitmap background;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalize);
image = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2Icon);
Button btnChangeImage = (Button) findViewById(R.id.btnChangeImage);
btnChangeImage.setOnClickListener(this);
Button btnChangeImageForIcon = (Button) findViewById(R.id.btnChangeImageForIcon);
btnChangeImageForIcon.setOnClickListener(this);
Button btnSetBackground = (Button) findViewById(R.id.btnSetBackground);
btnSetBackground.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnChangeImage:
launchImageChooser();
break;
case R.id.btnChangeImageForIcon:
launchImageChooser();
break;
case R.id.btnSetBackground:
setBackgroundImageInDragAndDrop();
break;
}
}
private void setBackgroundImageInDragAndDrop() {
Log.d("Personalize", "setBackgroundImageInDragAndDrop() called");
Intent i = getIntent();
//Convert bitmap to byte array to send back to activity
// See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
ByteArrayOutputStream stream = new ByteArrayOutputStream();
background.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray = stream.toByteArray();
i.putExtra("myBackgroundBitmap", byteArray);
setResult(RESULT_OK, i);
finish();
}
private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
if(cursor != null) {
cursor.close();
}
return imagePath;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
background = getAndDecodeImage(selectedImagePath);
if(background != null){
image.setImageBitmap(background);
}
} else if (requestCode == SELECT_PICTURE_2)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap b2 = getAndDecodeImage(selectedImagePath);
if(b2 != null){
image2.setImageBitmap(b2);
}
}
}
}
private Bitmap getAndDecodeImage(String selectedImagePath){
try {
Log.d("Personalize", "selectedImagePath: " + selectedImagePath);
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
if (fileis != null)
{
fileis.close();
}
if (bufferedstream != null)
{
bufferedstream.close();
}
return bMap;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
}
Then here is my Drag_and_Drop_App.java (snippet of important parts -- collects bitmap and sets as background):
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Drag_and_Drop_App extends Activity {
private static final int SET_BACKGROUND = 10;
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public AppInfoAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// import buttons
Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);
Button btnLinkToPersonalize = (Button) findViewById(R.id.btnLinkToPersonalize);
// Link to Personalize Screen
btnLinkToPersonalize.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Personalize.class);
startActivityForResult(i, SET_BACKGROUND);
}
});
}
public Bitmap getThumbnail(String filename) {
Bitmap thumbnail = null;
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
return thumbnail;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Drag_and_Drop_App", "requestCode: " + requestCode + ", resultCode: " + resultCode);
if(requestCode == SET_BACKGROUND && resultCode == RESULT_OK){
byte[] byteArray = data.getByteArrayExtra("myBackgroundBitmap");
Bitmap myBackground = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
setBackgroundImage(myBackground);
}
}
#SuppressLint("NewApi")
private void setBackgroundImage(Bitmap bitmap) {
RelativeLayout yourBackgroundView = (RelativeLayout) findViewById(R.id.rl_drag_and_drop_app);
Drawable d = new BitmapDrawable(getResources(), bitmap);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
yourBackgroundView.setBackgroundDrawable(d);
} else {
yourBackgroundView.setBackground(d);
}
}
}
So where could I implement that coding and where could I also get rid of other unused bitmaps in memory? (recycle them?)