When load url show Error : java.security.cert.CertPathValidatorException: Trust anchor for certification path not found in PDF android studio

Ponglang Petrung
PongPloyDev
Published in
9 min readAug 25, 2020

--

When load URL and show java.security.cert.CertPathValidatorException: Trust anchor for certification path not found in android.

The First Find library load PDF most Using File-Loader and PdfViewer

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
implementation 'com.github.kk121:File-Loader:1.2'
}

Opening and viewing documents in Android applications is a very useful feature and should be included in every application. You can open any application available on your mobile phone and you will find that most of them contain document files in different ways.

And among these documents, the most common and widely used document format is the PDF format . Format PDF , or Portable Document Format is a file format that contains all the elements of printed material. This is the most used document format. For example, in payment applications, you may receive your monthly expense invoice as a PDF document.

So if you want to display some kind of document in your application, then you can use the PDF format. And this article is meant to introduce ways to open PDF files in Android apps. Hope you find the right way for your application.

Open the PDF file using WebView

The first and easiest way to display a PDF is to display it in WebView . All you need to do is place the WebView in the layout file and download the PDF file via the dedicated URL to view Google Docs documents using the function webView.loadUrl().

In my case, the Activity name is WebViewPdf . And the layout file is activity_web_view_pdf.xml:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

And WebViewPdf.kt file :

class WebViewPdf : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web_view_pdf)
webView.webViewClient = WebViewClient()
webView.settings.setSupportZoom(true)
webView.settings.javaScriptEnabled = true
val url = "Đường dẫn file pdf của bạn"
webView.loadUrl("https://docs.google.com/gview?embedded=true&url=$url")
}
}

The drawback of this method is that you have to depend on the Google viewer path, if it is changed then you have to change it manually as well.

Open the PDF file with the library

There are various libraries in Android that can be used to display PDFs. An example is the PDFViewer library to read the PDF file and the File-Loader library to download the file from the Internet and then display that file in the application.

In your project level build.gradle file , add the following code line:

repositories {
google()
jcenter()
maven {url "https://jitpack.io"}//add this line
}

And in the module-level build.gradle file :

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
implementation 'com.github.kk121:File-Loader:1.2'

After adding these dependencies, you need to add the following permissions in the AndroidManifest.xml file :

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

From the Assets folder

First, we will look at how to view PDF files stored in the assets directory .

First, a user interface is required, with buttons for opening PDFs from different places (asset folder, on the device, from the internet) — activity_main.xml :

<?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"
tools:context=".MainActivity">

<LinearLayout
android:orientation="vertical"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/open_assets"
android:text="From Assets"
android:layout_width="320dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/open_storage"
android:text="From Device"
android:layout_width="320dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/open_internet"
android:text="From Internet"
android:layout_width="320dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>

Next, create an Activity to display the PDF files in the application — ViewActivity and activity_view.xml :

<?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"
tools:context=".ViewActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdf_viewer"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.github.barteksc.pdfviewer.PDFView>
<ProgressBar
android:id="@+id/progress_bar"
android:indeterminate="true"
android:layout_centerInParent="true"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>

The next step is to add the PDF file in the assets directory . You can create an asset directory by right-clicking on the java folder then New> Folder> Asset Folder

Then, add the following code to handle the event onClickfor the buttons:

class MainActivity : AppCompatActivity() {    val PICK_PDF_CODE = 1000
lateinit var btn_open_assets: Button//for assets
lateinit var btn_open_storage:Button//for phone storage
lateinit var btn_opn_intenet:Button//for internet
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_open_assets = findViewById(R.id.open_assets) btn_open_assets.setOnClickListener(object: View.OnClickListener {
override fun onClick(view:View) {
val intent = Intent(this@MainActivity, ViewActivity::class.java)
intent.putExtra("ViewType", "assets")
startActivity(intent)
}
})
}
}

We will now use the PDFViewer library to perform various operations on the PDF, such as setting the default page using the defaultPage () method , enabling the swipe event using enableSwipe (). or double tap to zoom in using enableDoubletap ()ViewActivity.kt:

class ViewActivity : AppCompatActivity() {    lateinit var pdfView: PDFView
lateinit var progressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view)
pdfView = findViewById(R.id.pdf_viewer)
progressBar = findViewById(R.id.progress_bar)
if (intent != null)
{
val viewType = intent.getStringExtra("ViewType")
if (viewType != null || TextUtils.isEmpty(viewType))
{
if (viewType == "assets")
{
pdfView.fromAsset("github_git_cheat_sheet.pdf")
.password(null)//enter password if PDF is password protected
.defaultPage(0)//set the default page
.enableSwipe(true)//enable the swipe to change page
.swipeHorizontal(false)//set horizontal swipe to false
.enableDoubletap(true)//double tap to zoom
.onDraw(object: OnDrawListener {
override fun onLayerDrawn(canvas: Canvas, pageWidth:Float, pageHeight:Float, displayedPage:Int) {
}
})
.onDrawAll(object: OnDrawListener {
override fun onLayerDrawn(canvas:Canvas, pageWidth:Float, pageHeight:Float, displayedPage:Int) {
}
})
.onPageError(object: OnPageErrorListener {
override fun onPageError(page:Int, t:Throwable) {
Toast.makeText(this@ViewActivity, "Error", Toast.LENGTH_LONG).show()
}
})
.onPageChange(object: OnPageChangeListener {
override fun onPageChanged(page:Int, pageCount:Int) {
}
})
.onTap(object: OnTapListener {
override fun onTap(e: MotionEvent):Boolean {
return true
}
})
.onRender(object: OnRenderListener {
override fun onInitiallyRendered(nbPages:Int, pageWidth:Float, pageHeight:Float) {
pdfView.fitToWidth()
}
})
.enableAnnotationRendering(true)
.invalidPageColor(Color.WHITE)
.load()
}
}
}
}
}

