Access assets files from another class - android

Sorry for my English. I have a class named Server and I need to read URL from a file in my applications assets but AssetManager android studio says it cannot be accessed from outside package and getassets() don't work neither. How can I access assets from not activity class?

How can I access assets from not activity class
To access assets you need Context. So pass one to your class (via constructor or other way) or just pass your URL if that's all you need from your assets

Non Activity Class
public CustomClass(Context myContext) {
AssetManager mngr = myContext.getAssets();
InputStream is = mngr.open("text.txt"); // get text file
try {
InputStream bitmap = myContext.getAssets().open("imagename.png");// get iamge file
Bitmap bit = BitmapFactory.decodeStream(bitmap);
//imgview.setImageBitmap(bit);
}
catch (IOException e1) {
e1.printStackTrace();
}
}
Call the class like as
CustomClass(getApplicationContext()) ; //activity
CustomClass(getActivity().getApplicationContext()); //fragment

I think getAssets only works within Activity Class. One of the ways to apply it in ordinary class is by creating constructor with Context parameter the reference getAssets within the constructor.
public DataFile(Context DataContext){
try {
AssetManager am = DataContext.getAssets();// If this line gives you ERROR then try AssetManager am=getActivity().getAssets();
InputStream mInpuStream = am.open("Question.xls");
Workbook mWorkBook = jxl.Workbook.getWorkbook(mInpuStream);
Sheet mSheet = mWorkBook.getSheet(0);
int mRow = mSheet.getRows();
int mCol = mSheet.getColumns();
String mContent = "";
for (int i = 0; i < mRow; i++) {
for (int c = 0; c < mCol; c++) {
Cell mCell = mSheet.getCell(c, i);
mContent = mContent + mCell.getContents();
}
mContent = mContent + "\n";
}
display(mContent);
} catch (Exception e) {
}
}

Related

How to use getClassLoader() correctly?

