How to start Activity from Fragment? Android

泪湿孤枕 提交于 2019-12-25 02:37:07

问题


I am new to Android apps development. I use this open source sliding menu with fragments: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

I want to implement this rss feed parser (AndroidRssReader, also open source) in sliding menu project: http://android-er.blogspot.in/2010/04/simple-rss-reader-using-androids.html

My idea is, that one of the sliding menu items (one fragment), starting an AndroidRssReader.java activity. I was put AndroidRssReader.java file in my /src/stiw47.logos and want to call em from RssFragment.java. Here is my source code of RssFragment.java:

public class RssFragment extends Fragment {

    public RssFragment (){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_rss, container, false);

        Button newPage = (Button)v.findViewById(R.id.bNovosti);
        newPage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AndroidRssReader.class);
                startActivity(intent);
            }
        });
        return v;
    }
}

When I click a button to call AndroidRssReader class, I got a force close.

Here is my adb logcat:

    I/ActivityManager(13216): Timeline: Activity_launch_request id:stiw47.logos time:7317484
    V/AudioPolicyManagerBase( 1678): getOutput() stream 1, samplingRate 0, format0,         channelMask 3, flags 0
V/AudioPolicyManagerBase( 1678): getOutput() returns output 2
V/audio_policy_anm( 1678): audio_io_handle_t android::ap_get_output(audio_policy*, audio_stream_type_t, uint32_t, audio_format_t, uint32_t, audio_output_flags_t): tid 1678
V/AudioPolicyManagerBase( 1678): getOutput() stream 1, samplingRate 0, format 0, channelMask 3, flags 0
V/AudioPolicyManagerBase( 1678): getOutput() returns output 2
V/audio_policy_anm( 1678): audio_io_handle_t android::ap_get_output(audio_policy*, audio_stream_type_t, uint32_t, audio_format_t, uint32_t, audio_output_flags_t): tid 2371
V/AudioPolicyManagerBase( 1678): getOutput() stream 1, samplingRate 48000, format 1, channelMask 3, flags 4
V/AudioPolicyManagerBase( 1678): getOutput() returns output 2
W/AudioTrack( 2143): AUDIO_OUTPUT_FLAG_FAST denied by client due to mismatching sample rate (48000 vs 44100)
I/ActivityManager( 2143): START u0 {cmp=stiw47.logos/.AndroidRssReader} from pid 13216
V/AudioPolicyManagerBase( 1678): startOutput() output 2, stream 1, session 62
V/AudioPolicyManagerBase( 1678): changeRefCount() stream 1, count 1
V/AudioPolicyManagerBase( 1678): getNewDevice() selected device 2
V/AudioPolicyManagerBase( 1678): setOutputDevice() output 2 device 0002 force 0 delayMs 0 
V/AudioPolicyManagerBase( 1678): setOutputDevice() prevDevice 0002
V/AudioPolicyManagerBase( 1678): setOutputDevice() setting same device 0002 or null device for output 2
V/AudioPolicyManagerBase( 1678): releaseOutput() 2
D/AndroidRuntime(13216): Shutting down VM
W/dalvikvm(13216): threadid=1: thread exiting with uncaught exception (group=0x41febce0)
E/AndroidRuntime(13216): FATAL EXCEPTION: main
E/AndroidRuntime(13216): Process: stiw47.logos, PID: 13216
E/AndroidRuntime(13216): java.lang.RuntimeException: Unable to start activity ComponentInfo{stiw47.logos/stiw47.logos.AndroidRssReader}: android.os.NetworkOnMainThreadException
E/AndroidRuntime(13216):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
E/AndroidRuntime(13216):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
E/AndroidRuntime(13216):    at android.app.ActivityThread.access$800(ActivityThread.java:145)
E/AndroidRuntime(13216):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
E/AndroidRuntime(13216):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(13216):    at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(13216):    at android.app.ActivityThread.main(ActivityThread.java:5081)
E/AndroidRuntime(13216):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13216):    at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(13216):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
E/AndroidRuntime(13216):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
E/AndroidRuntime(13216):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(13216): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(13216):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
E/AndroidRuntime(13216):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(13216):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(13216):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
E/AndroidRuntime(13216):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
E/AndroidRuntime(13216):    at java.net.URL.openStream(URL.java:470)
E/AndroidRuntime(13216):    at stiw47.logos.AndroidRssReader.onCreate(AndroidRssReader.java:41)
E/AndroidRuntime(13216):    at android.app.Activity.performCreate(Activity.java:5231)
E/AndroidRuntime(13216):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(13216):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
E/AndroidRuntime(13216):    ... 11 more
W/ActivityManager( 2143):   Force finishing activity stiw47.logos/.AndroidRssReader
W/ActivityManager( 2143):   Force finishing activity stiw47.logos/.MainActivity

Notice 1: I declair an activity in Manifest and set Internet permission Notice 2: When I compile AndroidRssReader.java class as "standalone" app it's working, but when I try to run AndroidRssReader.java class in "my app" it's crashing.

Where am I mistake?


回答1:


the mistake you made is that you have somewhere in your code ( Exactly in the class AndroidRssReader.java Line 41 ) . You have a Network call or an http request that you are executing in the MainThread ( UIThread ) . you should put that code inside an [AsyncTask][1] .

check this tutorial to see how to use AsyncTask in Android .

EDIT :

the code in the onCreate() method which retreive the xml and parse it should be in AsyncTask like this :

new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {

                String result = "Cannot connect RSS!";
                try {
                      URL rssUrl = new URL("http://feeds.feedburner.com/Android-er?format=xml");
                      SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
                      SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
                      XMLReader myXMLReader = mySAXParser.getXMLReader();
                      RSSHandler myRSSHandler = new RSSHandler();
                      myXMLReader.setContentHandler(myRSSHandler);
                      InputSource myInputSource = new InputSource(rssUrl.openStream());
                      myXMLReader.parse(myInputSource);

                      result = streamTitle;

                     } catch (MalformedURLException e) {
                      e.printStackTrace();
                     } catch (ParserConfigurationException e) {
                      e.printStackTrace();
                     } catch (SAXException e) {
                      e.printStackTrace();
                     } catch (IOException e) {
                      e.printStackTrace();
                     }
                return result;
            }

            @Override
            protected void onPostExecute(String response) {
                if(response != null) {
                    result.setText(response);
                }
            }
        }.execute();



回答2:


The most important line is this one:

E/AndroidRuntime(13216): java.lang.RuntimeException: Unable to start activity ComponentInfo{stiw47.logos/stiw47.logos.AndroidRssReader}: android.os.NetworkOnMainThreadException

The problem is not with starting your Activity, the problem is that this Activity is performing a network operation within the main UI thread. Android forbids that, because doing so you are not allowing the user interact with your app, resulting in a ANR (which will make the user experience very poor and they probably won't use your app anymore).

Simply put the network code within an AsyncTask. For more info have a look here.



来源:https://stackoverflow.com/questions/22467759/how-to-start-activity-from-fragment-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!