![]() |
| Học lập trình Android cơ bản |
RSS là viết tắt của Really Simple Syndication. RSS là một cách dễ dàng để chia sẻ nội dung cập nhật và nội dung trang web của bạn với người dùng để người dùng có thể không phải truy cập vào trang web của bạn hàng ngày cho bất kỳ loại cập nhật nào.
Ví dụ RSS
RSS là tài liệu được tạo bởi trang web có phần mở rộng .xml. Bạn có thể dễ dàng phân tích cú pháp tài liệu này và hiển thị nó cho người dùng trong ứng dụng của bạn. Một tài liệu RSS trông như thế này.
Link đăng ký : Học lập trình Android cơ bản.
Đối với điều này, chúng ta sẽ tạo đối tượng XMLPullParser, nhưng để tạo ra chúng ta đầu tiên sẽ tạo đối tượng XmlPullParserFactory và sau đó gọi phương thức newPullParser () của nó để tạo ra XMLPullParser. Cú pháp của nó được đưa ra dưới đây
Bước tiếp theo liên quan đến việc xác định tệp cho XmlPullParser có chứa XML. Nó có thể là một tập tin hoặc có thể là một Stream. Trong trường hợp của chúng tôi nó là một cú pháp stream.Its được đưa ra dưới đây
Bước cuối cùng là phân tích cú pháp XML. Một tệp XML bao gồm các sự kiện, Tên, Văn bản, Thuộc tínhValue vv Vì vậy, XMLPullParser có một hàm riêng biệt để phân tích từng thành phần của tệp XML. Cú pháp của nó được đưa ra dưới đây
vì vậy chúng ta chỉ cần kiểm tra trong câu lệnh có điều kiện là nếu chúng ta có thẻ nhiệt độ, chúng ta gọi phương thức getAttributeValue trả về cho chúng ta giá trị của thẻ nhiệt độ.
Ngoài các phương thức này, còn có các phương thức khác được lớp này cung cấp để phân tích cú pháp các tệp XML tốt hơn. Những phương pháp này được liệt kê dưới đây
Để thử nghiệm với ví dụ này, bạn có thể chạy nó trên một thiết bị thực tế hoặc trong một trình giả lập.
Sau đây là nội dung của tệp hoạt động chính đã sửa đổi src / MainActivity.java .
<rss version="2.0"> <channel> <title>Sample RSS</title> <link>http://www.google.com</link> <description>World's best search engine</description> </channel> </rss>
Các thành phần RSS
Một tài liệu RSS như trên có các yếu tố sau.| Sr.No | Thành phần & mô tả |
|---|---|
| 1 | kênh Phần tử này được sử dụng để mô tả nguồn cấp dữ liệu RSS |
| 2 | chức vụ Xác định tiêu đề của kênh |
| 3 | liên kết Xác định liên kết siêu đến kênh |
| 4 | sự miêu tả Mô tả kênh |
Phân tích RSS
Phân tích cú pháp một tài liệu RSS giống như phân tích cú pháp XML. Bây giờ hãy xem cách phân tích cú pháp một tài liệu XML.Đối với điều này, chúng ta sẽ tạo đối tượng XMLPullParser, nhưng để tạo ra chúng ta đầu tiên sẽ tạo đối tượng XmlPullParserFactory và sau đó gọi phương thức newPullParser () của nó để tạo ra XMLPullParser. Cú pháp của nó được đưa ra dưới đây
private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();
Bước tiếp theo liên quan đến việc xác định tệp cho XmlPullParser có chứa XML. Nó có thể là một tập tin hoặc có thể là một Stream. Trong trường hợp của chúng tôi nó là một cú pháp stream.Its được đưa ra dưới đây
myparser.setInput(stream, null);
Bước cuối cùng là phân tích cú pháp XML. Một tệp XML bao gồm các sự kiện, Tên, Văn bản, Thuộc tínhValue vv Vì vậy, XMLPullParser có một hàm riêng biệt để phân tích từng thành phần của tệp XML. Cú pháp của nó được đưa ra dưới đây
int event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.END_TAG: if(name.equals("temperature")){ temperature = myParser.getAttributeValue(null,"value"); } break; } event = myParser.next(); }Phương thức getEventType trả về kiểu sự kiện xảy ra. Ví dụ: Tài liệu bắt đầu, bắt đầu từ khóa vv Phương thức getName trả về tên của thẻ và vì chúng ta chỉ quan tâm đến nhiệt độ.
vì vậy chúng ta chỉ cần kiểm tra trong câu lệnh có điều kiện là nếu chúng ta có thẻ nhiệt độ, chúng ta gọi phương thức getAttributeValue trả về cho chúng ta giá trị của thẻ nhiệt độ.
Ngoài các phương thức này, còn có các phương thức khác được lớp này cung cấp để phân tích cú pháp các tệp XML tốt hơn. Những phương pháp này được liệt kê dưới đây
| Sr.No | Phương pháp & mô tả |
|---|---|
| 1 | getAttributeCount () Phương thức này chỉ trả về số thuộc tính của thẻ bắt đầu hiện tại. |
| 2 | getAttributeName (chỉ mục int) Phương thức này trả về tên của thuộc tính được chỉ định bởi giá trị chỉ mục. |
| 3 | getColumnNumber () Phương thức này trả về trả về số cột hiện tại, bắt đầu từ 0. |
| 4 | getDepth () Phương thức này trả về Trả về độ sâu hiện tại của phần tử. |
| 5 | getLineNumber () Trả về số dòng hiện tại, bắt đầu từ 1. |
| 6 | getNamespace () Phương thức này trả về URI không gian tên của phần tử hiện tại. |
| 7 | getPrefix () Phương thức này trả về tiền tố của phần tử hiện tại. |
| số 8 | getName () Phương thức này trả về tên của thẻ. |
| 9 | getText () Phương thức này trả về văn bản cho phần tử cụ thể đó. |
| 10 | isWhitespace () Phương pháp này kiểm tra xem sự kiện TEXT hiện tại chỉ chứa các ký tự khoảng trắng. |
Thí dụ
Đây là một ví dụ minh họa việc sử dụng lớp XMLPullParser. Nó tạo ra một ứng dụng phân tích cú pháp cơ bản cho phép bạn phân tích cú pháp một tài liệu RSS có tại đây tại và sau đó hiển thị kết quả.Để thử nghiệm với ví dụ này, bạn có thể chạy nó trên một thiết bị thực tế hoặc trong một trình giả lập.
| Các bước | Sự miêu tả |
|---|---|
| 1 | Bạn sẽ sử dụng Android studio để tạo ứng dụng Android theo gói com.example.sairamkrishna.myapplication. |
| 2 | Sửa đổi tệp src / MainActivity.java để thêm mã cần thiết. |
| 3 | Sửa đổi res / layout / activity_main để thêm các thành phần XML tương ứng. |
| 4 | Tạo một tệp java mới dưới src / HandleXML.java để tìm nạp và phân tích cú pháp dữ liệu XML. |
| 5 | Tạo một tệp java mới dưới src / second.java để hiển thị kết quả của XML |
| 5 | Sửa đổi AndroidManifest.xml để thêm quyền truy cập internet cần thiết. |
| 6 | Chạy ứng dụng và chọn một thiết bị Android đang chạy và cài đặt ứng dụng trên đó và xác minh kết quả. |
package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { EditText title,link,description; Button b1,b2; private String finalUrl="http://tutorialspoint.com/android/sampleXML.xml"; private HandleXML obj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); title = (EditText) findViewById(R.id.editText); link = (EditText) findViewById(R.id.editText2); description = (EditText) findViewById(R.id.editText3); b1=(Button)findViewById(R.id.button); b2=(Button)findViewById(R.id.button2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { obj = new HandleXML(finalUrl); obj.fetchXML(); while(obj.parsingComplete); title.setText(obj.getTitle()); link.setText(obj.getLink()); description.setText(obj.getDescription()); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in=new Intent(MainActivity.this,second.class); startActivity(in); } }); } }Sau đây là nội dung của tệp java src / HandleXML.java .
package com.example.rssreader; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.util.Log; public class HandleXML { private String title = "title"; private String link = "link"; private String description = "description"; private String urlString = null; private XmlPullParserFactory xmlFactoryObject; public volatile boolean parsingComplete = true; public HandleXML(String url){ this.urlString = url; } public String getTitle(){ return title; } public String getLink(){ return link; } public String getDescription(){ return description; } public void parseXMLAndStoreIt(XmlPullParser myParser) { int event; String text=null; try { event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = myParser.getText(); break; case XmlPullParser.END_TAG: if(name.equals("title")){ title = text; } else if(name.equals("link")){ link = text; } else if(name.equals("description")){ description = text; } else{ } break; } event = myParser.next(); } parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchXML(){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try { 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(); xmlFactoryObject = XmlPullParserFactory.newInstance(); XmlPullParser myparser = xmlFactoryObject.newPullParser(); myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); myparser.setInput(stream, null); parseXMLAndStoreIt(myparser); stream.close(); } catch (Exception e) { } } }); thread.start(); } }Tạo một tệp và được đặt tên dưới dạng tệp second.java trong thư mục java / second.java
package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class second extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); WebView w1=(WebView)findViewById(R.id.webView); w1.loadUrl("http://tutorialspoint.com/android/sampleXML.xml"); } }Tạo tệp xml tại res / layout / second_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webView" android:layout_gravity="center_horizontal" /> </LinearLayout>Sửa đổi nội dung của res / layout / activity_main.xml thành những thứ sau -
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:transitionGroup="true"> <TextView android:text="RSS example" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:textSize="35dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials point" android:id="@+id/textView" android:layout_below="@+id/textview" android:layout_centerHorizontal="true" android:textColor="#ff7aff24" android:textSize="35dp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/abc" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:theme="@style/Base.TextAppearance.AppCompat" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_below="@+id/imageView" android:hint="Tittle" android:textColorHint="#ff69ff0e" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText2" android:layout_below="@+id/editText" android:layout_alignLeft="@+id/editText" android:layout_alignStart="@+id/editText" android:textColorHint="#ff21ff11" android:hint="Link" android:layout_alignRight="@+id/editText" android:layout_alignEnd="@+id/editText" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText3" android:layout_below="@+id/editText2" android:layout_alignLeft="@+id/editText2" android:layout_alignStart="@+id/editText2" android:hint="Description" android:textColorHint="#ff33ff20" android:layout_alignRight="@+id/editText2" android:layout_alignEnd="@+id/editText2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fetch" android:id="@+id/button" android:layout_below="@+id/editText3" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_toLeftOf="@+id/imageView" android:layout_toStartOf="@+id/imageView" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Result" android:id="@+id/button2" android:layout_alignTop="@+id/button" android:layout_alignRight="@+id/editText3" android:layout_alignEnd="@+id/editText3" /> </RelativeLayout>Sửa đổi res / values / string.xml thành
<resources> <string name="app_name">My Application</string> </resources>Đây là tệp AndroidManifest.xml mặc định .
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".second"></activity> </application> </manifest>Hãy thử chạy ứng dụng của bạn. Tôi cho rằng bạn đã tạo AVD của mình trong khi thiết lập môi trường. Để chạy ứng dụng từ Android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ.
Android studio cài đặt ứng dụng trên AVD của bạn và khởi động ứng dụng và nếu mọi thứ đều ổn với thiết lập và ứng dụng của bạn, ứng dụng sẽ hiển thị cửa sổ Trình mô phỏng sau
Chỉ cần nhấn nút Tìm nạp nguồn cấp dữ liệu để tìm nạp nguồn cấp dữ liệu RSS. Sau khi nhấn, màn hình sau sẽ xuất hiện sẽ hiển thị dữ liệu RSS.
Chỉ cần nhấn nút Tìm nạp nguồn cấp dữ liệu để tìm nạp nguồn cấp dữ liệu RSS. Sau khi nhấn, màn hình sau sẽ xuất hiện sẽ hiển thị dữ liệu RSS.

Không có nhận xét nào:
Đăng nhận xét