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.
Related
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.
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.
Is it possible to write a whole shared_preferences.xml at once?
I want to realize a kind of settings import/export, so i need to read and write the whole file without loosing the xml-tags.
Reading the file is easy, but when i write my values (using PrintWriter) the old values stored in memory overwrite them seconds later.
what can i do to prevent that without writing single values using preference editor.
Now I read it from a file designed like Android's own preferences.xml and write it successively in my own function like this:
public static void preferencesImport(String PreferenceFilepath) {
preferencesImportPreferenceFilepath = PreferenceFilepath;
try {
// Parsing
// see http://theopentutorials.com/tutorials/android/xml/android-simple-xml-dom-parser/
XMLParserHelper parser = new XMLParserHelper(); // reference to described XMLDOMParser helper class
BufferedInputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(preferencesImportPreferenceFilepath));
org.w3c.dom.Document doc = parser.getDocument(stream);
// string value
NodeList nodeListString = doc.getElementsByTagName("string");
for (int i = 0; i < nodeListString.getLength(); i++) {
Element eString = (Element) nodeListString.item(i);
Pref.setString(eString.getAttribute("name"), eString.getTextContent()); // Own getter/setter -> use Android's preference manager instead in similar way
}
// repeat code above for boolean, long, int, float values
stream.close();
} catch (IOException e1) {
// output IOException
} catch (Throwable t1) {
// output Throwable1
}
writer.close();
} catch (Throwable t2) {
// output Throwable2
}
}
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();
}
I'm trying to write a json file using android like this:
String jsonString = broadcastDataArray.toString();
Writer output = null;
File fileAnnouncement = new File("announcement.json");
try {
output = new BufferedWriter(new FileWriter(fileAnnouncement));
output.write(jsonString);
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and now i'm trying to load/read the file using phonegap. Using this method shown here, i am able to read a file that was included in my application source. But i want to read some file that was generated by the android code.
Is there anyway to do this? Is there any specific directory where the file could be accessed from Java android and Phonegap/Sencha ?
Any kind of help or pointer is appreciated. Thanks.
You can do this in following way.
Write this function in your Android activity to write data in text file.
public void WriteDataToFile(String sFileName, String sBody){
try
{
FileWriter f = new FileWriter("/sdcard/data.txt");
f.append(sBody);
f.flush();
f.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
And, now you can read that file from your Sencha/Phonegap app by calling this function.
var user_data = function(){
var request = new XMLHttpRequest();
request.open("GET", "/sdcard/data.txt");
request.onreadystatechange = function() {
if (request.readyState == 4) {
// alert("*" + request.responseText + "*");
data = request.responseText;
}
}
request.send();
}