Here I try to use getClassLoader().getResources() to get my .model file, however it returns null. I'm not sure where goes wrong!
And when I try to print out the urls, it gives me java.lang.TwoEnumerationsInOne#5fd1900, what does this means?
public Activity(MainActivity activity) {
MainActivity activity = new MainActivity();
try {
// Open stream to read trained model from file
InputStream is = null;
// this .model file is save under my /project/app/src/main/res/
Enumeration<URL> urls = Activity.class.getClassLoader().getResources("file.model");
// System.out.println("url:"+urls);
if (urls.hasMoreElements()) {
URL element = urls.nextElement();
is = element.openStream();
}
// deserialize the model
classifier = (J48) SerializationHelper.read(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
In Android, resources put under src/main/res are not visible in the class path and can only be accessed via the android resources API. Try to put the file into src/main/resources.

Eclipse Android config file always returns null

Currently in the process of creating a testing framework for Android via Eclipse and JUnit. The last thing I'm implementing is a Configuration file and reader so that the config file can be used to change various properties when necessary. The structure of my framework is as follows:
MainFramework (project)
Base package
Utility package
Config class
Testing (project)
examples package
Artist testing class
The Config class is as follows:
public class Config {
private static Config instance;
public Context context;
public static Properties prop;
public static StorefrontConfig getInstance(Context context) {
if(instance == null)
instance = new StorefrontConfig(context);
return instance;
}
protected StorefrontConfig(Context cont) {
context = cont;
AssetManager manager = context.getAssets();
try {
InputStream instream = manager.open("config");
readConfig(instream);
}
catch (Exception e) {
Log.d("cool", "Failed to create properly initialized config class");
}
}
private static void readConfig(InputStream instream) {
try {
String line = "";
BufferedReader read = new BufferedReader(new InputStreamReader(instream));
while ((line = read.readLine()) != null) {
String[] split_line = line.split("=", 2);
prop.setProperty(split_line[0], split_line[1]);
}
prop.store(new FileOutputStream("config.properties"), "Default and local config files");
read.close();
}
catch (Exception e) {
Log.d("cool", "Failed to create properly initialized config class");
}
}
public String getProperty (String propertyKey) {
try {
return prop.getProperty(propertyKey);
}
catch (Exception e) {
Log.d("cool", "Failed to access property");
return null;
}
}
public Context getContext () {
return context;
}
When I call the getProperty() method in my code, it always returns null. However, I have no idea if it is failing to initially read and write the values or what is going on. All I know is that my program works with hard-coded values but not when using this class and referencing it via config.getProperty() in the code where needed (my main framework has a Config class that is inherited by all the tests).
Any help would be really appreciated. Only thing I can think of is that Java's Properties class cannot be used with Android?
Java's Properties can be used with Android.
It looks like you aren't instantiating prop, which probably results in a NullPointerException when you call prop.getProperty(propertyKey). At some point you need to instantiate prop with prop = new Properties();. Check out these examples. Number 2 will probably make your life easier, as you don't need to manually parse the properties file like you do in readConfig().

android testing accessing json file

I implemented a JSON interface for getting model data over http in one of my android projects.
this works so far and I would like to write some tests. I created a test project as suggested in the android documentation. for testing the JSON interface I need some test data which I would like to put in a file.
my research showed up that it's best to put these files in the assets folder of the android test project. to access files in the assets folder one should extend the test class by InstrumentationTestCase. then it should be possible to access the files by calling getAssets().open() on a resources object. so I came up with the following code:
public class ModelTest extends InstrumentationTestCase {
public void testModel() throws Exception {
String fileName = "models.json";
Resources res = getInstrumentation().getContext().getResources();
InputStream in = res.getAssets().open(fileName);
...
}
}
unfortunately I'm getting an "no such file or directory (2)" error when trying to access "models.json" file. (/assets/models.json)
when getting a list of the available files by
String[] list = res.getAssets().list("");
"models.json" is listed in there.
I'm running these tests on Android 4.2.2 api level 17.
public static String readFileFromAssets(String fileName, Context c) {
try {
InputStream is = c.getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
return text;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Then use the following code:
JSONObject json = new JSONObject(Util.readFileFromAssets("abc.txt", getApplicationContext()));
please use below code:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("foo.txt");
if ( inputStream != null)
Log.d(TAG, "It worked!");
} catch (IOException e) {
e.printStackTrace();
}

FileNotFoundException when trying to read xls in android

I'm trying to read excel contents in android, but always get file not found exception
The project is in:
C:\AndroidWorkSpace\AntenaProject
And the code is:
public void TestClick(View view)
{
File inputWorkbook = new File("shidur.xls");
Workbook w;
StringBuilder sb = new StringBuilder("starting");
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
//CellType type = cell.getType();
sb.append(cell.getContents());
}
}
} catch (Exception e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.testText);
tv.setText(sb.toString());
}
i tried to put shidur.xls in the following folders:
C:\AndroidWorkSpace\AntenaProject\res\raw
C:\AndroidWorkSpace\AntenaProject\res
but still getting this exception.
i'm using jxl.jar from http://jexcelapi.sourceforge.net/
thanks for the help
The path that you provide to the File constructor needs to be the absolute path of the file, or you need to use the overload that takes another File object as the first parameter which represents the directory the file lives in.
That being said, constructing a file in this way is for files that are either in local storage (ie. phone's main memory) or external storage (ie. SD card).
To open a file from the res/raw directory, get an InputStream in the following way
InputStream in = getResources().openRawResource(R.raw.file_name);
Then, you will need code that reads the contents of your input stream. I use a static helper method that looks like this, but this could run you into problems if the file is huge. Hasn't happened to me yet, but in principle that's always a risk when loading the entire content of a file into memory
public static String readStream(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch(Exception ex) { }
finally
{
// NOTE: you don't have my IOUtils class,
// but all these methods do is check for null and catch the exceptions that Closeable.close() can throw
IOUtils.safeClose(in);
IOUtils.safeClose(reader);
}
return sb.toString();
}
You should use the following code to open file in the /res/raw
getResources().openRawResource(R.raw.shidur.xls)

Retrieving all Drawable resources from Resources object

In my Android project, I want to loop through the entire collection of Drawable resources. Normally, you can only retrieve a specific resource via its ID using something like:
InputStream is = Resources.getSystem().openRawResource(resourceId)
However, I want to get all Drawable resources where I won't know their ID's beforehand. Is there a collection I can loop through or perhaps a way to get the list of resource ID's given the resources in my project?
Or, is there a way for me in Java to extract all property values from the R.drawable static class?
Okay, this feels a bit hack-ish, but this is what I came up with via Reflection. (Note that resources is an instance of class android.content.res.Resources.)
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i = 0, max = fields.length; i < max; i++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableResources);
} catch (Exception e) {
continue;
}
/* make use of resourceId for accessing Drawables here */
}
If anyone has a better solution that makes better use of Android calls I might not be aware of, I'd definitely like to see them!
i used getResources().getIdentifier to scan through sequentially named images in my resource folders. to be on a safe side, I decided to cache image ids when activity is created first time:
private void getImagesIdentifiers() {
int resID=0;
int imgnum=1;
images = new ArrayList<Integer>();
do {
resID=getResources().getIdentifier("img_"+imgnum, "drawable", "InsertappPackageNameHere");
if (resID!=0)
images.add(resID);
imgnum++;
}
while (resID!=0);
imageMaxNumber=images.size();
}
I have taken Matt Huggins great answer and refactored it to make it more generic:
public static void loadDrawables(Class<?> clz){
final Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
final int drawableId;
try {
drawableId = field.getInt(clz);
} catch (Exception e) {
continue;
}
/* make use of drawableId for accessing Drawables here */
}
}
Usage:
loadDrawables(R.drawable.class);
You should use the Raw folder and AssetManager, but if you want to use drawables because why not, here is how...
Let's suppose we have a very long file list of JPG drawables and we want to get all the resource ids without the pain of retrieving one by one (R.drawable.pic1, R.drawable.pic2, ... etc)
//first we create an array list to hold all the resources ids
ArrayList<Integer> imageListId = new ArrayList<Integer>();
//we iterate through all the items in the drawable folder
Field[] drawables = R.drawable.class.getFields();
for (Field f : drawables) {
//if the drawable name contains "pic" in the filename...
if (f.getName().contains("image"))
imageListId.add(getResources().getIdentifier(f.getName(), "drawable", getPackageName()));
}
//now the ArrayList "imageListId" holds all ours image resource ids
for (int imgResourceId : imageListId) {
//do whatever you want here
}
Add a picture named aaaa and another named zzzz, then iterate through the following:
public static void loadDrawables() {
for(long identifier = (R.drawable.aaaa + 1);
identifier <= (R.drawable.zzzz - 1);
identifier++) {
String name = getResources().getResourceEntryName(identifier);
//name is the file name without the extension, indentifier is the resource ID
}
}
This worked for me.
If you find yourself wanting to do this you're probably misusing the resource system. Take a look at assets and AssetManager if you want to iterate over files included in your .apk.
I guess the reflection code will work but I don't understand why you need this.
Resources in Android are static once the application is installed so you can have a list of resources or an array. Something like:
<string-array name="drawables_list">
<item>drawable1</item>
<item>drawable2</item>
<item>drawable3</item>
</string-array>
And from your Activity you can get it by doing:
getResources().getStringArray(R.array.drawables_list);
Just do this:
Field[] declaredFields = (R.drawable.class).getDeclaredFields();
The OP wanted drawables and I needed layouts. This is what I came up with for layouts. The name.startsWith business lets me ignore system generated layouts, so you may need to tweak that a bit. This should work for any resource type by modifying the value of clz.
public static Map<String,Integer> loadLayouts(){
final Class<?> clz = R.layout.class;
Map<String,Integer> layouts = new HashMap<>();
final Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
if (
!name.startsWith("abc_")
&& !name.startsWith("design_")
&& !name.startsWith("notification_")
&& !name.startsWith("select_dialog_")
&& !name.startsWith("support_")
) {
try {
layouts.put(field.getName(), field.getInt(clz));
} catch (Exception e) {
continue;
}
}
}
return layouts;
}
USE THIS MY CODE
R.drawable drawableResources = new R.drawable();
Class<R.drawable> c = R.drawable.class;
Field[] fields = c.getDeclaredFields();
for (int i = 0, max = fields.length; i < max; i++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableResources);
// call save with param of resourceId
SaveImage(resourceId);
} catch (Exception e) {
continue;
}
}
...
public void SaveImage(int resId){
if (!CheckExternalStorage()) {
return;
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resID);
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(path, "image1.png");
file.createNewFile();
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
Log.i(LOGTAG, "Image Written to Exterbal Storage");
} catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
}
}
To create an array of drawables in Kotlin:
val drawablesFields: Array<Field> = drawable::class.java.fields
val drawables: ArrayList<Drawable> = ArrayList()
for (field in drawablesFields) {
context?.let { ContextCompat.getDrawable(it, field.getInt(null)) }?.let {
drawables.add (
it
)
}
}

Categories

Resources