Fragments med rss-läsare

Discussion in 'Frågor, support och diskussion' started by Lovera, Feb 1, 2013.

  1. Lovera

    Lovera Baby Droid Medlem

    Joined:
    Dec 17, 2010
    Messages:
    17
    Likes Received:
    4

    MINA ENHETER

    Hej!

    Jag har gjort en app med fragment där jag vill att en av flikarna ska hämta rss-inlägg från en hemsida. Några tips på hur jag går tillväga?

    Här är min MainActivity:

    Code:
    
    import java.util.ArrayList;
     
    import android.app.ActionBar;
    import android.app.ActionBar.Tab;
    import android.app.FragmentTransaction;
    import android.content.Context;
    import android.os.Bundle;
     
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
     
    public class MainActivity extends FragmentActivity {
     
     ViewPager ViewPager;
     TabsAdapter TabsAdapter;
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
     
            //create a new ViewPager and set to the pager we have created in Ids.xml
            ViewPager = new ViewPager(this);
            ViewPager.setId(R.id.pager);
            setContentView(ViewPager);
     
            //Create a new Action bar and set title to strings.xml
            final ActionBar bar = getActionBar();
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    
     
            //Attach the Tabs to the fragment classes and set the tab title.
            TabsAdapter = new TabsAdapter(this, ViewPager);
            TabsAdapter.addTab(bar.newTab().setText("Nyheter"),
                    NewsFragment.class, null);
            TabsAdapter.addTab(bar.newTab().setText("Träning"),
              TrainingFragment.class, null);
            TabsAdapter.addTab(bar.newTab().setText("Rutter"),
              RoutesFragment.class, null);
            TabsAdapter.addTab(bar.newTab().setText("Info"),
                    InfoFragment.class, null);
     
            if (savedInstanceState != null) {
                bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
            }
     
        }
     
     @Override
     protected void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
            outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
     
     }
     // create TabsAdapter to create tabs and behavior
     public static class TabsAdapter extends FragmentPagerAdapter
      implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
     
      private final Context mContext;
            private final ActionBar mActionBar;
            private final ViewPager mViewPager;
            private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
     
            static final class TabInfo {
                private final Class<?> clss;
                private final Bundle args;
     
                TabInfo(Class<?> _class, Bundle _args) {
                    clss = _class;
                    args = _args;
                }
            }
     
      public TabsAdapter(FragmentActivity activity, ViewPager pager) {
       super(activity.getSupportFragmentManager());
                mContext = activity;
                mActionBar = activity.getActionBar();
                mViewPager = pager;
                mViewPager.setAdapter(this);
                mViewPager.setOnPageChangeListener(this);
            }
     
      public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
                TabInfo info = new TabInfo(clss, args);
                tab.setTag(info);
                tab.setTabListener(this);
                mTabs.add(info);
                mActionBar.addTab(tab);
                notifyDataSetChanged();
     
            }
     
      @Override
      public void onPageScrollStateChanged(int state) {
       // TODO Auto-generated method stub
     
      }
     
      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
       // TODO Auto-generated method stub
     
      }
     
      @Override
      public void onPageSelected(int position) {
       // TODO Auto-generated method stub
       mActionBar.setSelectedNavigationItem(position);
      }
     
      @Override
      public void onTabReselected(Tab tab, FragmentTransaction ft) {
       // TODO Auto-generated method stub
     
      }
     
      @Override
      public void onTabSelected(Tab tab, FragmentTransaction ft) {
       Object tag = tab.getTag();
                for (int i=0; i<mTabs.size(); i++) {
                    if (mTabs.get(i) == tag) {
                        mViewPager.setCurrentItem(i);
                    }
                }
      }
     
      @Override
      public void onTabUnselected(Tab tab, FragmentTransaction ft) {
       // TODO Auto-generated method stub
     
      }
     
      @Override
      public Fragment getItem(int position) {
       TabInfo info = mTabs.get(position);
                return Fragment.instantiate(mContext, info.clss.getName(), info.args);
      }
     
      @Override
      public int getCount() {
       return mTabs.size();
      }
     
     }
     
    }
    
    Min fragment-class:

    Code:
    	
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    	public class NewsFragment extends Fragment {
    	    @Override
    	    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    	        Bundle savedInstanceState) {
    	        // Inflate the layout for this fragment
    	        return inflater.inflate(R.layout.news_activity, container, false);
    	    }
    	}
    
     
  2. e7andy

    e7andy Professional Droid Hedersmedlem

    Joined:
    Oct 14, 2009
    Messages:
    2 349
    Likes Received:
    835
    Telefon:
    Huawei P10 Plus

    MINA ENHETER

    Telefon:
    Huawei P10 Plus
    Telefon 2:
    Nexus 5
    Telefon 3:
    ADP1
    Övrigt:
    LG G Watch R, ChromeCast
  3. Lovera

    Lovera Baby Droid Medlem

    Joined:
    Dec 17, 2010
    Messages:
    17
    Likes Received:
    4

    MINA ENHETER

    Jag har försökt få in koden från länken e7andy skrev i min NewsFragment men appen krashar när jag kör den. Hur ändrar jag koden till ett fragment?

    Code:
    public class NewsFragment extends Activity {
    	
        public static final String WIFI = "Wi-Fi";
        public static final String ANY = "Any";
        private static final String URL =
                "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";
    
        // Whether there is a Wi-Fi connection.
        private static boolean wifiConnected = false;
        // Whether there is a mobile connection.
        private static boolean mobileConnected = false;
        // Whether the display should be refreshed.
        public static boolean refreshDisplay = true;
    
        // The user's current network preference setting.
        public static String sPref = null;
    
        // The BroadcastReceiver that tracks network connectivity changes.
        private NetworkReceiver receiver = new NetworkReceiver();
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Register BroadcastReceiver to track connection changes.
            IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
            receiver = new NetworkReceiver();
            this.registerReceiver(receiver, filter);
        }
    
        // Refreshes the display if the network connection and the
        // pref settings allow it.
        @Override
        public void onStart() {
            super.onStart();
    
            // Gets the user's network preference settings
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    
            // Retrieves a string value for the preferences. The second parameter
            // is the default value to use if a preference value is not found.
            sPref = sharedPrefs.getString("listPref", "Wi-Fi");
    
            updateConnectedFlags();
    
            // Only loads the page if refreshDisplay is true. Otherwise, keeps previous
            // display. For example, if the user has set "Wi-Fi only" in prefs and the
            // device loses its Wi-Fi connection midway through the user using the app,
            // you don't want to refresh the display--this would force the display of
            // an error page instead of stackoverflow.com content.
            if (refreshDisplay) {
                loadPage();
            }
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            if (receiver != null) {
                this.unregisterReceiver(receiver);
            }
        }
    
        // Checks the network connection and sets the wifiConnected and mobileConnected
        // variables accordingly.
        private void updateConnectedFlags() {
            ConnectivityManager connMgr =
                    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
            NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
            if (activeInfo != null && activeInfo.isConnected()) {
                wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
                mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
            } else {
                wifiConnected = false;
                mobileConnected = false;
            }
        }
    
        // Uses AsyncTask subclass to download the XML feed from stackoverflow.com.
        // This avoids UI lock up. To prevent network operations from
        // causing a delay that results in a poor user experience, always perform
        // network operations on a separate thread from the UI.
        private void loadPage() {
            if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
                    || ((sPref.equals(WIFI)) && (wifiConnected))) {
                // AsyncTask subclass
                new DownloadXmlTask().execute(URL);
            } else {
                showErrorPage();
            }
        }
    
        // Displays an error if the app is unable to load content.
        private void showErrorPage() {
            setContentView(R.layout.main);
    
            // The specified network connection is not available. Displays error message.
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.loadData(getResources().getString(R.string.connection_error),
                    "text/html", null);
        }
    
        // Populates the activity's options menu.
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.mainmenu, menu);
            return true;
        }
    
        // Handles the user's menu selection.
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.settings:
                    Intent settingsActivity = new Intent(getBaseContext(), SettingsActivity.class);
                    startActivity(settingsActivity);
                    return true;
            case R.id.refresh:
                    loadPage();
                    return true;
            default:
                    return super.onOptionsItemSelected(item);
            }
        }
    
        // Implementation of AsyncTask used to download XML feed from stackoverflow.com.
        private class DownloadXmlTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... urls) {
                try {
                    return loadXmlFromNetwork(urls[0]);
                } catch (IOException e) {
                    return getResources().getString(R.string.connection_error);
                } catch (XmlPullParserException e) {
                    return getResources().getString(R.string.xml_error);
                }
            }
    
            @Override
            protected void onPostExecute(String result) {
                setContentView(R.layout.main);
                // Displays the HTML string in the UI via a WebView
                WebView myWebView = (WebView) findViewById(R.id.webview);
                myWebView.loadData(result, "text/html", null);
            }
        }
    
        // Uploads XML from stackoverflow.com, parses it, and combines it with
        // HTML markup. Returns HTML string.
        private String loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
            InputStream stream = null;
            StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
            List<Entry> entries = null;
            String title = null;
            String url = null;
            String summary = null;
            Calendar rightNow = Calendar.getInstance();
            DateFormat formatter = new SimpleDateFormat("MMM dd h:mmaa");
    
            // Checks whether the user set the preference to include summary text
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
            boolean pref = sharedPrefs.getBoolean("summaryPref", false);
    
            StringBuilder htmlString = new StringBuilder();
            htmlString.append("<h3>" + getResources().getString(R.string.page_title) + "</h3>");
            htmlString.append("<em>" + getResources().getString(R.string.updated) + " " +
                    formatter.format(rightNow.getTime()) + "</em>");
    
            try {
                stream = downloadUrl(urlString);
                entries = stackOverflowXmlParser.parse(stream);
            // Makes sure that the InputStream is closed after the app is
            // finished using it.
            } finally {
                if (stream != null) {
                    stream.close();
                }
            }
    
            // StackOverflowXmlParser returns a List (called "entries") of Entry objects.
            // Each Entry object represents a single post in the XML feed.
            // This section processes the entries list to combine each entry with HTML markup.
            // Each entry is displayed in the UI as a link that optionally includes
            // a text summary.
            for (Entry entry : entries) {
                htmlString.append("<p><a href='");
                htmlString.append(entry.link);
                htmlString.append("'>" + entry.title + "</a></p>");
                // If the user set the preference to include summary text,
                // adds it to the display.
                if (pref) {
                    htmlString.append(entry.summary);
                }
            }
            return htmlString.toString();
        }
    
        // Given a string representation of a URL, sets up a connection and gets
        // an input stream.
        private InputStream downloadUrl(String urlString) throws IOException {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            InputStream stream = conn.getInputStream();
            return stream;
        }
    
        /**
         *
         * This BroadcastReceiver intercepts the android.net.ConnectivityManager.CONNECTIVITY_ACTION,
         * which indicates a connection change. It checks whether the type is TYPE_WIFI.
         * If it is, it checks whether Wi-Fi is connected and sets the wifiConnected flag in the
         * main activity accordingly.
         *
         */
        public class NetworkReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                ConnectivityManager connMgr =
                        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    
                // Checks the user prefs and the network connection. Based on the result, decides
                // whether
                // to refresh the display or keep the current display.
                // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
                if (WIFI.equals(sPref) && networkInfo != null
                        && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    // If device has its Wi-Fi connection, sets refreshDisplay
                    // to true. This causes the display to be refreshed when the user
                    // returns to the app.
                    refreshDisplay = true;
                    Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
    
                    // If the setting is ANY network and there is a network connection
                    // (which by process of elimination would be mobile), sets refreshDisplay to true.
                } else if (ANY.equals(sPref) && networkInfo != null) {
                    refreshDisplay = true;
    
                    // Otherwise, the app can't download content--either because there is no network
                    // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
                    // is no Wi-Fi connection.
                    // Sets refreshDisplay to false.
                } else {
                    refreshDisplay = false;
                    Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    
     
  4. e7andy

    e7andy Professional Droid Hedersmedlem

    Joined:
    Oct 14, 2009
    Messages:
    2 349
    Likes Received:
    835
    Telefon:
    Huawei P10 Plus

    MINA ENHETER

    Telefon:
    Huawei P10 Plus
    Telefon 2:
    Nexus 5
    Telefon 3:
    ADP1
    Övrigt:
    LG G Watch R, ChromeCast
    Börja med att ärva från Fragment. Då kommer den att börja klaga på de metoderna med override som inte existerar i Fragment-klassen som du behöver ändra på, t.ex. onCreate ska vara onCreateView.
    Vissa metoder kan ha lite andra signaturer som du behöver ändra till, t.ex. onCreateOptionsMenu ska inte returnera något.
    Du måste sätta setHasOptionsMenu(true); om ditt fragment ska tillhandahålla en options menu.
    this ska ändras till getActivity() eller något Context-objekt.

    Kolla i JavaDoc:en för Fragment för att se hur du ska göra:
    http://developer.android.com/reference/android/app/Fragment.html

    Det är en del småsaker som måste ändras för att det ska fungera.
     
  5. Lovera

    Lovera Baby Droid Medlem

    Joined:
    Dec 17, 2010
    Messages:
    17
    Likes Received:
    4

    MINA ENHETER

    Tack för ditt svar!
    Har googlat men hittar inte hur jag ärver från ett fragment. Jag är ganska ny på det här med android-programmering ska väl tilläggas.
     
  6. e7andy

    e7andy Professional Droid Hedersmedlem

    Joined:
    Oct 14, 2009
    Messages:
    2 349
    Likes Received:
    835
    Telefon:
    Huawei P10 Plus

    MINA ENHETER

    Telefon:
    Huawei P10 Plus
    Telefon 2:
    Nexus 5
    Telefon 3:
    ADP1
    Övrigt:
    LG G Watch R, ChromeCast
    Din klass ärver just nu från Activity:
    public class NewsFragment extends Activity {

    Ändra arvet till:
    public class NewsFragment extends Fragment {

    Det här är vanlig Java-programmering så sök på det så får du nog lite bättre tips på objektorientering och hur du bygger upp klasser än om du söker på Android-programmering.
     
  7. Lovera

    Lovera Baby Droid Medlem

    Joined:
    Dec 17, 2010
    Messages:
    17
    Likes Received:
    4

    MINA ENHETER

    Har ändrat arvet till Fragment, satt onCreateOptionsMenu till false och ändrat (this) till (getActivity()). Men appen kraschar fortfarande :(

    Code:
    public class NewsFragment extends Fragment {
        public static final String WIFI = "Wi-Fi";
        public static final String ANY = "Any";
        private static final String URL =
                "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";
    
        // Whether there is a Wi-Fi connection.
        private static boolean wifiConnected = false;
        // Whether there is a mobile connection.
        private static boolean mobileConnected = false;
        // Whether the display should be refreshed.
        public static boolean refreshDisplay = true;
    
        // The user's current network preference setting.
        public static String sPref = null;
    
        // The BroadcastReceiver that tracks network connectivity changes.
        private NetworkReceiver receiver = new NetworkReceiver();
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Register BroadcastReceiver to track connection changes.
            IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
            receiver = new NetworkReceiver();
            getActivity().registerReceiver(receiver, filter);
        }
    
        // Refreshes the display if the network connection and the
        // pref settings allow it.
        @Override
        public void onStart() {
            super.onStart();
    
            // Gets the user's network preference settings
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    
            // Retrieves a string value for the preferences. The second parameter
            // is the default value to use if a preference value is not found.
            sPref = sharedPrefs.getString("listPref", "Wi-Fi");
    
            updateConnectedFlags();
    
            // Only loads the page if refreshDisplay is true. Otherwise, keeps previous
            // display. For example, if the user has set "Wi-Fi only" in prefs and the
            // device loses its Wi-Fi connection midway through the user using the app,
            // you don't want to refresh the display--this would force the display of
            // an error page instead of stackoverflow.com content.
            if (refreshDisplay) {
                loadPage();
            }
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            if (receiver != null) {
            	getActivity().unregisterReceiver(receiver);
            }
        }
    
        // Checks the network connection and sets the wifiConnected and mobileConnected
        // variables accordingly.
        private void updateConnectedFlags() {
            ConnectivityManager connMgr =
                    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
            NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
            if (activeInfo != null && activeInfo.isConnected()) {
                wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
                mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
            } else {
                wifiConnected = false;
                mobileConnected = false;
            }
        }
    
        private ConnectivityManager getSystemService(String connectivityService) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	// Uses AsyncTask subclass to download the XML feed from stackoverflow.com.
        // This avoids UI lock up. To prevent network operations from
        // causing a delay that results in a poor user experience, always perform
        // network operations on a separate thread from the UI.
        private void loadPage() {
            if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
                    || ((sPref.equals(WIFI)) && (wifiConnected))) {
                // AsyncTask subclass
                new DownloadXmlTask().execute(URL);
            } else {
                showErrorPage();
            }
        }
    
        // Displays an error if the app is unable to load content.
        private void showErrorPage() {
            setContentView(R.layout.news_activity);
    
            // The specified network connection is not available. Displays error message.
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.loadData(getResources().getString(R.string.connection_error),
                    "text/html", null);
        }
    
        private WebView findViewById(int webview) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	private void setContentView(int main) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	// Populates the activity's options menu.
        public boolean onCreateViewOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.mainmenu, menu);
            return false;
        }
    
        private MenuInflater getMenuInflater() {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	// Handles the user's menu selection.
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.settings:
                    Intent settingsActivity = new Intent(getBaseContext(), SettingsActivity.class);
                    startActivity(settingsActivity);
                    return true;
            case R.id.refresh:
                    loadPage();
                    return true;
            default:
                    return super.onOptionsItemSelected(item);
            }
        }
    
        private Context getBaseContext() {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	// Implementation of AsyncTask used to download XML feed from stackoverflow.com.
        private class DownloadXmlTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... urls) {
                try {
                    return loadXmlFromNetwork(urls[0]);
                } catch (IOException e) {
                    return getResources().getString(R.string.connection_error);
                } catch (XmlPullParserException e) {
                    return getResources().getString(R.string.xml_error);
                }
            }
    
            @Override
            protected void onPostExecute(String result) {
                setContentView(R.layout.main);
                // Displays the HTML string in the UI via a WebView
                WebView myWebView = (WebView) findViewById(R.id.webview);
                myWebView.loadData(result, "text/html", null);
            }
        }
    
        // Uploads XML from stackoverflow.com, parses it, and combines it with
        // HTML markup. Returns HTML string.
        private String loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
            InputStream stream = null;
            StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
            List<Entry> entries = null;
            String title = null;
            String url = null;
            String summary = null;
            Calendar rightNow = Calendar.getInstance();
            DateFormat formatter = new SimpleDateFormat("MMM dd h:mmaa");
    
            // Checks whether the user set the preference to include summary text
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
            boolean pref = sharedPrefs.getBoolean("summaryPref", false);
    
            StringBuilder htmlString = new StringBuilder();
            htmlString.append("<h3>" + getResources().getString(R.string.page_title) + "</h3>");
            htmlString.append("<em>" + getResources().getString(R.string.updated) + " " +
                    formatter.format(rightNow.getTime()) + "</em>");
    
            try {
                stream = downloadUrl(urlString);
                entries = stackOverflowXmlParser.parse(stream);
            // Makes sure that the InputStream is closed after the app is
            // finished using it.
            } finally {
                if (stream != null) {
                    stream.close();
                }
            }
    
            // StackOverflowXmlParser returns a List (called "entries") of Entry objects.
            // Each Entry object represents a single post in the XML feed.
            // This section processes the entries list to combine each entry with HTML markup.
            // Each entry is displayed in the UI as a link that optionally includes
            // a text summary.
            for (Entry entry : entries) {
                htmlString.append("<p><a href='");
                htmlString.append(entry.link);
                htmlString.append("'>" + entry.title + "</a></p>");
                // If the user set the preference to include summary text,
                // adds it to the display.
                if (pref) {
                    htmlString.append(entry.summary);
                }
            }
            return htmlString.toString();
        }
    
        // Given a string representation of a URL, sets up a connection and gets
        // an input stream.
        private InputStream downloadUrl(String urlString) throws IOException {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            InputStream stream = conn.getInputStream();
            return stream;
        }
    
        /**
         *
         * This BroadcastReceiver intercepts the android.net.ConnectivityManager.CONNECTIVITY_ACTION,
         * which indicates a connection change. It checks whether the type is TYPE_WIFI.
         * If it is, it checks whether Wi-Fi is connected and sets the wifiConnected flag in the
         * main activity accordingly.
         *
         */
        public class NetworkReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                ConnectivityManager connMgr =
                        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    
                // Checks the user prefs and the network connection. Based on the result, decides
                // whether
                // to refresh the display or keep the current display.
                // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
                if (WIFI.equals(sPref) && networkInfo != null
                        && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    // If device has its Wi-Fi connection, sets refreshDisplay
                    // to true. This causes the display to be refreshed when the user
                    // returns to the app.
                    refreshDisplay = true;
                    Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
    
                    // If the setting is ANY network and there is a network connection
                    // (which by process of elimination would be mobile), sets refreshDisplay to true.
                } else if (ANY.equals(sPref) && networkInfo != null) {
                    refreshDisplay = true;
    
                    // Otherwise, the app can't download content--either because there is no network
                    // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
                    // is no Wi-Fi connection.
                    // Sets refreshDisplay to false.
                } else {
                    refreshDisplay = false;
                    Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
                }
            }
        }
    
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    }
    
    
     
  8. e7andy

    e7andy Professional Droid Hedersmedlem

    Joined:
    Oct 14, 2009
    Messages:
    2 349
    Likes Received:
    835
    Telefon:
    Huawei P10 Plus

    MINA ENHETER

    Telefon:
    Huawei P10 Plus
    Telefon 2:
    Nexus 5
    Telefon 3:
    ADP1
    Övrigt:
    LG G Watch R, ChromeCast
    Det kan vara vad som helst som går fel. Vad du har gjort vet jag inte eftersom jag bara ser en enda klass.

    Kolla i LogCat för att få reda på vad som går fel. Det brukar stå ett ganska utförligt felmeddelande och i bland även tips på vad man kan ha gjort för fel och hur man åtgärdar det.
     
  9. evening.beam

    evening.beam Teen Droid Medlem

    Joined:
    Jun 20, 2012
    Messages:
    259
    Likes Received:
    61

    MINA ENHETER

    Ett vanligt problem är att man har fel i sin manifest fil, såsom felaktiga rättigheter, missat att deklarera en publik klass etc.
     
  10. pata88

    pata88 Youth Droid Medlem

    Joined:
    Jan 22, 2011
    Messages:
    208
    Likes Received:
    14

    MINA ENHETER

    Jag använder mig av samma implementation för TabsAdaptern som trådskaparen. Min fråga lyder:

    När man skapar en ny tabb så kan man skicka med en Bundle. Detta vill jag göra men hur kommer jag åt den från min Fragment sen?


    Exempel:

    mTabsAdapter = new TabsAdapter(this, mViewPager);

    Bundle bundle = new Bundle();
    bundle.putParcelable("State", state);


    mTabsAdapter.addTab(
    bar.newTab().setText("Information"),
    FragmentInformation.class, bundle);
     
  11. pata88

    pata88 Youth Droid Medlem

    Joined:
    Jan 22, 2011
    Messages:
    208
    Likes Received:
    14

    MINA ENHETER

    Kom på det själv!


    Bundle bundle = getArguments();
    State state = bundle.getParcelable("State");