Similarly, you can take out PDF files already in the device to display.

From the Internet

First, we will have to download the bending PDF file using FileLoader and then use this file to display on ViewActivity using the same process as above. But here you will have to use fromFile () to add the PDF display. Here is the code for the ViewActivity.kt file :

if (viewType == "assets") {
...
...
//assets code
}
else if (viewType == "storage") {
...
...
//storage code
}
else if (viewType == "internet")
{
progressBar.visibility = View.VISIBLE
FileLoader.with(this)
.load("https://github.github.com/training-kit/downloads/github-git-cheat-sheet.pdf")
.fromDirectory("PDFFiles", FileLoader.DIR_EXTERNAL_PUBLIC)
.asFile(object: FileRequestListener<File> {
override fun onLoad(fileLoadRequest: FileLoadRequest, fileResponse: FileResponse<File>) {
progressBar.visibility = View.GONE
val pdfFile = fileResponse.getBody()
pdfView.fromFile(pdfFile)
.password(null)
.defaultPage(0)
.enableSwipe(true)
.swipeHorizontal(false)
.enableDoubletap(true)
.onDraw(object:OnDrawListener {
override fun onLayerDrawn(canvas:Canvas, pageWidth:Float, pageHeight:Float, displayedPage:Int) {
}
})
.onDrawAll(object:OnDrawListener {
override fun onLayerDrawn(canvas:Canvas, pageWidth:Float, pageHeight:Float, displayedPage:Int) {
}
})
.onPageError(object:OnPageErrorListener {
override fun onPageError(page:Int, t:Throwable) {
Toast.makeText(this@ViewActivity, "Error", Toast.LENGTH_LONG).show()
}
})
.onPageChange(object:OnPageChangeListener {
override fun onPageChanged(page:Int, pageCount:Int) {
}
})
.onTap(object:OnTapListener {
override fun onTap(e:MotionEvent):Boolean {
return true
}
})
.onRender(object:OnRenderListener {
override fun onInitiallyRendered(nbPages:Int, pageWidth:Float, pageHeight:Float) {
pdfView.fitToWidth()
}
})
.enableAnnotationRendering(true)
.invalidPageColor(Color.WHITE)
.load()
}
override fun onError(fileLoadRequest:FileLoadRequest, throwable:Throwable) {
Toast.makeText(this@ViewActivity, "Error", Toast.LENGTH_LONG).show()
progressBar.setVisibility(View.GONE)
}
})
}

Done, run the application and test the results offline.

When Run App in use URl this certification path

Handling custom SSL Certificates on Android and fixing SSLHandshakeException.

“E/MainActivity: onError: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.”

Why !!!

IS use help full

The step use Certificates

1. The CA that issued the server certificate was unknown
2. The server certificate wasn’t signed by a CA, but was self signed
3. The server configuration is missing an intermediate CA

https://developer.android.com/training/articles/security-ssl.html#CommonProblems

“carloan.xxx.com Using illegal security certificates The certificate might not be sending the appropriate intermediate certificates. An additional root certificate may need to be imported. Error code: SEC_ERROR_UNKNOWN_ISSUER”

how to set up new

Try following the suggestions that google suggests.

How to solve it by 2 simple methods.

Perform overide. Change usesCleartextTraffic to true under the application tag.

<?xml version=”1.0" encoding=”utf-8"?>
<manifest …>
<uses-permission android:name=”android.permission.INTERNET” />
<application

android:usesCleartextTraffic=”true”
…>

</application>
</manifest>

2. Perform Overide Network Security Config. The method is
Create an xml folder as in the image.

Enable SSL Proxy for debug only

The above setting is good, but it defeats the purpose of Google adding this security feature in Android Nougat for your App.

So to take advantage of this feature, you might want to enable your SSL network to be proxy-able in debug mode only.

What you need to do is still follow the step one above, but change the content of networkSecurityConfig.xml to below

3. Create file network_security_config.xml Which is under the xml folder and copy the code below to paste

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>

4. Edit the manifest.xml file as follows.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
<domain-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="@raw/xxxsolutionscom" />
</trust-anchors>
<domain includeSubdomains="true">xxxsolutions.com</domain>

</domain-config>
</network-security-config>

cr :

You have followed the group:

https://developer.android.com/training/articles/security-ssl

https://discord.gg/22mgfu

- Who does not answer questions, press delete all cases.
- Incomplete answers are also deleted.
- Accepting only people, not accepting pages
Impolite, illegal, erased and banned
- Account / Avatar account.
- No need to join a group. Catch, delete, only one location.
- Do not advertise for work Job .
- This group is sharing knowledge, not sharing nonsense.

- Thank you to member All.
- Thank you for the add later

Pm.
If you understand Please reply with If not, then you will be deleted.

//admin 😁😁😁

And

I created a group of Android Developers Android and Kotlin Droidcon Github library. If you have any questions, you can ask. You can join in the App Telegram. Now join Android Developers And Kotlin Droidcon

Android Developers And Kotlin Droidcon Github Library

Thank you for joining: https://www.facebook.com/groups/883546485084033/?fref=ts I created a group of Android Developers Android and Kotlin Droidcon Github library. If you have any questions, you can ask. You can join in the App Telegram. https://t.me/joinchat/IhB5KQ0aXC7ckNgjRaBaCw Now join Android Developers And Kotlin Droidcon Github Library Community Telegram App to help each other. Joining Link:

PongPloy Zone AppDev

Link : https://www.facebook.com/PPAndroid-Github-Dev-Zone-170227463027435/notifications/

--

--