13

I'm making a kind of browser app. It's working just like I want except for one thing. I have to load a URL that is inside a .txt in my WebView. The .txt will be in the device root directory and the user will be able to edit this .txt using the app. How can I do it?

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="com.abaco.abawser.MainActivity">

    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

MainActivity.java:

package com.abaco.awser;

import android.app.ActionBar;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView web;
    String webURL = "http://www.google.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();

        if (savedInstanceState != null)
            ((WebView)findViewById(R.id.web)).restoreState(savedInstanceState);

        web = (WebView) findViewById(R.id.web);
        web.loadUrl(webURL);
        web.setPadding(0, 0, 0, 0);
        web.getSettings().setLoadWithOverviewMode(true);
        web.getSettings().setUseWideViewPort(true);
        web.getSettings().setJavaScriptEnabled(true);

        this.web.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                view.loadUrl(url);
                return true;
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        web.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        web.restoreState(savedInstanceState);
    }

    @Override
    public void onBackPressed() {
    }

}

2 Answers2

11

There are two separate concerns here:

  1. getting a URL from the .txt file
  2. loading a URL in WebView

You should think of them separately. You already seem to know how to do 2. (load a URL into WebView), so focus on 1.

You can learn how to open and read a file in Java from many resources. Including SO. The only Android specific part is accessing the file. Android applications have restricted access to most storage locations. On user (not rooted) devices, apps have access to only few location:

Application Storage

Each app can access own storage (in /data/data/{your.package}). You can open these files directly using openFileInput. Or get the path using getFilesDir().

External Storage

If the file is in /sdcard your app will need the READ_EXTERNAL_STORAGE permission and you might have to ensure that external storage is mounted. Learn more here.

/data/local/tmp

This is one location on most Android devices (but not all) that all apps can "enter", so if you put the file in there and make sure it's world readable (chmod o+r /data/local/tmp/myfile.txt) then you will be able to open it in any app.

szym
  • 5,606
  • 28
  • 34
4

I would like to support the approach of @szym. Here you can find some code for your better understanding.

File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
    }
    br.close();

String url = "";

String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
    Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
    Matcher urlMatcher = pattern.matcher(text.toString());

    while (urlMatcher.find())
    {
        url = text.toString().substring(urlMatcher.start(0),
                urlMatcher.end(0));
        break;
    }

    if(""!=url){
         WebView webview = (WebView) findViewById(R.id.webView1);
        webview.setWebViewClient(new WebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl(url);
    }

}
catch (IOException e) {
    //You'll need to add proper error handling here
}
Rivu Chakraborty
  • 1,372
  • 2
  • 12
  • 37