I am working on android automation test, I create a test project in eclipse. (In automation, it will be packed as apk and deploy onto emulator) And In my project, I want to read a xml file in assets folder. I put my xml file "mytest.xml" directly in the folder assets. And I want to load it and parse. But it seems I will always get NullPointerException. Below is my code
1.the function is defined in a class OSNCommonLib.
public class OSNCommonLib extends Activity {
public String readTranslationFile(String fileName,String transunitId)
{
if(doc == null)
{
try
{
InputStream in = getAssets().open(fileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(in);
}
catch ( Exception e )
{
System.out.println("mytest catch" + e.toString() );
e.printStackTrace();
}
}
org.w3c.dom.Element root = doc.getDocumentElement();
NodeList nodes = root.getElementsByTagName( "trans-unit" );
.......
}
....
}
And the function above will be called in another java class
public class TC01_OSNdemo extends ActivityInstrumentationTestCase2 {
OSNCommonLib ocl = new OSNCommonLib();
...
public void testSortByButton(){
....
String getstr = ocl.readTranslationFile("mytest","osn_menu_sortby");
Assert.assertTrue(solo.searchText(getstr));
...
}
And in the catch, I will always get java.lang.NullPointerException. Does it means it can't load my file? I tried many times and still the same errors.
Can anyone give some suggestions about this issue?
Besides: here is the full log
java.lang.NullPointerException
at com.stg.osn.lib.OSNCommonLib.readTranslationFile(OSNCommonLib.java:107) --> **point to org.w3c.dom.Element root = doc.getDocumentElement();**
at com.sgt.osn.junit.test.TC01_OSNdemo.testSortByButton(TC01_OSNdemo.java:142)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)
At last, the problem is sovled. As I extend my test case on Instruments, I should use the below method to call: InputStream in = getInstrumentation().getContext().getAssets().open("mytest.xml"); The useful link http://developer.android.com/reference/android/test/InstrumentationTestCase.html http://www.mail-archive.com/[email protected]/msg62671.html
Thanks to all!!!
You can try this..