Failed to send image from one activity to another. Please see details - java

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);

Related

How do I save the name after generating QR code

I am trying to make an app that generates QR Code.
It works well but there is no text when it is saved. People would be confused after saving a few codes because of no name on it.
If people generate QR code with "Wikipedia.com", I want it saved with the name of "Wikipedia.com" at the photo gallery. What should I do?
MainActivity
public class MainActivity extends AppCompatActivity {
private String inputValue;
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
private Bitmap bitmap;
private QRGEncoder qrgEncoder;
private ImageView qrImage;
private EditText edtValue;
private AppCompatActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = findViewById(R.id.qr_image);
edtValue = findViewById(R.id.edt_value);
activity = this;
/**Barcode Generator*/
findViewById(R.id.generate_barcode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
try {
bitmap = qrgEncoder.getBitmap();
qrImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else {
edtValue.setError(getResources().getString(R.string.value_required));
}
}
});
/**Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});
}
}
I tried your code and it works fine. The generated QR codes are saved as you want: QR-code-text.jpg
The only problem is the QRGSaver().save(...) is not compatible with Android10+.
Try to extend your onClickListener of save_barcode button as follows:
/*Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(v -> {
String filename = edtValue.getText().toString().trim();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Toast.makeText(activity, "Image Saved. Check your gallery.", Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});

how to add instagram share to story button in my android app

Currently, I am getting this error: cannot find symbol
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg);
I am trying to add Share to Instagram Story button. I had success with share to Whatsapp button. but stuck at this... does anyone can help me?
I want to add "Share to Instagram story" button on onExitButtonClicked
public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {
public CustomDialogListener listener;
public Dialog d;
public Button yes, no, exit;
public CustomDialogClass(#NonNull Context context,
CustomDialogListener listener) {
super(context);
this.listener = listener ;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.btn_yes);
no = (Button) findViewById(R.id.btn_no);
exit = (Button) findViewById(R.id.btn_exit);
yes.setOnClickListener(this);
no.setOnClickListener(this);
exit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
listener.onYesButtonClicked();
break;
case R.id.btn_no:
listener.onNoButtonClicked();
break;
case R.id.btn_exit:
listener.onExitButtonClicked();
break;
default:
break;
}
dismiss();
}
public interface CustomDialogListener {
public void onYesButtonClicked() ;
public void onNoButtonClicked() ;
public void onExitButtonClicked() ;
}
}
public void onBackPressed() {
CustomDialogClass cd = new CustomDialogClass(this, new CustomDialogClass.CustomDialogListener() {
#Override
public void onYesButtonClicked() {
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "sample text");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onNoButtonClicked() {
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "URLyouWantToShare");
startActivity(Intent.createChooser(shareIntent, "Share..."));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onExitButtonClicked() {
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg);
File extStorageDirectory = context.getExternalCacheDir();
File stickerFile = new File(extStorageDirectory, "bg.png");
try {
FileOutputStream outStream = new FileOutputStream(stickerFile);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (IOException e) {
Log.e("TEST", e.getMessage());
}
Uri stickerUri = FileProvider.getUriForFile(this, "con.pixoid.upsend.fileprovider", stickerFile);
// Uri stickerUri = Uri.fromFile(stickerFile);
String linkUrl = "https://stackoverflow.com";
Intent intent = new Intent("com.instagram.share.ADD_TO_STORY");
intent.setType("image/*");
intent.putExtra("interactive_asset_uri", stickerUri);
intent.putExtra("content_url", linkUrl);
intent.putExtra("top_background_color", "#33FF33");
intent.putExtra("bottom_background_color", "#FF00FF");
grantUriPermission("com.instagram.android", stickerUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (getPackageManager().resolveActivity(intent, 0) != null) {
startActivityForResult(intent, 0);
}
}
});
cd.show();
}
Here's a Kotlin example:
private fun shareStory(){
val sticker = BitmapFactory.decodeResource(resources,
R.drawable.your_logo)
val savedImageURL: String = MediaStore.Images.Media.insertImage(
requireContext().contentResolver,
sticker,
"test_image",
"image_description"
)
val savedImageURI = Uri.parse(savedImageURL)
val storiesIntent = Intent("com.instagram.share.ADD_TO_STORY").apply {
type = "image/jpeg"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
setPackage("com.instagram.android")
putExtra("interactive_asset_uri", savedImageURI)
putExtra("content_url", "something");
putExtra("top_background_color", "#33FF33");
putExtra("bottom_background_color", "#FF00FF")
}
requireContext().grantUriPermission("com.instagram.android", savedImageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION)
this.startActivity(storiesIntent)
}
Also here's a link for the official doc:
Instagram Stories

Multiple Images Uploads OOM issues [duplicate]

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)

Pass photo path to another activity using uri

I have the following method for the button onclick listener
titleBar.setRightBtnOnclickListener(v -> {
savePicture();
PublishActivity.openWithPhotoUri(this, Uri.fromFile(photoPath));
});
i want to be able to pass the filepath of the photo to another activity
here i am saving the bitmap
private void savePicture(){
//加滤镜
final Bitmap newBitmap = Bitmap.createBitmap(mImageView.getWidth(), mImageView.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas cv = new Canvas(newBitmap);
RectF dst = new RectF(0, 0, mImageView.getWidth(), mImageView.getHeight());
try {
cv.drawBitmap(mGPUImageView.capture(), null, dst, null);
} catch (InterruptedException e) {
e.printStackTrace();
cv.drawBitmap(currentBitmap, null, dst, null);
}
//加贴纸水印
EffectUtil.applyOnSave(cv, mImageView);
new SavePicToFileTask().execute(newBitmap);
}
Then here am using the async
public class SavePicToFileTask extends AsyncTask<Bitmap,Void,String>{
Bitmap bitmap;
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("图片处理中...");
}
#Override
protected String doInBackground(Bitmap... params) {
String fileName = null;
try {
bitmap = params[0];
String picName = TimeUtils.dtFormat(new Date(), "yyyyMMddHHmmss");
fileName = ImageUtils.saveToFile(FileUtils.getInst().getPhotoSavedPath() + "/"+ picName, false, bitmap);
photoPath = new File(fileName);
} catch (Exception e) {
e.printStackTrace();
toast("图片处理错误,请退出相机并重试", Toast.LENGTH_LONG);
}
return fileName;
}
#Override
protected void onPostExecute(String fileName) {
super.onPostExecute(fileName);
dismissProgressDialog();
if (StringUtils.isEmpty(fileName)) {
return;
}
}
}
so am having trouble on how to get the photo path and then using Uri pass it to the next activity
thanks guys
You should pass the filename as a String using an Intent.
Intent intent = new Intent(getBaseContext(), NEWACTIVITYNAME.class);
intent.putExtra("FILE_NAME", fileName);
startActivity(intent);
Then you can access that intent on next activity:
String fileName = getIntent().getStringExtra("fileName");

Download pictures using a service

I'm trying to download pictures in the background of an app using Service (not IntentSevice)
Somehow, my code doesn't work.
I set permissions for Internet and Storage in the Manifest.
I'm thankful for any comments or answers (:
Here's my code:
For the Service and then for the MainActivity
i have already tried different links or httpURLConnection instead of the normal URL connection but that doesnt't work either.
when I run the app, it always shows my "error" toast. it doesn't even get to the Input Stream.
public class Download extends Service {
public static final String URL = "url";
public static final String FILENAME = "name";
public static final String FILEPATH = "path";
public static final String RESULT = "result";
public static final String NOTIFICATION = "notification";
public ImageView imageView1 ;
#Override
public IBinder onBind(Intent arg0){
// TODO Auto-generated method stub
return null;
}
public void onCreate(){
super.onCreate();
Toast.makeText(this,"Service is created",Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
String urlPath = intent.getStringExtra(FILEPATH);
String fileName = intent.getStringExtra(FILENAME);
int result = Activity.RESULT_CANCELED;
try {
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
final URL fileUrl = new URL(urlPath);
HttpURLConnection urlConnection = (HttpURLConnection) fileUrl.openConnection();
final InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();
//Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();
File downloadordner = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (!downloadordner.exists()) {
downloadordner.mkdirs();
}
File downloadedfile = new File(downloadordner, "Bild1" + System.currentTimeMillis() + ".png");
OutputStream outputStream = new FileOutputStream(downloadedfile);
try {
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
result = Activity.RESULT_OK;
}finally{
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e){
e.printStackTrace();
Toast.makeText(this,"Fehler",Toast.LENGTH_LONG).show();
}
publishResults(result);
return START_STICKY;
}
private void publishResults(int result){
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT,result);
sendBroadcast(intent);
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
System.exit(0);
}
}
public class MainActivity extends AppCompatActivity {
Button btn1;
Button btn2;
ProgressBar progbar1;
public ImageView imageView1;
private TextView downloadStatus; //neu
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadStatus = (TextView) findViewById(R.id.download_status);
progbar1 = (ProgressBar) findViewById(R.id.progbar1);
btn1 = (Button) findViewById(R.id.go);
btn2 = (Button) findViewById(R.id.kill);
imageView1 = (ImageView) findViewById(R.id.bild1);
btn1.setOnClickListener(onDownloadListener());
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Download.class));
System.exit(0);
}
});
}
private View.OnClickListener onDownloadListener(){
return new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Download.class);
intent.putExtra(Download.FILENAME,"logo.png");
intent.putExtra(Download.FILEPATH,"https://de.wikipedia.org/wiki/Kleiner_Eisvogel#/media/File:Limenitis_camilla3.jpg");
startService(intent);
downloadStatus.setText("Downloading....");
Toast.makeText(MainActivity.this, "downloading", Toast.LENGTH_LONG).show();
}
};
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#SuppressLint("SetTextI18n")
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle != null){
int resultCode = bundle.getInt(Download.RESULT);
if (resultCode == RESULT_OK){
Toast.makeText(MainActivity.this,"File downloaded",Toast.LENGTH_LONG).show();
downloadStatus.setText("Download completed");
}else{
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
downloadStatus.setText("Download failed");
}
}
}
};
}
Service runs on the main thread so there is a network exception NO networking is allowed on the main thread.

Categories