onSaveInstanceState for ImageVeiw - java

I'm making a dice game and I want to save the image View when I rotate the screen.
I have tried to save the value and then re-establish it. This worked but when I wanted to download the picture but the value I saved it does not work.
// How do I save this?
public void setDiceOne() {
getDiceOne = new DiceAll(diceOne);
getDiceOne.getRandomNumber();
getDiceOne.getImageWhite();
}
public void setDiceTwo() {
getDiceTwo = new DiceAll(diceTwo);
getDiceTwo.getRandomNumber();
getDiceTwo.getImageWhite();
}

Related

how to print a layout with Print Document Adapter in android

i want to preview a layout for printer and want to print that layout. i already searched a lot but didn't find any way. i dont want to print many pages of document i just want to print one page one layout.
the layout contains text information, one list view and one imageView of QR code.
I have tried the following code:
private void doPrint() {
// Get a PrintManager instance
PrintManager printManager = (PrintManager) getApplicationContext()
.getSystemService(Context.PRINT_SERVICE);
// Set job name, which will be displayed in the print queue
String jobName = getApplicationContext().getString(R.string.app_name) + " Document";
// Start a print job, passing in a PrintDocumentAdapter implementation
// to handle the generation of a print document
printManager.print(jobName, new MyPrintDocumentAdapter(getApplicationContext()),
null);
}
and this is my Adapter class
package com.example.haier.arksolsfollow;
import android.content.Context;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.widget.Toast;
class MyPrintDocumentAdapter extends PrintDocumentAdapter {
public MyPrintDocumentAdapter(Context applicationContext) {
}
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
computePageCount(oldAttributes);
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onFinish() {
super.onFinish();
}
private int computePageCount(PrintAttributes printAttributes) {
int itemsPerPage = 4; // default item count for portrait mode
// default item count for portrait mode
PrintAttributes.MediaSize pageSize = printAttributes.getMediaSize();
if (!pageSize.isPortrait()) {
// Six items per page in landscape orientation
itemsPerPage = 6;
}
// Determine number of print items
int printItemCount = 1;
return (int) Math.ceil(printItemCount / itemsPerPage);
}
}
my app also get crashes in this line
printManager.print(jobName, new MyPrintDocumentAdapter(getApplicationContext()),
null);
kindly guide me how to use all call back methods in adapter and how to preview a layout for printer
If i understood correctly you simply want to take a printout of your current layout. Assuming that i can provide you with an alternative solution. What you can do is first generate a bitmap of the layout you want to print and then pass it to the Printer Helper. You can even preview the bitmap before printing by setting it to an ImageView.
You can convert the layout view directly to a bitmap using below code.
View v = THE_LAYOUT_TO_BE_PRINTED;
Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
v.draw(c);
Then you can print the bitmap using Print Helper
PrintHelper photoPrinter = new PrintHelper(getActivity());
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
photoPrinter.printBitmap("layout.png", bmp);
Below information is as for the Android Developer Documentation.
After the printBitmap() method is called, no further action from your
application is required. The Android print user interface appears,
allowing the user to select a printer and printing options. The user
can then print the image or cancel the action. If the user chooses to
print the image, a print job is created and a printing notification
appears in the system bar.
Edit:
Above method can be used to get a print out of an simple image without using the PrintDocumentAdapter itself. But if someone still prefers to use a custom PrintDocumentAdapter as in the original question, well constructed following article in Github will give a clear idea.

Load media thumbnails efficiently

