Finding Screen Dimensions Android - java

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();

Related

Android Studio: Getting id of Dialog TextView in another class?

I'm trying to create a couple of Progress Bars inside a Dialog "remaining_amount_report" in Activtiy A:
public void setProgressBars(){
ProgressBar_Setup setup = new ProgressBar_Setup();
setup.createProgressBar(1, "product1", 80);
setup.createProgressBar(2, "product2", 60);
setup.createProgressBar(3, "product3", 100);
setup.createProgressBar(4, "product4", 20);
}
Therefore I've created a Class "ProgressBar_Setup" where the Method is reachable.
But the problem is, since I want to overwrite some TextView Texts of the Dialog, I need to get access to the Dialog inside the Class.
The Class extends Activity A, so I normally should get access just like this:
public void createProgressBar(int position, String productname, int progress) {
mposition = position;
switch(mposition){
case 1:
progressbar[0].setProductname(((TextView) remaining_amount_report.findViewById(R.id.remaining_amount_productname_1)));
But I get an Null Object Reference Error, by doing this.
Then I tried a different way, by adding a Dialog Variable to the "createProgressBar"-Method (not really good behavour, I guess):
public void setProgressBars(){
ProgressBar_Setup setup = new ProgressBar_Setup();
setup.createProgressBar(1, "product1", 80, remaining_amount_report);
setup.createProgressBar(2, "product2", 60, remaining_amount_report);
setup.createProgressBar(3, "product3", 100, remaining_amount_report);
setup.createProgressBar(4, "product4", 20, remaining_amount_report);
And in the ProgressBar_Setup-Class
public void createProgressBar(int position, String productname, int progress, Dialog dialog) {
mposition = position;
switch(mposition){
case 1:
progressbar[0].setProductname(((TextView) dialog.findViewById(R.id.remaining_amount_productname_1)));
But still the same error.
Could you help me here?
Thank you!
I think you need to use findViewById to first link the views in progressbar.

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.

imageButton in RecyclerView not displaying

I've been a lurker on your forums for some time now, and they have helped me enormously on a variety of issues I've had, so thanks! :D
I'm trying to create my first app for android and it's a card game named shithead that my friends and I used to play often.
I've decided to use a RecyclerView to display your hand. I need to be able to dynamically add buttons (with card images) to the display at runtime. From what I can tell, I need an adapter for this.
Using the handy guide at "https:// guides.codepath.com/android/using-the-recyclerview" and attempting to modify it for my own purposes I've come very close to a test run of making this work. When I run the program on an emulator in Android Studio, it gives me the following display:
images displayed as grey rectangles
I feel like I've got to be really close, and I'm simply missing some crucial syntax for working with android or android studio.
In my Card object I build a String idText that correlates to the card images I have saved in my project's mipmap-hdpi, mipmap-xhdpi etc. folders (mipmap-hdpi shown below)
mipmap-hdpi folder in Android Studio
public Card(int suitInput, int rankInput)
{
suit = suitInput;
rank = rankInput;
faceUp = false;
text = RankString[rank] + " of " + SuitString[suit];
idText = "i_" + RankString[rank] + "_of_" + SuitString[suit];
}
I also have a function getImageId in my Card Class:
public static int getImageId(Context context) {
return context.getResources().getIdentifier("drawable/#+id/" + idText, null, context.getPackageName());
}
my onBindViewHolder method in my CardAdapter is below:
#Override
public void onBindViewHolder(CardAdapter.ViewHolder viewHolder, int position)
{
//get the data model based on position
Card card = mCards.get(position);
//Set item views baased on views and data model
ImageButton imageButton = viewHolder.cardButton;
imageButton.setImageResource(card.getImageId(mContext));
TextView textView = viewHolder.cardText;
textView.setText(card.text);
}
my MainActivity class does very little as of yet. It initializes one player, me, and a Deck of Card objects. It then gives me 6 cards off the top of the unshuffled deck, AKA 2 - 7 of diamonds. It then initializes the CardAdapter.
public class MainActivity extends AppCompatActivity {
Player me;
Deck deck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testdisplay);
//lookup the recyclerview in activity layout
RecyclerView rvCards = (RecyclerView) findViewById(R.id.rvCards);
me = new Player("Dr_StrangeKill");
deck = new Deck();
me.hand.add(deck.getCards().remove(0));
me.hand.add(deck.getCards().remove(0));
me.hand.add(deck.getCards().remove(0));
me.hand.add(deck.getCards().remove(0));
me.hand.add(deck.getCards().remove(0));
me.hand.add(deck.getCards().remove(0));
//create adapter passing in sample user data
CardAdapter adapter = new CardAdapter(this, me.hand);
//Attach the adapter to the recyclerView to populate items
rvCards.setAdapter(adapter);
//Set layout manager to position the items
rvCards.setLayoutManager(new LinearLayoutManager(this));
}
The Deck, Player, and Card objects all appear to be working as intended insofar as the values of the code are concerned, as the resultant display correctly shows that 'Dr_StrangeKill' has received 2 - 7 of Diamonds, but doesn't show the card images themselves! This is my first time working with images in any IDE (eclipse, visual studio, android studio), and I feel like i'm very close but off in some small but crucial way. Any help would be greatly appreciated!
I suggest you put your images in a drawable folder because mipmap folder is for launcher icons, if you want to support different screen densities, here's a link that shows you how to create a drawable folder for each screen density, after that you should get your image identifier like this:
context.getResources().getIdentifier(idText, "drawable", context.getPackageName());
It looks like you're trying to get the identifier of the image resource by name. In that case you could try:
return context.getResources().getIdentifier(idText, "mipmap", context.getPackageName());
But doing that is not recommended. See docs for getIdentifier()
https://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)
You could just add the id (an int) to your card object and instantiate like new Card(R.mipmap.hearts_2,2,"hearts") or however you're instantiating (seems like you're using public fields and no constructor) and grab that id in your adapter to set on the imageview.

Android: Show multiple street views (Google Maps Api)

I have an xml file called activity_collage.xml with 2 street view fragments - I would like both fragments to display the street view of a given location - So a total of 2 street views on the screen
Here's my code:
public class Collage extends ActionBarActivity implements OnStreetViewPanoramaReadyCallback {
StreetViewPanoramaFragment topLeft, topRight;
static final LatLng posOne = new LatLng(43.771925, -79.512460);
static final LatLng posTwo = new LatLng(43.790634, -79.193632);
Here's where I initialize my 2 StreetViewFragment objects in my onCreate() method
topLeft =
(StreetViewPanoramaFragment) getFragmentManager()
.findFragmentById(R.id.picTL);
topLeft.getStreetViewPanoramaAsync(this);
topRight =
(StreetViewPanoramaFragment) getFragmentManager()
.findFragmentById(R.id.picTR);
Here's the overridden method from the OnStreetViewPanoramaReadyCallback interface ...
#Override
public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
panorama.setPosition(posOne);
}
But how do I set the street view for topRight?
According to http://code.google.com/p/gmaps-api-issues/issues/detail?id=6953, multiple StreetViewPanorama Objects are not supported. In my experience, no explicit errors occur, but the second StreetViewPanorama will remain blank.
Frustratingly, I don't think the documentation was updated like the above thread indicates it should have been.
I have the same problem with my fragment XML containing 2 fragments : map fragment, and StreetViewPanoramaFragment. StreetView stays blank. I managed to use it with a simple view instead of fragment.
With Kotlin it gives :
val myFrag=getView()!!.findViewById<StreetViewPanoramaView>(R.id.street_view_panorama)
myFrag.onCreate(savedInstanceState);
myFrag.getStreetViewPanoramaAsync(OnStreetViewPanoramaReadyCallback { panorama ->
panorama.setPosition(LatLng(55.758818, 37.620587))
svPano = panorama
})

Where to place the AsyncTask() so that i can call it to load image?

Below is my coding where it would load the image when this Activity is called. But i wished to display the progressDialog when it was retrieving the images from the server instead of just a black screen presented to the user. I heard that AsyncTask is able to do but i stuck with where to place the AsyncTask function and calling it.
public class LargeImageScroller extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private static Bitmap bmLargeImage; //bitmap large enough to be scrolled
private static Rect displayRect = null; //rect we display to
private Rect scrollRect = null; //rect we scroll over our bitmap with
private int scrollRectX = 0; //current left location of scroll rect
private int scrollRectY = 0; //current top location of scroll rect
private float scrollByX = 0; //x amount to scroll by
private float scrollByY = 0; //y amount to scroll by
private float startX = 0; //track x from one ACTION_MOVE to the next
private float startY = 0; //track y from one ACTION_MOVE to the next
public SampleView(Context context) {
super(context);
displayRect = new Rect(0, 0, displayWidth, displayHeight);
scrollRect = new Rect(0, 0, displayWidth, displayHeight);
bmLargeImage = Bitmap.createBitmap(1035 , 665, Config.ARGB_8888);
bmLargeImage = createMap(this.getContext());
}
public boolean onTouchEvent(MotionEvent event) {....}
protected void onDraw(Canvas canvas) {....}
private static Bitmap createMap(Context context) {...}
private static Drawable LoadImageFromWebOperations(String url) {....}
private static Bitmap decodeFile(File f, int requiredSize) {...}
}
}
I wish to know where should i place the AsyncTask function so as to display the progressDialog while the program is loading the image from server/cache. Most of the source i found on the internet doesn't say much.
AsyncTask is somehow like a Thread. It is used to handle some time-consuming operations so that the main thread won't be blocked.
In your case, AsyncTask is suitable. However, the place where you would like to put it depends on your logic.
Please read the SDK: AsyncTask to get more info about it. There is also a code snippet that may help you.
Added:
Well, I understand your concern. If you just want to show a progress bar to tell the users that the app is downloading the images from the server. You may handle this way:
1. Create a xml layout file containing a ProgressBar.
2. In OnCreate in Class LargeImageScroller, call setContentView(R.layout.that_layout) to show the progressbar, and Start a AsyncTask to download the images.
3.Inside AsyncTask, override onProgressUpdate(Integer... progress) to tell the ProgressBar the donwloading progress.
4. Inside AsyncTask, override onPostExecute(Long result). This method will be called when the AsyncTask finishes. Here you can do : SampleView sv=new SampleView(this), and then pass the images to the sv object. Then call setContentView(sv) to show your images.
This is just my train of thought. I think you can use AsyncTask in either LargeImageScroller class or SampleView class. Hope ithis comment helps.

Categories

Resources