How to call getDrawable method - android

I am creating an image sharing app which uses a button to share images. I'm getting an unable to resolve the required method error in the code below:
public class ShareActivity extends Activity implements View.OnClickListener {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
private void button1Click()
{
BitmapDrawable bm = (BitmapDrawable) getDrawable(button1);
Bitmap mysharebmp = bm.getBitmap();
String path = Images.Media.insertImage(getContentResolver(),
mysharebmp, "MyImage", null);
On this line:
BitmapDrawable bm = (BitmapDrawable) getDrawable(button1);ShareActivity
I am getting The method getDrawable(Button) is undefined for the type ShareActivity. Why might I be getting this error? The full code is here.

It's extremely unclear as to what you want to do here, and I suspect you're going to encounter a number of other problems with this code. But the reason that you're getting the error "getDrawable is undefined for ShareActivity" is because the Activity class does not have a getDrawable method.
Instead of calling getDrawable, you need to get the app resources and then retrieve the drawable. What you're looking for is:
BitmapDrawable bm = (BitmapDrawable) getResources().getDrawable(R.drawable.my_bitmap);
Where you have some image called "my_bitmap.png" in /res/drawable/.
Edit Feb 7 2016: This answer is no longer correct. Context#getDrawable(int) was added in API 21 (Lollipop) which was released in November 2014.
Note that you probably shouldn't be using it anyway.

If you are trying to get the image displayed inside the button the consider using the function defined inside the image button object.
I mean to say use button1.getDrawable()

The getDrawable() method requires id of the resource and in this case you are passing Button. Try passing R.id.button1
Here is the documentation

Related

How to print image displayed in ImageView in android Studio

I have a recyclerView which will display all images from JSON path and I used a click event that will display the clicked image to a new activity.
Now I want to print the image that is displayed. I have put a print button in the activity and while clicking on the print button i should get image to be printed in the network printer. I have used the below code. but I am getting error in getActivity() .
Button print = findViewById(R.id.print);
//imageView.setDrawingCacheEnabled( true );
print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PrintHelper photoPrinter = new PrintHelper(getActivity());
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
//Bitmap bitmap = imageView.getDrawingCache( );
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
photoPrinter.printBitmap("test print",bitmap);
}
});
Any help will be greatly appreciated :)
Use Activity.this instead of getActivity() where Activity is the name of your Activity.
The method getActivity() is used when you want to reference Fragments. But here you have an activity so there is an error! You have to do something like this:
//Other code
PrintHelper photoPrinter = new PrintHelper(YourJavaClassName.this);
//Other code
Please be sure to change YourJavaClassName to your activity's class name.
You can use getapplicationcontext() method or YourCurrentActivityName.this

calling functions from another class having errors

I have 2 class: Main and Image.
My problem is how can I call a function from Image to Main because I have this error: Non-static method 'pickImg()' cannot be referenced from a static context
Main = main program
Image = getting image by camera capture/gallery and cropping
Main.java
public void getImg(){
ImageView iv1 = findViewById(R.id.imgVw);
Bitmap img = Image.pickImg();
iv1.setImageBitmap(img);
}
Image.java
public void pickImg() {
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
I read some topics about the error above and i tried to change public void pickImg() to public static Bitmap pickImg(Bitmap img) and put return at the end to return the image to fulfill the error above but I get an error to startActivityForResult. I also tried using #Override to make another void function inside pickImg() but I get Annotations are not allowed here error.
But when I put (based on some answers that I read)
Image IPick = new Image();
Bitmap newI = IPick.pickImg();
public void pickImg() changes to public Bitmap pickImg() I get no error but I dont know what or how to return the image to Main since that function has try{}catch{} for camera intent only and that function is the first function that is needed and the one that will be called for getting image.
Any help/suggestion/getaround?
For those who will ask why I created 2 class instead of using 1, I created different class to avoid long codes in Main.java since I still have things to put on my app.
[EDIT-TL;DR]
I can take image with camera when i put my codes on Main.java. But if I put my codes on Image.java and call the function on Main.java, that is where im having a problem. And I can't seem to put the cropped image to imageview(app crashes).
Create the constructor of Image class and pass the MainActivity reference in constructor.
for e.g.
class Image
{
private MainActivity mActivity;
public Image(MainActivity activity){
this.mActivity=activity;
}
}
& then call your main activity methods from image class.
mActivity.yourActivityMethod();

Android ImageView From URL: Not Getting Set (Using Picasso)

I'm brand new to Android development, so I'm probably doing something stupid. Any ideas why this code shouldn't work?
It compiles and runs, but doesn't actually successfully set the image (which is previously set to a gray background).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
Button getImageButton = (Button) (findViewById(R.id.btnGetImage));
getImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView myImageView = (ImageView) (findViewById(R.id.myImageView));
Picasso.with(v.getContext()).load("https://www.example.com/someimage").into(myImageView);
}
});
}
alter you code this way
Picasso.with(YOUR_ACTIVITY_NAME.this).load("https://www.example.com/someimage").into(myImageView);
Here v.getContext() is not related to the main context, so it won't help you, we need to pass context of current activity
Please try this and let me know.
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
Button getImageButton = (Button) (findViewById(R.id.btnGetImage));
ImageView myImageView = (ImageView) (findViewById(R.id.myImageView));
getImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Picasso.with(YourActivityName.this).load("https://www.example.com/someimage").into(myImageView);
}
});
}
Ding ding here is my answer
I am sure that you add the dependency
compile 'com.squareup.picasso:picasso:2.5.2'
and used the right url
Picasso.with(v.getContext()).load("http://i.imgur.com/DvpvklR.png").into(imageView);
I am telling you where you went wrong !!
Magic : Have you added the internet permission ? It needs to be in your manifest
<uses-permission android:name="android.permission.INTERNET" />
Rather than that your code is just fine
But i recommend you to use getApplicationContext()
copying from my comment
Picasso is a library and not an application. While creating
Picasso instance if you'll not pass context, then how do you think
it will get the application context from ? For it to work it requires
context , and it definitely needs to be provided by the application
using this library.It also prevents leaking an Activity (if that's
what you pass ,some of below answers have used ) by switching to the
application context. use getApplicationContext()
And for the people who randomly put an answer here read this as well
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside
of). Use this instead of the current Activity context if you need a
context tied to the lifecycle of the entire application, not just the
current Activity.
ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The
Context referred to from inside that ContextWrapper is accessed via
getBaseContext().
so any way he is accessing the currant activity context.
Cheers!
step 1 In Menifest check Internet Connection
<uses-permission android:name="android.permission.INTERNET" />
step 2 compile "com.squareup.picasso:picasso:2.4.0"
step 3 Image url is not showing any image in browser paste your url in browser and if you get image then you can set that image to imagview
step 4 check url is working or not there is not .png or .jpg extension for imagfile
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
Button getImageButton = (Button) (findViewById(R.id.btnGetImage));
getImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Initializing the ImageView
imageView = (ImageView) findViewById(R.id.imageView);
//Loading Image from URL
Picasso.with(this)
.load("https://www.example.com/someimage")
.placeholder(R.drawable.placeholder) // optional
.error(R.drawable.error) // optional
.resize(400,400) // optional
.into(imageView);
}
});
}

