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");
Related
My first question would be, Is onCreate method needed on every new class in android ?
Next, can we use multiple onActivityResult method without causing distortion
?
For exemple my MainActivity and ShareActivity class both have their own onActivityResult and Oncreate method (code taken from git)
MainActivity is for opening camera and gallery
ShareActivity is for sharing images captured
Note : Both class check for permission first
I wanna call the ShareActivity in my MainActivity, the logical thing to do would be
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, ShareActivity.class);
startActivity(myIntent);
}
});
But my ShareActivity also has this
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
And then I thought about calling it like this
ShareActivity.getInstance().onShareTouched();
But the app keep crashing, everytime I call the Share class,
Edit : Should I use implement ?
Note :the Share class works fine without MainActivity (I tried in new project)
for better understanding I leave the complete code below
ShareActivity
public class ShareActivity extends AppCompatActivity {
private static ShareActivity instance;
private static final String TAG = "ShareActivity";
private final int SHARE_STORAGE_PERMS_REQUEST_CODE = 900;
private final int RESULT_LOAD_IMG_REQUEST_CODE = 778;
private final String[] perms = { android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE};
private static final String IMAGE_URL = null;
private Bitmap bmp;
#BindView(R.id.open_share)
SimpleDraweeView imageView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
bmp = getBitmapFromUrl(IMAGE_URL);
imageView2.setImageURI(Uri.parse(IMAGE_URL));
instance = this;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMG_REQUEST_CODE && resultCode == RESULT_OK) {
List<Image> images = ImagePicker.getImages(data);
if(images.size() > 0) {
String imagePath = images.get(0).getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagePath, options);
imageView2.setImageURI(Uri.fromFile(new File(imagePath)));
}
}
}
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
#AfterPermissionGranted(SHARE_STORAGE_PERMS_REQUEST_CODE)
private void shareImageFromBitmap(Bitmap bmp) {
Uri uri = getUriImageFromBitmap(bmp, ShareActivity.this);
if(uri == null) {
//Show no URI message
return;
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, IMAGE_URL);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/png");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
private Bitmap getBitmapFromUrl(String url) {
Uri uri = Uri.parse(url);
ImageRequest downloadRequest = ImageRequest.fromUri(uri);
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(downloadRequest, ShareActivity.this);
if (ImagePipelineFactory.getInstance().getMainFileCache().hasKey(cacheKey)) {
BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey);
byte[] data = null;
try {
data = resource.read();
} catch (IOException e) {
e.printStackTrace();
}
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
return null;
}
private Uri getUriImageFromBitmap(Bitmap bmp, Context context) {
if(bmp == null)
return null;
Uri bmpUri = null;
try {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "IMG_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
bmpUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public static ShareActivity getInstance() {
return instance;
}
}
MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
if (requestCode == OPEN_THING) {
Uri uri = Objects.requireNonNull(data.getExtras()).getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
if (uri != null) {
getContentResolver().delete(uri, null, null);
}
scannedImageView.setImageBitmap(bitmap);
FileOutputStream outputStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/Scan Documents");
directory.mkdir();
String filename = String.format("d.jpg", System.currentTimeMillis());
File outFile = new File(directory, filename);
Toast.makeText(this, "Image Saved Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));
sendBroadcast(intent);
try {
outputStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I found a better easier way
I had to completely change my method, I put everything in my button onClick
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
});
No need ShareActivity it works great
I am creating an application in which i am setting a gallery of images with shuffling effect on wallpaper. shuffling effect is working if app is in background.
But the problem is when i change my wallpaper from my device to set on home screen(not from application but select form wallpapers of device), that wallpaper is setting on my home screen and the shuffling effect remains continue(because i think service is running). Can someone please tell me what is the issue and how to solve this. This is my service class:
public class WallpaperService extends Service {
ArrayList<String> arrayList = new ArrayList<>();
int counter = 0;
Bitmap bmImg = null;
int seconds;
public WallpaperService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flag, int startId) {
super.onStartCommand(intent, flag, startId);
arrayList = intent.getStringArrayListExtra("image_url");
seconds = intent.getIntExtra("seconds", 5000 * 60);
Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
SaveWallpaperAsync async = new SaveWallpaperAsync();
async.execute();
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
}
public class SaveWallpaperAsync extends AsyncTask<String, Integer, Void> {
URL ImageUrl;
Bitmap bmImg = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Toast.makeText(WallpaperService.this, "downloading", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
InputStream is = null;
for (int i = 0; i < arrayList.size(); i++) {
try {
ImageUrl = new URL(arrayList.get(i));
HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bmImg = BitmapFactory.decodeStream(is, null, options);
saveImageToInternalStorage(bmImg, i);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(WallpaperService.this, "Downloaded", Toast.LENGTH_SHORT).show();
createNotificationIcon();
}
}
protected String saveImageToInternalStorage(Bitmap bitmap, int index) {
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Dark Wallpapers/");
if (!dir.exists()){
dir.mkdirs();
}
File file = new File(dir, "UniqueFileName" + index + ".jpg");
try {
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
Uri savedImageURI = Uri.parse(file.getAbsolutePath());
return savedImageURI.toString();
}
private Bitmap loadImageFromStorage(int counter) {
Bitmap b = null;
try {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Dark Wallpapers/", "UniqueFileName" + counter + ".jpg");
b = BitmapFactory.decodeStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return b;
}
public void createNotificationIcon() {
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
counter += 1;
if (counter < arrayList.size()) {
try {
wallpaperManager.setBitmap(loadImageFromStorage(counter));
wallpaperManager.suggestDesiredDimensions(1080, 1920);
} catch (IOException e) {
e.printStackTrace();
}
} else if (counter == arrayList.size()) {
counter = 0;
try {
wallpaperManager.setBitmap(loadImageFromStorage(counter));
wallpaperManager.suggestDesiredDimensions(1080, 1920);
} catch (IOException e) {
e.printStackTrace();
}
}
}
},
0,
seconds);
}}
This is how i called it from activity:
Intent intent = new Intent(CategoryActivity.this, WallpaperService.class);
intent.putExtra("image_url", img_urls);
intent.putExtra("seconds", 60);
intent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(intent);
If I have understood well you would like to get an "event" (or just to know...) when the home wallpaper is changed. Is it right?
Maybe you would like to stop your Service if it detects that the User wants to set a fixed wallpaper from that moment.
There isn't any Event to do this, but there is a solution: remember which wallpaper you have automatically changed from the App (maybe memorize the path+filename in a file in your /xxxxx/files folder) and then check the Current Wallpaper just before trying to set the new one, using this:
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
In this way if the Current Wallpaper is the same of your last and memorized filename than there is a 99% of chance that the user doesn't set a fixed one by his/her own. (the remaining 1% could be the possibility that the user manually sets the SAME wallpaper you automatically set as the last one, but it's very-very rare)
Please pardon any bad English as this is my first time posting question on stackoverflow.
I would like to create a OCR Android Application using tesseract OCR engine and faced the following error, I have tried to search around but however did not find any solution, would appreciate your help. Thanks.
Codes I am trying:
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(Environment.getExternalStorageDirectory().toString()+"/", `"eng");`
I have already created a tessdata folder in my device root with the eng.traineddata file inside, but I was prompted the following error when I access the function.
Could not initialize Tesseract API with language=eng!
I am using Android 6.0.1, API 23
Would appreciate any help! Thanks in advance~
Try this code out . It allows you to take a picture and displays the text .There are minor bugs in this code .Try this code on letters typed in notepad
Ignore the various files being placed in the tessdata folder . I am trying to read maths equation hence i need those . I have commented out the other files, it shouldn't bother you. If you are willing to try , try Mobile Vision API.
Hope this helps :)
public class MainActivity extends AppCompatActivity {
String imgPath;
Bitmap imgBitmap;
Uri imgUri;
InputStream trainDataInputStream;
OutputStream trainDataOutputStream;
AssetManager assetManager;
String externalDataPath;
TextView t;
String[] fileToBeCopied = {"eng.cube.bigrams", "eng.cube.fold", "eng.cube.lm", "eng.cube.nn", "eng.cube.params", "eng.cube.size", "eng.cube.word-freq", "eng.tesseract_cube.nn", "eng.traineddata","equ.traineddata"};
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.text);
new CopyFile().execute();
//placeFileFromAssetsToExternalStorage();
takePicture();
}
class CopyFile extends AsyncTask {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Fetching image...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Object doInBackground(Object[] objects) {
//placeFileFromAssetsToExternalStorage(fileToBeCopied[0]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[1]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[2]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[3]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[4]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[5]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[6]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[7]);
placeFileFromAssetsToExternalStorage(fileToBeCopied[8]);
//placeFileFromAssetsToExternalStorage(fileToBeCopied[9]);
return null;
}
#Override
protected void onPostExecute(Object o) {
pDialog.dismiss();
}
}
private void takePicture() {
File photoFile = null;
Intent iPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (iPicture.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (Exception e) {
e.printStackTrace();
}
//if photo file is created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getApplicationContext(), "com.scorpio.fileprovider", photoFile);
System.out.println(imgPath);
iPicture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(iPicture, 1);
}
}
}
private File createImageFile() {
File imgFile = null;
String fileStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File storageDir = Environment.getExternalStorageDirectory();
try {
imgFile = File.createTempFile(fileStamp, ".jpeg", storageDir);
} catch (IOException e) {
e.printStackTrace();
}
imgPath = imgFile.getAbsolutePath();
return imgFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
galleryAddPic();
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imgPath);
System.out.println("Image path ->" + imgPath);
Uri contentUri = Uri.fromFile(f);
imgUri = contentUri;
System.out.println("Image uri " + imgUri);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
ocrImage();
}
public void ocrImage() {
try {
//getting image for ocr
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
imgBitmap = BitmapFactory.decodeFile(imgPath, options);
} catch (Exception e) {
e.printStackTrace();
}
ExifInterface exif = null;
try {
exif = new ExifInterface(imgPath);
} catch (IOException e) {
e.printStackTrace();
}
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
int w = imgBitmap.getWidth();
int h = imgBitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap & convert to ARGB_8888, required by tess
imgBitmap = Bitmap.createBitmap(imgBitmap, 0, 0, w, h, mtx, false);
}
imgBitmap = imgBitmap.copy(Bitmap.Config.ARGB_8888, true);
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(externalDataPath, "eng");
baseApi.setImage(imgBitmap);
String ocrResult = baseApi.getUTF8Text();
System.out.println(ocrResult);
baseApi.end();
t.setText(ocrResult);
}
public void placeFileFromAssetsToExternalStorage(String filename) {
System.out.println("Running DataRunnable class ");
assetManager = getResources().getAssets();
externalDataPath = Environment.getExternalStorageDirectory() + "/tessdata";
System.out.println("external data path " + externalDataPath);
//creating eng.trainedData
File f = new File(externalDataPath);
try {
if (!f.exists()) {
f.mkdir();
}
externalDataPath = externalDataPath + "/" + filename;
f = new File(externalDataPath);
if (!f.exists())
f.createNewFile();
externalDataPath = Environment.getExternalStorageDirectory().toString();
trainDataInputStream = assetManager.open(filename);
trainDataOutputStream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int read;
while ((read = trainDataInputStream.read(buffer)) != -1) {
trainDataOutputStream.write(buffer, 0, read);
}
trainDataOutputStream.flush();
trainDataOutputStream.close();
trainDataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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);
I want to save imageView into sd card but I get the following exception (some times not always) when I try to get bitmap from imageView. Can somebody please help me? Thanks in advance
Caused by: java.lang.IllegalArgumentException: width and height must be > 0 at android.graphics.Bitmap.createBitmap(Bitmap.java:922)
public static class SaveImageToSD extends AsyncTask<String, Void, String> {
Context context;
ImageView mImageView;
ProgressDialog progressDialog;
public SaveImageToSD(Context context, ImageView iv, String name) {
this.context = context;
this.mImageView = iv;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", context.getResources().getString(R.string.please_wait), true);
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected String doInBackground(String... x) {
File projectFolder = new File(Environment.getExternalStorageDirectory() + File.separator + Settings.projectFolder + File.separator);
boolean folderCreateSuccess = true;
if (!projectFolder.exists()) {
folderCreateSuccess = projectFolder.mkdir();
}
if (folderCreateSuccess) {
Bitmap bitmap;
// Exception in if statement
if (mImageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
Drawable d = mImageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
d.draw(canvas);
}
File image = new File(projectFolder, "GE_" + System.currentTimeMillis() + ".jpg");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "title");
values.put(MediaStore.Images.Media.DESCRIPTION, "description");
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_ID, image.toString().toLowerCase(Locale.US).hashCode());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, image.getName().toLowerCase(Locale.US));
values.put("_data", image.getAbsolutePath());
ContentResolver cr = context.getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
if (success) {
((ActionBarActivity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.image_successfully_saved), Toast.LENGTH_SHORT).show();
}
});
} else {
((ActionBarActivity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.image_successfully_saved), Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.i("Create Folder", "Error during create folder");
}
return "";
}
}
to set image I use following code, I'm using transparentDrawable because of Picasso wrap content problem
transparentDrawable.setBounds(new Rect(0, 0, 1000, 1000));
Picasso.with(mContext).load(((FBPhotoCard) mImageCards.get(position)).getThumbnail()).placeholder(transparentDrawable).noFade().into(holder.imageView);
I think the exception is of because d.getIntrinsicWidth(), d.getIntrinsicHeight() at line bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
According to Android docs drawable.getIntrinsicWidth() Return the intrinsic width of the underlying drawable object. Returns -1 if it has no intrinsic width, such as with a solid color. So make sure to pass values greater than 1 to Bitmap.createBitmap() method
This error you are getting because d.getIntrinsicWidth(), d.getIntrinsicHeight() returning 0 try to put some constant value and then check like 100.