getResources in non-activity class - android

I've been trying to load a bitmap in a non-activity class but everything I've done so far has failed. I have even tried to send the Context as reference, but this also results in error.
My current situation looks like this:
// Surface class
public class GameScreen extends SurfaceView implements Callback {
TileSet ts;
public GameScreen(Context context, AttributeSet attr) {
// Here I send context as a reference
ts = new TileSet(context, R.drawable.tiles);
}
}
// This is the class I need to get resources
public class TileSet {
public TileSet(Context context, int id) {
Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), id);
}
}
Any ideas?

Have you tried just getting the bitmap in the Activity and then passing that to the constructor of your GameScreen?

Related

How to get context of class

I have the following class and i try to get context so as to send an intent to another activity.
public class CloudDocumentTextRecognitionProcessor
extends VisionProcessorBase<FirebaseVisionCloudText> {
public Context mContext;
private FirebaseVisionCloudDocumentTextDetector detector;
public CloudDocumentTextRecognitionProcessor() {
super();
detector = FirebaseVision.getInstance().getVisionCloudDocumentTextDetector();
}
public CloudDocumentTextRecognitionProcessor(Context context) {
this.mContext = context;
}
#Override
protected Task<FirebaseVisionCloudText> detectInImage(FirebaseVisionImage image) {
return detector.detectInImage(image);
}
#Override
protected void onSuccess(
#NonNull FirebaseVisionCloudText text,
#NonNull FrameMetadata frameMetadata,
#NonNull GraphicOverlay graphicOverlay) {
graphicOverlay.clear();
Intent i = new Intent(mContext, ResultActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("key", text.getText());
mContext.startActivity(i);
}
}
But i get an error in the line where i set the intent:
"Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference"
I ve also tried MyApplication.getContext() instead of mContext, but with no results.
Any ideas?
This class does not inherit any Android component that has a Context, so you have to inject it yourself. You have to instantiate the class with the constructor that takes a Context as a parameter, and pass it in from an Activity or other Android component that has a context/access to the app context.
Something like (pseudo-code):
Class MyActivity
{
...
imageProcessor = new CloudDocumentTextRecognitionProcessor(this);
// or imageProcessor = new CloudDocumentTextRecognitionProcessor(this.getApplicationContext());
}
How to choose the context?
If the CloudDocumentTextRecognitionProcessorinstance is supposed to exist throughout the whole lifetime of your app, use getApplicationContext();
If the CloudDocumentTextRecognitionProcessorinstance is guaranteed to only exist during the lifetime of the Activity, use this.
You already have a setter for the mContext field and you can use the secondary constructor for the class that passes the context.
Initialize the class object from your activity like this:
CloudDocumentTextRecognitionProcessor imageProcessor = new CloudDocumentTextRecognitionProcessor(this);
or
CloudDocumentTextRecognitionProcessor imageProcessor = new CloudDocumentTextRecognitionProcessor(getApplicationContext());

This Field leaks context object

I am using Context object inside non-Activity, it is working perfectly but the problem is it shows warning
That is where I am using the context object
Here is the result of inspection
You can use WeakReferences for this case. something like this:
public class ContactsTask {
private WeakReference<Context> weakContext;
public ContactsTask(Context context){
weakContext = new WeakReference<>(context);
}
public void doSomething(){
if (weakContext!=null) weakContext.get() ... //return context without leaks
}
}

Getting Image w/ BitmapFactory

I'm not sure why this is not getting my image. This is my first time working with android apps with java so idk what to do.
public class Player {
private GameView view;
private Bitmap bmp;
public int x, y;
public Player(GameView view) {
this.view = view;
}
public void tick() {
//This is my error here//
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
public void onDraw(Canvas c) {
c.drawBitmap(bmp, x, y, null);
}
}
I'm getting an error when trying to set bmp equal to what I want it to be in my tick method for getResources(). I don't know why getResources() is wrong.
Thanks
getResources() is a method on Context. Your call to getResources() is not in a Java class that inherits from Context. You probably copied this code from some class that does inherit from Context, like Activity.
Your onDraw() method suggests that you are trying to create some custom View. If so, Player would need to inherit from View, and then you could use getContext() in order to retrieve a Context to use for getResources() (e.g., getContext().getResources().

Android: error when using int array passed into class

I am passing an int array from one class to another but am getting an error when I try to access values from it. I have no idea why, hopefully someone can enlighten me?
Here's the first class that calls the second:
public class ConvertToGrid extends Activity{
DrawGrid v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...code...
int[] binArray = {Color.RED, Color.WHITE, Color.YELLOW, ...};
v = new DrawGrid(this, binArray);
setContentView(v);
}}
This calls my DrawGrid View:
public class DrawGrid extends View{
private int[] binary;
public DrawGrid(Context context) {
super(context);
}
public DrawGrid(Context context, int[] inBinary) {
super(context);
binary = inBinary.clone();
}
int sq00c = binary[0];
...etc}
What am I doing wrong such that it cannot access this int array called binary? If I move the int array into DrawGrid it accesses the cells without any trouble, but passing it through with my construct seems to make it inaccessible. In case anyone asks, I can't just define the array in DrawGrid as it is defined by the code in ConvertGrid.
Perhaps I am going about this in the wrong way and there is a better way to pass the int array? Thanks
Edit:
LogCat:
E/AndroidRuntime(12035): FATAL EXCEPTION: main
E/AndroidRuntime(12035): java.lang.RuntimeException: Unable to start activity ComponentInfo{bras2756.ox.ac.uk.colourgrid/bras2756.ox.ac.uk.colourgrid.ConvertToGrid}: java.lang.NullPointerException
You can't do that because your int sq00c = binary[0]; type statements are outside a method body, and hence get executed before your constructor is called, which makes the binary array empty. So when you try to access data in it, you'll get an ArrayIndexOutOfBounds exception.
Try using:
public class DrawGrid extends View{
private int[] binary;
private int sq00c;
etc....
public DrawGrid(Context context) {
super(context);
}
public DrawGrid(Context context, int[] inBinary) {
super(context);
binary = inBinary;
sq00c = binary[0];
...etc
}
}
I've split the int declaration and the assignment into two. The ints are still declared at the class level, but are only given a value when the constructor is called.
By seeing the exception seems like this is your problem
Clone() create a shallow copy check this link
I think following modification will solve your problem
public DrawGrid(Context context, int[] inBinary) {
super(context);
binary = inBinary; //update to this
}

Android Test Case non Activity class

I have a problem to test my non activity-class which need the context of a activity class.
The class Card extends ImageView and have a few methods:
public class Card extends ImageView {
public Card(Context context, int cardID) {
super(context);
this.cardID = cardID;
this.turnback = 0;
backImage = getResources().getDrawable(R.drawable.backimage);
setBackgroundDrawable(backImage);
}
}
I would like to test this class as a standalone class, is there an opportunity to create an Dummy Context?
The simple answer is no. The reason being that you are extending a view. The only way to test a view is to view it. To do that you need an activity. This is android fundamentals.

Categories

Resources