Monodroid - ImageView -> SetImageURI crash application

I have an issue displaying a picture taken from the Camera.
I proceed as the following:
Calling Camera Activity -> Saving Picture -> Keeping Picture Location as a string.
Creating a new Intent -> Setting String extra with the Picture Location.
Calling the activity and retreiving the string.
Switching back to an URI using Parse on the string containing the file location.
Calling SetImageURI on the ImageView. <- this crashes.
I get the "Application had to close unexpectedly" thing..
Not really handy to debug.
There's the code for the Activity:
[Activity (Label = "ViewPhoto")]
public class ViewPhoto : Activity
{
ImageView image;
protected override void OnResume ()
{
string PhotoLocation = Intent.GetStringExtra ("PicLoc");
Android.Net.Uri _img = Android.Net.Uri.Parse (PhotoLocation);
image.SetImageURI (_img);
}
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.PhotoViewer);
image = FindViewById<ImageView> (Resource.Id.exCurrentPhoto);
}
}
I checked the picture weight.. it's 9kb (its probably a simple picture generated through the android emulator I use).. so I doubt it's a memory issue o.o
Thanks for helping.
I hate myself for not noticing I had forgotten to call the base.OnResume() function...
Without exception being thrown I didn't realise until I randomly had to go through the Android LogCat x)
Problem solved =D

Screen capture inside the method onCreate not working in android

I am working in an android application and I want to capture the screen of current activity in the Overrided method onCreate(). The bitmap returns null when I wrote the code for capturing screen inside the Overrided method onCreate(). But when I call the same code in a button click in the same activity the bitmap returns the correct value. Please correct my code to return by bitmap in my ocCreate() method itself.
My code is :
View v1 = findViewById(R.id.printpreviewBaseScrollView);
v1.setDrawingCacheEnabled(true);
Bitmap bmv = v1.getDrawingCache();
View printlayout = findViewById(R.id.printpreviewBaseRelativeLayout);
printlayout.setDrawingCacheEnabled(true);
printlayout.measure(printlayout.getMeasuredWidth(),
printlayout.getMeasuredHeight());
printlayout.layout(0, 0, 700, 1755);
Log.e("width", "" + printlayout.getMeasuredWidth());
Log.e("hight", "" + printlayout.getMeasuredHeight());
printlayout.buildDrawingCache(true);
bitmap = Bitmap.createBitmap(printlayout.getDrawingCache());
printlayout.setDrawingCacheEnabled(false); // clear drawing cache
You must do it later than onCreate. During onCreate, your layout is measured and inflated but your UI is not yet created. See the Activity life cycle documentation:
http://developer.android.com/training/basics/activity-lifecycle/starting.html
#Override
public void onStart(){
View v1 = findViewById(R.id.printpreviewBaseScrollView);
v1.setDrawingCacheEnabled(true);
Bitmap bmv = v1.getDrawingCache();
}
I just copied and pasted your code. You should probably make v1 a class level variable, set it's reference in onCreate(), then get the bitmap in onStart().
Create method called
void screenshot(){
Your btimap code
}
Onactivity call
screenshot();
As the method 'onCreate()' suggests your activity will be created in this moment. So you can't take a screen capture at this point. Try your code in 'onResume()':
...
#Override
public void onResume(){
View v1 = findViewById(R.id.printpreviewBaseScrollView);
v1.setDrawingCacheEnabled(true);
Bitmap bmv = v1.getDrawingCache();
}
...
According to android's documation
The visible lifetime of an activity happens between a call to
onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user.
As can be seen from the graph above, it is not in the visible lifetime when onCreate() is executed, and you cannot get the screenshot.
Move your code to onResume(), which should be in the visible lifetime.

Categories

Resources