Failed to call a dynamic method in a static contex

2019-09-11 05:36发布

问题:

These are created using Android Studio similar to How to modify dummy content in android master/detail activity?. I changed the static method under dummyContent into below:

public void fetchData() {
    // Add some sample items.
    for (int i = 1; i <= COUNT; i++) {
        addItem(createDummyItem(i));
    }

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    DummyContent.UNAME, DummyContent.PASSWORD.toCharArray());
        }
    });

    try {
        DummyContentRegistry registry = new XMLDummyContentParser(DummyContent.url).parse();
        for (DummyContent.DummyItem t: registry.getTeachers()) {
            DummyContent.addItem(t);
        }
    } catch (Exception e) {
        fail("Exception should not have been thrown");
    }
}

while above passed the test:

public class DummyContentRegistryTest {
    @Before
    public void buildRegistry() {}

    @Test
    public void testFetchData() {
        Assert.assertEquals(0,DummyContent.ITEMS.size());
        new DummyContent().fetchData();
        Assert.assertEquals(27,DummyContent.ITEMS.size());// two more items are added through parsing xml on a website
    }

}

However when I call the method under MainActivity.onCreate it failed "Exception should not have been thrown". Why? Here's an example of failing call

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (DummyContent.ITEMS.isEmpty()) {
        new DummyContent().fetchData();
    }
......
}

I don't know if the problem is similar to calling non-static method in static method in Java but I've obviously tried the way most of them agreed.

    [ 07-25 04:04:56.442 23983:24025 D/         ]
                                                                                    HostConnection::get() New Host Connection established 0x7f1b57910500, tid 24025
07-25 04:04:56.460 23983-24025/*****private*****.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
07-25 04:04:56.873 23983-23983/*****private*****.myapplication I/Choreographer: Skipped 32 frames!  The application may be doing too much work on its main thread.
07-25 04:05:07.474 23983-23983/*****private*****.myapplication W/System.err: java.io.IOException: Couldn't open *****private*****
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.dummy.XMLDummyContentParser.parse(XMLDummyContentParser.java:33)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.dummy.DummyContent.fetchData(DummyContent.java:53)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:52)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.Activity.performCreate(Activity.java:6237)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: Caused by: android.os.NetworkOnMainThreadException
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:    ... 18 more
07-25 04:05:07.483 23983-23983/*****private*****.myapplication D/AndroidRuntime: Shutting down VM


07-25 04:05:07.484 23983-23983/*****private*****.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: ******private*******, PID: 23983
                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{******private*******.myapplication.MainActivity}: java.lang.IllegalStateException: Already attached
                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                        at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                     Caused by: java.lang.IllegalStateException: Already attached
                                                                                        at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2126)
                                                                                        at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
                                                                                        at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:313)
                                                                                        at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
                                                                                        at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:55)
                                                                                        at android.app.Activity.performCreate(Activity.java:6237)
                                                                                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                                        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                        at android.os.Looper.loop(Looper.java:148) 
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

 

回答1:

The Exception e, which you catch may contain useful information on what exactly went wrong. Do e.printStackTrace(); inside your catch-block to print all available information to the standard output. If that does not help you solve the problem post the stacktrace here.



回答2:

You cannot manipulate UI thread from background thread thats why you are getting this error.

ClassName.this.runOnUiThread(new Runnable() {
                public void run() {
                //Do something on UiThread

                // enclose your UI manipulated code here in these braces.
            }
        });