I've spent few days to solve this problem but still can't find a solution. I'm new to Android so my code might be pretty messy!
I have a RecyclerView(Grid layout) that displays thumbnails for images and videos. It loads media files in a specific folder. But when I launch this activity, it takes up so much memory!
To load thumbnails, I created two threads.
Thread 1) MediaLoadThread that queries media files in SDCard. It loops through the cursor and queue thumbnail decode tasks to the different thread.
Thread 2) ThumbnailLoaderThread that decode each individual thumbnail. It receives the content resolver, media type(image or video), and media id. It uses basic .getThumbnail() method. After it's done with getting thumbnail, it triggers the response callback to it's caller thread(MediaLoadThread).
3) When MediaLoadThread(Thread 1) receives the callback, it triggers another callback that lets the activity update the adapter item of the given position. The adapter updates the UI and finally the thumbnail ImageView changes from placeholder to actual thumbnail.
:::Here's my code:::
1) MediaLoadThread.java
#Override
public void run() {
mMediaDataArr.clear();
mLoaderThread.start(); // Prepping the thread 2
mLoaderThread.prepareHandler();
// .... SD Card query stuff .....
if (mediaCursor != null && mediaCursor.moveToFirst()) {
do {
mMediaDataArr.add(new MediaData(videoCursor.getInt(columnIndexId),
mediaCursor.getLong(columnIndexDate), //ID
mediaCursor.getInt(columnIndexType), //MEDIA TYPE
null); //THUMBNAIL BITMAP (NULL UNTIL THE ACTUAL THUMBNAIL IS DECODED)
} while (mediaCursor.moveToNext());
mediaCursor.close();
mResponseHandler.post(new Runnable() {
#Override
public void run() {
// This callback lets the activity activate the adapter and recyclerview so that the user can interact with recyclerview before the app finishes decoding thumbnails.
mCallback.onVideoLoaded(mMediaDataArr);
}
});
//Passing tasks to thread 2
for (int i = 0; i < mMediaDataArr.size(); i++) {
mLoaderThread.queueTask(
mMediaDataArr.get(i).getmMediaType(),
i, mMediaDataArr.get(i).getmMediaId());
}
}
}
}
// This is triggered by thread 2 when it finishes decoding
#Override
public void onThumbnailLoaded(final int position, final Bitmap thumbnail) {
mResponseHandler.post(new Runnable() {
#Override
public void run() {
mCallback.onThumbnailPrepared(position, thumbnail);
}
});
}
2) ThumbnailLoaderThread.java
public void queueTask(int mediaType, int position, int videoId) {
mWorkerHandler.obtainMessage(mediaType, position, videoId).sendToTarget();
}
public void prepareHandler() {
mWorkerHandler = new Handler(getLooper(), new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
int type = msg.what;
final int position = msg.arg1;
int videoId = msg.arg2;
try {
if (type == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
Bitmap newThumb = MediaStore.Images.Thumbnails
.getThumbnail(mCr, videoId,
MediaStore.Images.Thumbnails.MINI_KIND, null);
postResult(position, newThumb);
} else if (type == MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO) {
Bitmap newThumb = MediaStore.Video.Thumbnails
.getThumbnail(mCr, videoId,
MediaStore.Video.Thumbnails.MINI_KIND, null);
postResult(position, newThumb);
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
}
private void postResult(final int position, final Bitmap newThumb) {
mResponseHandler.post(new Runnable() {
#Override
public void run() {
mCallback.onThumbnailLoaded(position, newThumb);
}
});
}
3) LibraryActivity.java
#Override
public void onThumbnailPrepared(int position, Bitmap thumbnail) {
if (thumbnail != null && position < mData.size()) {
MediaData updatedData = mData.get(position);
updatedData.setmThumbnail(thumbnail);
mData.set(position, updatedData);
mVideoAdapter.notifyItemChanged(position);
}
}
The flow is like this.
1) The activity starts the thread 1.
2) Thread 1 starts querying files and starts thread 2. It passes the media id looping through the cursor.
3) Thread 2 decodes thumbnails with the given media id.
4) When decoding is done, thread 2 triggers the callback to Thread 1 with the result bitmap.
5) Thread 1 receives the bitmap and delivers the bitmap to activity through callback.
6) Activity receives the thumbnail and updates the RecyclerView data with the given bitmap.
It works fine, but when the system allocates almost 50MB of memory for this task... Considering it was only loading 100 thumbnails, I think it's pretty heavy.
:::What I've tried:::
1) I extracted the URI of each individual thumbnail and let the recyclerview adapter to load the image with the given URI when it binds. It works fine and did not consume that much memory, but because it loads images when the item is bound, it reloads the thumbnail whenever I scroll the screen with a little bit of delay.
2) I let the adapter to load thumbnails with the direct thumbnail path. But it won't work when the user cleans up the /.thumbnails folder.
3) I set the BitmapFactory.Options samplsize into 4 when the thread decodes thumbnails. But when it was still heavy and even slower sometimes...
4) In MediaData object, it holds the thumbnail bitmap as a member variable. So I made it null right after the adapter loaded it into the ImageView. Still heavy, and because I made the object's thumbnail into null, it just shows the placeholder when I scroll back.
I really have no clue. Any help would be appreciated!!
You can used nostra universal image loader library to load images. This library is very good for image loading and also some other library like Picasso, glide etc available which you can used instead of making manual coding.

Finding Screen Dimensions Android

