So I have a database with a table where a User name corresponds to the name of an image. So In my AsyncHTTP I retrieve the Username and wish to map that Username to its correct image(all images are located in my drawable folder)
In my XML where this image will be rendered I just put an imageview and never assigned it an image(the Id for this imageView is myImage)
So how when I run my code the image is not rendered. I cant assign the image outside of async because of scope issues.
Context context = this;
AsyncHTTPPost asyncHttpPost2 = new AsyncHTTPPost(
"http://lamp.ms.wits.ac.za/~s1363679/avatars.php", params) {
#Override
protected void onPostExecute(String s) {
try {
JSONArray all = new JSONArray(s);
for (int i = 0; i < all.length(); i++) {
JSONObject item = all.getJSONObject(i);
fName = item.getString("avatarName");
System.out.println();
Toast.makeText(Profile.this, fName, Toast.LENGTH_LONG).show();
ImageView Image = (ImageView) findViewById(R.id.myImage);
System.out.println("");
theName = fName;
//String imagename="kaius";
Resources res = context.getResources();
int resID = res.getIdentifier(theName, "drawable", context.getPackageName());
Image.setImageResource(resID);
}
} catch (Exception e) {
Toast.makeText(Profile.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
};
asyncHttpPost2.execute();
}
The imageName is retrieved correctly and stored in the variable "theName" but it doesnt seem to render onto the view.
At the same level of your drawable folder, there should also be some folders with these names:
-drawable-hdpi
-drawable-xhdpi
-drawable-xxhdpi
-drawable-xxxhdpi
Your images should be scaled according to different dpi´s and placed inside those folders to render correctly in all screens.
Another thing you could do instead, is:
// get drawable path
String imageUri = "drawable://" + R.drawable.image;
imageView.setImageBitmap(decodeSampledBitmapFromFile(imageUri , 1920, 1080));
And declare somewhere decodeSampledBitmapFromFile like this:
public static Bitmap decodeSampledBitmapFromFile(String imagePath,
int reqWidth, int reqHeight) {
// BitmapFactory.decodeFile(this.getFilesDir().getPath() + "/" + imagestoplay[currImage])
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(res, resId, options);
BitmapFactory.decodeFile(imagePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imagePath, options);
}
Don´t forget to change 1080 and 1920 to your required size in pixels.
Related
I'm trying to display ImageView using Bitmap and Bitmap get it's value from sharedpref path
/// Activity Fields
ٍString mWinPhotoPath, mLosePhotoPath;
ImageView winnerImage, loserImage;
Bitmap winImage, loseImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_winner);
//// Get shared pref values
mWinPhotoPath = **sharedPreferences.getString(getString(R.string.sharedPreferences_winner_pic), getString(R.string.error_sorry_message)); // win pic
mLosePhotoPath = sharedPreferences.getString(getString(R.string.sharedPreferences_loser_pic), getString(R.string.error_sorry_message)); // lose pic**
**winImage = BitmapFactory.decodeFile(mWinPhotoPath);
loseImage = BitmapFactory.decodeFile(mLosePhotoPath);**
// Activity Objects
**winnerImage = findViewById(R.id.winner_image);**
**loserImage = findViewById(R.id.loser_image);**
// set values
**winnerImage.setImageBitmap(winImage);**
**loserImage.setImageBitmap(loseImage);**
I don't have any error in my log but the problem is the ImageView didn't display Bitmap
also I checked that the shared pref get the path value correctly
Is there any logical error in my code !!?
What's the problem ?
To get bitmap from a path you need to use this code below
File image = new File(mWinPhotoPath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
winImage = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
If you are storing path of file in SharedPrefrence then you can decode file into bitmap by using its path.
File f = new File(file path....);
Bitmap map = BitmapFactory.decodeFile(f.getAbsolutePath());
image.setImageBitmap(map);
OR
String fileName = "...."; // file path
File completeFile = new File(fileName);
FileInputStream readPicture = new FileInputStream(completeFile);
BufferedInputStream bf = new BufferedInputStream(readPicture);
Bitmap bitmap = BitmapFactory.decodeStream(bf);
I'm a newbie in programming. I want to build a QR Code Generator that the QR Code can be saved or downloaded.
Here's my code for the generator:
public class GeneratorActivity extends AppCompatActivity {
EditText text;
Button gen_btn;
ImageView image;
String text2Qr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generator);
text = findViewById(R.id.text);
gen_btn = findViewById(R.id.gen_btn);
image = findViewById(R.id.image);
gen_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text2Qr = text.getText().toString().trim();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try{
BitMatrix bitMatrix = multiFormatWriter.encode(text2Qr, BarcodeFormat.QR_CODE,200,200);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
image.setImageBitmap(bitmap);
bitmap = ((BitmapDrawable) ImageView.getdrawable()).getBitmap();
}
catch (WriterException e){
e.printStackTrace();
}
}
});
}
}
I got a error that I cannot resolve method 'getdrawable()
anybody know how to fix this?
Here's the screenshot of the error: screenshot
get the drawable like from imageview like
Drawable myDrawable = imageView.getDrawable();
You can compare it with a drawable resource like
if(iv.getDrawable()==getResources().getDrawable(R.drawable.image1)){
//do work here
}
getDrawable
Return a drawable object associated with a particular resource ID and
styled for the specified theme.
You should pass OBJECT
bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
FYI
Drawable drawable = image.getDrawable();
You already have a bitmap and you have set it to imageview. Why do you need this line
bitmap = ((BitmapDrawable) ImageView.getdrawable()).getBitmap();
The error is saying that there is no method called getDrawable() in the ImageView class.
I think you can use it Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);directly. may be not need bitmap = ((BitmapDrawable) image.getdrawable()).getBitmap();
You are getting drawable from empty imageview that will return null. for getting bitmap from drawble, try this method.
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
Hope it will help you!!
I've been trying to add an image from drawable folder into a notification line. But the image doesn't appear and [OBJ] is shown instead.
I can add image in any other place on notifications. Also I can add emoji into a notification line like this issue Android notification - custom inboxstyle (add line ) .
But I can not add an image.
Is there any chance to overcome this issue?
public void someMethod() {
...
mInboxStyle.addLine(imageSpanned());
...
}
private Spanned imageSpanned () {
String imgString = "Something <img src=\"ic_arrow_forward_black_24dp\">";
return Html.fromHtml(imgString, mImageGetter, null);
}
Html.ImageGetter mImageGetter = new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
Drawable drawable;
Resources res = mContext.getResources();
int drawableId = res.getIdentifier(source, "drawable", mContext.getPackageName());
drawable = res.getDrawable(drawableId);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
drawable.setBounds(0, 0, width, height);
return drawable;
}
};
You need to provide ic_arrow_forward_black_24dp icon resource in your drawables or mipmap.
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Something").append(" ");
builder.setSpan(
new ImageSpan(
getActivity(),
R.drawable.ic_arrow_forward_black_24dp),
builder.length() - 1,
builder.length(),
0
));
textView.setText(builder);
This is my first post and while I am new to Android, this community has been great so far.
Here is the trouble I am having with my relatively simple application.
I have a image view on my main activity. onClick, the image view will open up the Camera application. I can take a picture and the camera application will return that picture and set it as the picture in the image view.
The main activity will crash when I start in one orientation and take a picture in another. Example: I open the main activity initially in a vertical orientation, open the camera application and switch to a horizontal view, and take a picture. When the camera application tries to return the picture the main activity crashes. The application does not crash when all activities are used in the same orientation.
I'm lead to believe it's either the way that I am saving the picture or that on onResume, the main activity doesn't have enough time to switch to the new orientation and receive the picture before it crashes.... or maybe that it simply destroys the picture when the main activity is resumed.
public class mainActivity extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
//Declares variable of mImageView
ImageView mImageView;
String mCurrentPhotoPath;
//String activityOrientation;
File photoFile = null;
Uri uriFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting mImageView to the UI ID of
mImageView = (ImageView) findViewById(R.id.imageViewLicense); // making mImageView = the license image view right now just to make sure the code works, I can add to later when adding the medical card
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
uriFile = Uri.parse(savedInstanceState.getString("cameraImageUri"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (uriFile != null) {
outState.putString("cameraImageUri", uriFile.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Initialized the camera to take a picture then return the result of the picture
public void dispatchTakePictureIntent(View view)
{
//Create new intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
uriFile = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
uriFile);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
//Method for rotating the image of the bitmap to the corrected orientation
private Bitmap adjustImageOrientation(Bitmap image) {
ExifInterface exif;
try {
exif = new ExifInterface(mCurrentPhotoPath);
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 = image.getWidth();
int h = image.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap & convert to ARGB_8888, required by tess
image = Bitmap.createBitmap(image, 0, 0, w, h, mtx, false);
}
} catch (IOException e) {
return null;
}
return image.copy(Bitmap.Config.ARGB_8888, true);
}
//The photo taken in the takePicture method is returned here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// 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 = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
//Rotates the image to the proper orientation
Bitmap adjustedBitmap = adjustImageOrientation(bitmap);
//Sets the original imageview as picture taken.
mImageView.setImageBitmap(adjustedBitmap);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
}
Android restarts the main activity when the orientation changes so you'll need to disable or handle that. You can find out more here: How do I disable orientation change on Android?
The accepted answer is bad practice, see Why not use always android:configChanges="keyboardHidden|orientation"?.
It would be a better idea to save your mCurrentPhotoPath variable.
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("filepath", mCurrentPhotoPath);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
mCurrentPhotoPath = state.getString("filepath");
super.onRestoreInstanceState(state);
}
I am experimenting with the android FaceDetector.
I need to use a bitmap file (faces.bmp is from a group photo) since I have not found a way to use the android camera in the android emulator.
But BitmapFactory.decodeFile returns null and the documentation only says it returns null if the bitmap could not be decoded. It is just a 24 bit .bmp file. I am using Eclipse on Windows 7. Did I specify pathName incorrectly? Do I need to use something other than a 24 bit .bmp file?
public class MyFaces extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final int width = 600;
final int height = 600;
final int maxFaces = 8;
FaceDetector faceDetector = new FaceDetector(width, height, maxFaces);
String pathName = "../res/drawable-hdpi/faces.bmp";
try {
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
Face faces[] = new Face[maxFaces];
int nFaces = faceDetector.findFaces(bitmap, faces);
Log.d(this.getClass().toString(), "Faces: " + nFaces);
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e);
}
}
}
If you are just testing then in place of Bitmap bitmap = BitmapFactory.decodeFile(pathName); you could use:
Bitmap bitmap = BitmapFactory.decodeResource(R.drawable.faces);