Android10 : Webview loaddata not working on Android 10

Time to upgrade targetSdkVersion to 29 (Android 10)

หลังจากเราอัพเกรด tarketSdkVersion = 29 (android10) แล้ว พบกว่าแอปปลิเคชันบางส่วน Error, Warning or not working ในที่นี้ขอยกมาหนึ่งปัญหาที่เกิดขึ้นหลังจากอัพเกรด targetSdk = 29 นั่นคือ Webview ไม่แสดงข้อความ

เดิมเราเรียกใช้ Webview แสดงข้อความแบบ Web html ได้ ดังตัวอย่าง

webview = (Webview) findViewById(R.id.webview1) ;

String mimeType = “text/html;charset=UTF-8”;
String encoding = “UTF-8”;

String text = “<html><head>”
+ “<style> body{color: #000 !important;text-align:left}”
+ “</style></head>”
+ “<body>”
+ “Hello World”
+ “</body></html>”;

webview.loadData(text,mimeType, encoding);

แต่พอเปลี่ยน targetSdk = 29 webview coding ข้างต้นไม่ทำงาน ไม่แสดงผลออกมา เราสามารถแก้ไขด้วยการเรียกใช้ฟังก์ชันโหลดข้อมูลตัวใหม่ดังนี้

loadDataWithBaseURL(baseUrl, string, mimeType, encoding, historyUrl);

โดยแก้ไขเฉพาะบรรทัดที่โหลดข้อมูลดังตัวอย่าง

เดิม

webview.loadData(text,mimeType, encoding);

ใหม่

webview.loadDataWithBaseURL(null, text, mimeType, encoding, null);

แล้วลอง Build -> Run ใหม่ครับ

You may also like...