I have read a few posts on this site about finding screen dimensions and most of them reference getWindowManager().getDefaultDisplay;
I tried to this is my code and got an error saying cannot resolve method getWindowManager(). My code is below so you can fully understand:
public class MainActivity {
public static void main(String args[])throws IOException{
Display display = getWindowManager().getDefaultDisplay;
//WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
//int displayid = Display.DEFAULT_DISPLAY;
//Display display = DisplayManager.getDisplay(displayid);
int tlx = (168/800)*display.getWidth();
int tly = (136/480)*display.getHeight();
int brx = (631/800)*display.getWidth();
int bry = (343/480)*display.getHeight();
int rotation = display.getRotation();
This is just an excerpt in case somethings don't make sense. Also, I'm using the display dimensions to find screen elements within an application. If I should be using the window dimensions for this please inform me upon how to go about doing that as well, but I still need to get the display right so I can use methods such as the .getRotation() one shown above. Thanks in advance for your help.
You need to reference getWindowManager from an Activity. Your MainActivity doesn't appear to be extending Activity so you either need to extend Actvity
public class MainActivity extends Activity {
Or pass an activity to that class then do something like this.
Display display = myActivity.getWindowManager().getDefaultDisplay();
Or through a Context
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

How to check if an imageview has an image in it and skip over the image to the next imageview

Kinda like hangman
how to skip over the imageview if something is in it and check to see if something is in it
trying to check the imageView if there is an image in it
CODE
final boolean imageThere = mImageView17.setBackgroundResource(null);
public void image6(){
randomNumber();
final int thisLetter = currentLetter;
final boolean imageThere = mImageView17.setBackgroundResource(null);
mImageView6 = (ImageView) findViewById(R.id.imageView6);
mImageView6.setImageResource(thisLetter);
mImageView6.bringToFront();
mImageView17 = (ImageView)findViewById(R.id.imageView17);
mImageView6.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (imageThere == false) {
mImageView17.setImageResource(thisLetter);
mImageView17.bringToFront();
mImageView6.setImageResource(R.drawable.whitespace);
} else {
mImageView18.setImageResource(thisLetter);
mImageView18.bringToFront();
mImageView6.setImageResource(R.drawable.whitespace);
}
}
});
mImageView17.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mImageView6.setImageResource(thisLetter);
mImageView6.bringToFront();
mImageView17.setImageResource(R.drawable.whitespace);
}
});
}
Basically I want to check the ImageView to see if the image in imageview 17 is there, If it is, Skip over 17 and add imageresource 6 to imageview18
I also want to make sure that if I do this for another imageview17 does not get messed up when I add the same code to imageview 6 of 7 or 8 when I click on image view 17
How do I go about fixing this?
if (mImageView17.getDrawable() != null) {
// I already have a bitmap
}
the doc for getDrawable says:
Return the view's drawable, or null if no drawable has been assigned.
I think you'd be better off storing your game state in some other Variables / Objects that are designed specifically to store that information, rather than relying on your UI to store the gamestate for you.
So for instance if the user gets 18 guesses you could store an int that represents how many times the user has guessed. And then based on that int you will make a decision on how to update the UI(which image view to set the image in). I don't know the exact mechanics of your game, so I may have overspimplified it, but the overall approach of storing your game state in some Object should be possible no matter what your game mechanics are.
This way you always have access to your game state anything you may need it for, and you can use that int to update the UI accordingly as play continues.
You can use getDrawable() for it to check whether the drawable has been set already. Check for every imageview and continue looping. Source.

How to dynamic update the adapter for activities?

I am working on an app which combines the SQL and the adapter. The main issue is that once I updated the database, the adapter will not reflect my update directly. Here's the code:
public class RSSItemActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rssitem);
long channelid = getIntent().getExtras().getLong(RSSReaderApp.CHANNEL_KEY);
DBAdaptor dbAdaptor = ((RSSReaderApp)getApplication()).getDBAdaptor();
Cursor cursor = dbAdaptor.getRssItems(channelid);
adapter = new RSSItemAdapter(this, R.layout.rssitemview, cursor);
setListAdapter(adapter);
}
As you can see, this code get the data from the SQL at the line Cursor cursor = dbAdaptor.getRssItems(channelid);(The get RssItems is just loading data we want to present on the screen from the SQL). However, I have some bottoms in the same activity that if I press that, it will change the values in the SQL, which should affect the data it retrieve. (For example, there's a column decide what's these item's color, it is originally set to white, after I press that, it should be blue.) However, once I press that, seems although the data in the SQL is changed, but the real presentation is still the same color. I had tried using adapter.swapCursor(dbAdapter.getRssItems(id)); on the bottom to update the cursor everytime I press the buttom, but it will let my original display disappear (Possibly because the original adapter loses it's cursor,so it can display nothing), I have to reload that page to get the correct output. Is there a way that I can instantly update the output? Thanks for your reply in advance =)
You will have to update the cursor in the adapter. You could call the following:
// Closes the old cursor as well.
adapter.changeCursor(dbAdapter.getRssItems(id));
// Notify the view that the underlying data has changed.
adapter.notifyDataSetChanged();
Also, the difference with swapCursor() is that changeCursor, automatically closes the old cursor, while swapCursor does not.
try this...
runOnUiThread(returnResult);
private Runnable returnResult = new Runnable() {
#Override
public void run() {
if(array_list.size() > 0)
{
m_adapter.notifyDataSetChanged();
for(int i=0;i<array_list.size();i++)
m_adapter.add(array_list.get(i));
}
m_adapter.notifyDataSetChanged();
}
};

Categories

Resources