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().
Related
I have a simple .txt file with just a couple lines in right now, each line has a word then a comma then another word, representing a very simplistic username , password bank. For some reason though I cant get the File to open to read from it.
Here is my code that I'm using....
try {
final String PATH = "src\\main\\assets\\passwords.txt";
Log.w("myApp", "passed");
List<String> user_password = FileUtils.readLines(new File(PATH));
Log.w("myApp", "passed2");
#SuppressWarnings("unchecked") List<Credentials> credentials = (List<Credentials>) CollectionUtils.collect(user_password, new Transformer() {
#Override
public Object transform(Object input) {
String cred = (String) input;
String parsed[] = cred.split(",");
Log.w("myApp", parsed[0]);
return new Credentials(parsed[0], parsed[1]);
//return credential;
}
});
user = (Credentials) CollectionUtils.find(credentials, new Predicate() {
#Override
public boolean evaluate(Object object) {
Credentials c = (Credentials) object;
return c.getUserName().equals(userName);
}
});
} catch (IOException e) {
System.out.print(e);
Log.w("MyApp", "failed");
}
I've tried putting the passwords.txt file in different places but that doesn't seem to work either.
You're referencing wrong to file in assets folder. It has to be smth like:
file:///android_asset/myfoldername/myfilename
in your particular case it's file:///android_asset/passwords.txt, though you have to keep in mind that it's always read only file
final String PATH = "src\\main\\assets\\passwords.txt";
That's not going to work. Android is not Windows, and an Android device is not your Windows development PC.
First, \ is the Windows path separator. On OS X, Linux, and Android, the path separator is /.
Second, src\main\assets\passwords.txt is a file in your project. It is not a file on the filesystem of the Android device.
To access assets, use AssetManager to open an InputStream(). You can get an AssetManager by calling getAssets() on any handy Context, such as your activity. Then, for your asset, call open("passwords.txt") on the AssetManager to get the InputStream, that you can then use to read in the data.
Thanks to #CommonsWare I was able to achieve what I was trying to do by using InputStream and then also IOUtils to read everything into the List.
try {
InputStream iS = this.getAssets().open("passwords.txt");
List<String> user_password = IOUtils.readLines(iS);
#SuppressWarnings("unchecked") List<Credentials> credentials = (List<Credentials>) CollectionUtils.collect(user_password, new Transformer() {
#Override
public Object transform(Object input) {
String cred = (String) input;
String parsed[] = cred.split(",");
return new Credentials(parsed[0], parsed[1]);
}
});
user = (Credentials) CollectionUtils.find(credentials, new Predicate() {
#Override
public boolean evaluate(Object object) {
Credentials c = (Credentials) object;
return c.getUserName().equals(userName);
}
});
}catch (IOException e){
System.out.print(e);
}
JUnitTest/Mockito/PowerMockito :: Trying to access dataSet json file from res/raw file in android, But getting "InvocationTargetException"
InputStream in = this.getClass().getClassLoader().getResourceAsStream("resource.json");
try {
Reader reader = new InputStreamReader(in, "UTF-8");
ConfigModel result = new Gson().fromJson(reader, ConfigModel.class);
} catch (IOException e) {
e.printStackTrace();
}
EDIT: updated version.
If you using Android instrumentation test then you can get the context and you can do something like this,
#Test
public void someTest() {
// Context of the app under test.
// In this case put your resource in your app's assets folder src/main/assets
Context appContext = InstrumentationRegistry.getTargetContext();
/ **
* Context of the test app.
* In this case put your resource in your test app's assets folder src/androidTests/assets
* Context appContext = InstrumentationRegistry.getContext();
**/
InputStream in = null;
try {
in = appContext.getAssets().open("resource.json");
} catch (IOException e) {
e.printStackTrace();
}
}
If you do not want to go into Android way of testing, simple way is to have your resource.json under src/test/resources folder and then your above code would work. Something like this.
#Test
public void test() {
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream res = classLoader.getResourceAsStream("testFlags.json");
}
I did some testing around these and I can say they are working fine. Let me know how it goes.
I have a simple .txt file with just a couple lines in right now, each line has a word then a comma then another word, representing a very simplistic username , password bank. For some reason though I cant get the File to open to read from it.
Here is my code that I'm using....
try {
final String PATH = "src\\main\\assets\\passwords.txt";
Log.w("myApp", "passed");
List<String> user_password = FileUtils.readLines(new File(PATH));
Log.w("myApp", "passed2");
#SuppressWarnings("unchecked") List<Credentials> credentials = (List<Credentials>) CollectionUtils.collect(user_password, new Transformer() {
#Override
public Object transform(Object input) {
String cred = (String) input;
String parsed[] = cred.split(",");
Log.w("myApp", parsed[0]);
return new Credentials(parsed[0], parsed[1]);
//return credential;
}
});
user = (Credentials) CollectionUtils.find(credentials, new Predicate() {
#Override
public boolean evaluate(Object object) {
Credentials c = (Credentials) object;
return c.getUserName().equals(userName);
}
});
} catch (IOException e) {
System.out.print(e);
Log.w("MyApp", "failed");
}
I've tried putting the passwords.txt file in different places but that doesn't seem to work either.
You're referencing wrong to file in assets folder. It has to be smth like:
file:///android_asset/myfoldername/myfilename
in your particular case it's file:///android_asset/passwords.txt, though you have to keep in mind that it's always read only file
final String PATH = "src\\main\\assets\\passwords.txt";
That's not going to work. Android is not Windows, and an Android device is not your Windows development PC.
First, \ is the Windows path separator. On OS X, Linux, and Android, the path separator is /.
Second, src\main\assets\passwords.txt is a file in your project. It is not a file on the filesystem of the Android device.
To access assets, use AssetManager to open an InputStream(). You can get an AssetManager by calling getAssets() on any handy Context, such as your activity. Then, for your asset, call open("passwords.txt") on the AssetManager to get the InputStream, that you can then use to read in the data.
Thanks to #CommonsWare I was able to achieve what I was trying to do by using InputStream and then also IOUtils to read everything into the List.
try {
InputStream iS = this.getAssets().open("passwords.txt");
List<String> user_password = IOUtils.readLines(iS);
#SuppressWarnings("unchecked") List<Credentials> credentials = (List<Credentials>) CollectionUtils.collect(user_password, new Transformer() {
#Override
public Object transform(Object input) {
String cred = (String) input;
String parsed[] = cred.split(",");
return new Credentials(parsed[0], parsed[1]);
}
});
user = (Credentials) CollectionUtils.find(credentials, new Predicate() {
#Override
public boolean evaluate(Object object) {
Credentials c = (Credentials) object;
return c.getUserName().equals(userName);
}
});
}catch (IOException e){
System.out.print(e);
}
Hi Iam having serious issues try to persist some serializable objects to a file on the local android file system. Iam getting a Bad file descriptor error and I think it is to do with my methods for creating the file. the file and checking if the file exists. i create a private file object in the class. Then, on write or read. I check file existance with the following code.
#Override
public boolean fileExists() {
File file = context.getFileStreamPath(filename);
return file.exists();
}
this doesnt instantiate my file object called "objectfile"!! but does check the "filename" exists.
to create the file I call this method if "filename" doesnt exist.
public void createFile()
{
objectfile = new File(context.getFilesDir(), filename);
objectfile.setReadable(true);
objectfile.setWritable(true);
}
Iam not sure if this will give me back my previously created file which would be ideally what I want to do. Is there a way i can just get the old file or create a new one and pass it to "objectfile" variable in the constructor??
Iam also wondering what the best way to do this is??
Or should i just use the mysqlite db? using object file persistance doesn't seem to be working out for me right now and iam working to a deadline. Also this method is mention in the gooogle docs so I thought it would be legit was to do it.
http://developer.android.com/training/basics/data-storage/files.html
here is my method for reading the serializable objects
public synchronized ArrayList<RoomItem> readObjects() {
final ArrayList<RoomItem> readlist = new ArrayList<>();
if(!fileExists())
return readlist;
if(objectfile == null)
createFile();
try {
finputstream = new FileInputStream(objectfile);
instream = new ObjectInputStream(finputstream);
readwritethread = new Thread(new Runnable() {
#Override
public void run() {
try {
final ArrayList<RoomItem> readitems = (ArrayList<RoomItem>) instream.readObject();
instream.close();
finputstream.close();
handler.post(new Runnable() {
#Override
public void run() {
listener.updateList(readitems);
}
});
} catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
Log.d("read failed", "file read failed");
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
timeOutReadWrite(readwritethread);
readwritethread.start();
try {
readwritethread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("read from file", "file read");
return readlist;
if anyone could suggest any improvements id really appreciate it. I use a handler to pass back to my activity and implement a listener interface on my activity thats call the activity when all the obj are read. Thanks again!
1#: Yes, it will return the original file you created.
2#: Depends on the thing you want to store, seems File is more flex from description
hope helpful.
We have used
FileOutputStream fos = context.openFileOutput("file.ser", Context.MODE_PRIVATE);
to write our serialized files.This will carete files in /data/data/app.package.name/files/. In fact, this path is returned by getFilesDir().
And while deserializing, use
//make sure you pass the same file that was passed to openFileOutput()..
FileInputStream fis = context.openFileInput("file.ser");
Also, to avoid confusing between file names you can use name of class that is being serialized.
Ex:
public static <T> void serialize(final Context context, final T objectToSerialize) {
....
....
Strin fileName = objectToSerialize.getClass().getSimpleName();
...
}
Do this and keep the method in util so it can be used for any type of objects (T type) to serialize.
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();
}