1

I have 2 classes, from class BinderData, which extends BaseAdapter (I can't extend this class to Activity as I have to extend to BaseAdapter) I am calling class AssetActivity by following code:

AssetActivity a = new AssetActivity(); Drawable image=a.getImage(imageUri); 

Here imageuri is a string and it is populated properly.In the AssetActivity class following code I am using.

public class AssetActivity extends Activity { private static final String TAG = "AssetActivity"; public Drawable getImage(String imgName) { String nextImageName = imgName+ ".jpg"; AssetManager assets = getAssets(); // get app's AssetManager InputStream stream; // used to read in Image images Drawable flag=null; try { // get an InputStream to the asset representing the next Image stream = assets.open(nextImageName ); // load the asset as a Drawable and display on the objImageView flag = Drawable.createFromStream(stream, nextImageName); } // end try catch (IOException e) { Log.e(TAG, "Error loading " + nextImageName, e); } // end catch return flag; } } 

When I am running the code I am getting NullPointerException at following line.

AssetManager assets = getAssets(); 

There are assets at the asset folder and I am able to fetch them in some other class which explicitly calls getAssets() method and that class extends Activity. Please help me with this. I am suspecting that I am doing something wrong in calling getImage method in BinderData class. Please help me. Thanks.

1 Answer 1

5

AssetManager assets = getAssets(); will give you NullPointerException because getAssets() will return null. getAssets() needs to be called in the Activity Context;

You are not allowed to create Object for the class android will take care of that through life cycle methods. So don't create Object for Activity.

place that method in your Activity class use context.getAssets() to get the Assets

Sign up to request clarification or add additional context in comments.

7 Comments

Thnx but can u please elaborate more as I am new to Android and Java.
@Sid ok..What else do you want to know? Simply place that method in your current Activity it self and call it directly. use context.getAssets() in place of getAssets()
I can't place the method in my main class as it's not an activity it's a BaseAdapter. I didn't understand context.getAssets() and how to use it. Shall I use it in Activity class?
if it is based Adapter, you'll need supply context in the constructor of your CustomAdapter. And using that context you can get the assets
ok I tried what you said. But still I m getting same error. private static Context appContext; @Override public void onCreate() { super.onCreate(); appContext = this; } public static Context getContext() { return appContext; } then I am using AssetManager assets = appContext.getAssets();
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.