Screen capture inside the method onCreate not working in android - 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.

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

Want to clear EditText content before activity goes in background

Use case is when user enters it's info in edittext and intentionally or unintentionally user sends the application in background. In such case I don't want to display edittext info in recent apps list screenshot and when user again resume the app I want to populate same info in edittext.
Another option is:
FLAG_SECURE - treat the content of the window as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.
More details here
But this also dissallows screenshots (not sure if u want that)
to use this add the following line to your onCreate() :
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
------------------------EDIT-------------------------
If u want to show the application in the "recent apps" list, but without the editText, than u might want to do something like this:
private string mySecretText;
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
//Now we remember the text
mySecretText = myEditText.getText().toString();
//Optional save it in your Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("secretText", mySecretText);
editor.apply();
//Remove the text from the editText
myEditText.setText("");
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//Optional load it from your Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
mySecretText = preferences.getString("secretText", "Default"); //U can remove default if u want
myEditText.setText(mySecretText);
}
------------------------EDIT-------------------------
Or u can change the complete thumbnail:
onCreateThumbnail - Generate a new thumbnail for this activity. This method is called before pausing the activity, and should draw into outBitmap the imagery for the desired thumbnail in the dimensions of that bitmap. It can use the given canvas, which is configured to draw into the bitmap, for rendering if desired.
Important!: The default implementation returns fails and does not draw a thumbnail; this will result in the platform creating its own thumbnail if needed.
So create ur own thumbnail
#Override
public boolean onCreateThumbnail (Bitmap outBitmap, Canvas canvas) {
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.myBitmap);
canvas.drawBitmap(myBitmap, 0, 0, null);
return true;
}
Good luck!
in the async task on execute add these lines
1. If u want to hide edittext box theneditext.setVisibility(View.INVISIBLE);
or
2.if u want to clear the content theneditext.clear();
You can use the activity lifecycle callback methods to clear (.clear()) or populate (.setText("some text")) the EditText.
onResume : the user sees and can interact with the activity.
onPause : the activity is partially or totally in background.
You could save the info as a shared preferences in MODE_PRIVATE for the current activity.
SharedPreferences sharedPreferences;
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
write a shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("INFO", "some text");
editor.commit();
read a shared pref
String info = sharedPreferences.getString("INFO", "default value");
So you can read the SP in onResume and write it in onPause, just before you clear the EditText content.
You can try the attribute, android:noHistory="true" for the activity tag in the manifest file.
It will destroy the trace.
OR if you want to show blank view in the recent list then:
Override onStop() method and just try resetting the content view of your activity to some blank xml file before you call super.onStop().
Probably, Android framework will make a screenshot of your app for showing in the recent apps when activity.onStop() is called.
Hope it will solve your problem.

Call fragment method from activity but view is null

I am checking internet connection in my main activity.If connection is lost,I want to show reconnecting message in fragment.Example:If I run following code in main activity my app is crashing.
ConversationFragment conv1 = new ConversationFragment();
conv1.showReconnecting();
And this is the showReconnecting method in fragment:
public void showReconnecting() {
final RelativeLayout rel=(RelativeLayout)rootView.findViewById(R.id.reconnecting);
rel.setVisibility(View.VISIBLE);
}
I know why my app is crashing because rootView is setting in onCreateView and when I call this method from activity rootView is returning null.
What can I do for resolve this problem ?
Try this (Assuming reconnecting view is in fragment and your fragment is visible on screen),
public void showReconnecting() {
if (conv1 != null && conv1.getView()!=null) {
final RelativeLayout rel=(RelativeLayout)conv1.getView().findViewById(R.id.reconnecting);
rel.setVisibility(View.VISIBLE);
}
}
If conv1 is not available then please make it class variable.
According to what you want to do, a simple ProgressDialog will do the job. You can lauch it from your ChatFragment, like this:
First, declare it on your Fragment:
private ProgressDialog connectiongProgressDialog;
Then, when you want to show it, use:
connectiongProgressDialog = ProgressDialog.show(getActivity(), "My title", "Reconnecting");
When you want to dismiss it, use:
if (connectiongProgressDialog != null){
connectiongProgressDialog .dismiss();
}
It will display a simple dialog with the message you want.
Well, just looking at this and your explanation, I would think you can't call methods relating to a view (such as a fragment) without creating said fragment. An option, if the fragment is only used for showing the reconnecting, would be just to put some code in the activity and use a Toast.makeText(....).show();
which notifies the user that you are attempting to reconnect. So instead of conv1.showReconnecting(); maybe rather put, Toast.makeText(context,"Reconnecting", Toast.LONG).show(); and then do the necessary background work in an AsyncTask.
I hope this helps.

How to call getDrawable method

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

Is checking savedInstanceState for null in onCreate a good way to tell if the device was rotated?

There's stuff I'd like to do in my Activities' onCreate() method only if they're constructed the first time, not when the device was rotated (on configuration changes). Currently I'm checking the savedInstanceState parameter passed into onCreate() for this. If it's null, then it's the first time the Activity starts, else there was only a rotation.
Is this a good and reliable way to tell this? Are there alternatives to this?
I don't know of a better solution. Romain Guy describes the same approach (checking savedInstance state or other objects you pass for null).
In the new activity, in onCreate(), all you have to do to get your
object back is to call getLastNonConfigurationInstance(). In
Photostream, this method is invoked and if the returned value is not
null, the grid is loaded with the list of photos from the previous
activity:
private void loadPhotos() {
final Object data = getLastNonConfigurationInstance();
// The activity is starting for the first time, load the photos from Flickr
if (data == null) {
mTask = new GetPhotoListTask().execute(mCurrentPage);
} else {
// The activity was destroyed/created automatically, populate the grid
// of photos with the images loaded by the previous activity
final LoadedPhoto[] photos = (LoadedPhoto[]) data;
for (LoadedPhoto photo : photos) {
addPhoto(photo);
}
}
}
When I am lazy to do this, I just disable recreating the Activity on orientation change. As described at How do I disable orientation change on Android?

Categories

Resources