বাংলায় অ্যান্ড্রয়েড সহায়িকা - Bangla Android Guide

XML ডাটা ব্যবহার

নমুনা উদাহরণটি অ্যাপলিকেশন একটি AsyncTaskএর মধ্যে থেকে XML ফিড আনতে যায় এবং পার্স করে। এটা প্রধান ইউজার ইন্টারফেস থ্রেড বন্ধ করার প্রক্রিয়াকে গ্রহণ করে। যখন প্রক্রিয়া শেষ হয় অ্যাপ প্রধান একটিভিটির (NetworkActivity) ইউআইকে আপডেট করে।

নীচের অংশটি দেখায়, loadPage() পদ্ধতি নীচের কাজগুলো করে:

  • XML ফিডের জন্য URL সহকারে একটি স্ট্রিং ভেরিয়েবল আরম্ভ করা।

  • যদি ইউজারের সেটিং এবং নেটওয়ার্ক কানেকশন এটাকে সমর্থ করে, new DownloadXmlTask().execute(url) আহবান করে। এটা একটি নতুন DownloadXmlTask অবজেক্ট (AsyncTask সাবক্লাস) ইনসটেনসিয়েট কওে এবং এর execute()পদ্ধতি রান করে, যা ফিড ডাউনলোড এবং পার্স করে এবং ইউআই তে প্রদর্শিত হতে একটি স্ট্রিং রেজাল্ট ফেরত দেয়।

    public class NetworkActivity 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;
      public static String sPref = null;
    
      ...
    
      // Uses AsyncTask to download the XML feed from stackoverflow.com.
      public void loadPage() {
    
          if((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) {
              new DownloadXmlTask().execute(URL);
          }
          else if ((sPref.equals(WIFI)) && (wifiConnected)) {
              new DownloadXmlTask().execute(URL);
          } else {
              // show error
          }
      }
    

AsyncTask সাবক্লাস নীচে দেখানো হলো, DownloadXmlTask নীচের AsyncTask পদ্ধতিগুলো বাস্তবায়ন করে:

  • doInBackground()পদ্ধতি loadXmlFromNetwork()বাস্তবায়ন করে। এটা ফিড কে একটি প্যারামিটার হিসাবে পাস করে। পদ্ধতি loadXmlFromNetwork() ফিড নিয়ে আসে এবং প্রক্রিয়া করে। যখন এটা শেষ করে, একটি রেজাল্ট স্ট্রিং ফেরত দেয়।

  • onPostExecute()ফেরত আসা স্ট্রিং গ্রহণ করে এবং ইউজার ইন্টারফেসে প্রদর্শন করে।

// 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);
    }
}

নিচেরটা হচ্ছে পদ্ধতি loadXmlFromNetwork()যা DownloadXmlTask থেকে আহবায়িত হয়। এটা নীচের বিষয়গুলো করে থাকে:

  1. একটি StackOverflowXmlParser ইনসটেনসিয়েট করে। এটা এন্ট্রি অবেজেক্টের (এন্ট্রিস), এবং title, url এবং summary এর একটি তালিকার (List) জন্য ভেরিয়েবলও তৈরী করে, ঐ ফিল্ডগুলোর জন্য এক্সএমএল ফিড থেকে বের করে নিয়ে আসা ভ্যালু ধারন করতে।

  2. downloadUrl কল করে, যা ফিড নিযে আসে এবং একটি InputStream. হিসাবে এটা ফেরত দেয়।

  3. InputStream কে পার্স করতে StackOverflowXmlParser ব্যবহার করে। StackOverflowXmlParser ফিড থেকে পাওয়া ডাটা সহকারে entries এর একটি List অধ্যুষিত করে।

  4. entriesList প্রসেস করে, HTML মার্কআপ দিয়ে ফিড ডাটা একত্রিত করে।

  5. একটি HTML স্ট্রিং ফেরত আনে যা AsyncTaskপদ্ধতি onPostExecute()দ্বারা প্রধান একটিভিটির মধ্যে প্রদর্শন করে।

// 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;
    // Instantiate the parser
    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();
    return conn.getInputStream();
}