I have an ".HTML" file which is stored in the "res\raw" folder.
I used the following code to display the contents of my file:
static String TAG="WebPageShowActivity";
WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webpagedisplay);
String summary = readRawTextFile(this,R.raw.spotlighterhelp);
//getResources().openRawResource(R.raw.spotlighterhelp).toString();
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadDataWithBaseURL (null,summary, "text/html","ASCII" ,null);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
}
} catch (IOException e) {
return null;
}
Log.e(TAG, "file content: "+text.toString());
return text.toString();
}
now, my problem is: Whatever be the type of encoding, it is not displaying special characters like " or ' What do I do so that these characters are shown too?
Following is the output I am getting
I think it may works, Try to use UTF-8 instead of ASCII for your webView.
mWebView.loadDataWithBaseURL (null,summary, "text/html","UTF-8" ,null);
Related
I have written an Android application to download HTTP contents of following URL: https://www.forbes.com/celebrities/list/
I want to use RegEx to extract image and name of the celebrities from HTML. But unfortunately, HTML content of celebrities list (<tr></tr> tags) only appears when user is “scrolling down”. In fact, my program doesn’t download any <tr></tr> tags inside <tbody> tag.
<tbody id="list-table-body">
</tbody>
How can I fix this problem?
DownloadWebContent Class:
public class DownloadWebContent extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
StringBuilder output = new StringBuilder();
try {
URL url = new URL(urls[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int read = inputStreamReader.read();
while (read != -1) {
char character = (char) read;
output.append(character);
read = inputStreamReader.read();
}
return output.toString();
} catch (Exception e) {
Log.i("HTML_Error", e.getMessage());
return "Failed!";
}
}
}
onCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
DownloadWebContent downloadWebContent = new DownloadWebContent();
try {
String htmlContent = downloadWebContent.execute("https://www.forbes.com/celebrities/list/").get();
String htmlContentReplaced= htmlContent.replace("\"", "");
textView.setText(htmlContentReplaced);
} catch (Exception e) {
e.printStackTrace();
}
}
I need to read an arabic docx placed into my sdcard from my android app, and display the text into a textView, i use the code below but the text appears like weird characters. What is the encoding to use other than UTF-8:
File logFile = new File(path + name);
if (logFile.exists())
{
try
{ FileInputStream fIn = new FileInputStream(logFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn,"UTF-8"));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";}
tv.setText(aBuffer); //tv is the textView
myReader.close();
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
you can convert it to HTML file and put it to assets and show it with WebView.
in your XML:
<WebView
android:layout_width="match_parrent"
android:layout_height="match_parrent"
android:id="#+id/WV1"
/>
in your activity class:
public class MainActivity extends AppCompatActivity {
public WebView wv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wv = (WebView) findViewById(R.id.WV1);
wv.loadUrl("file:///android_asset/myWV.html");
}
}
I am having an android application requirement where i need to open saved web pages, how to do the same?? FIrst of all, how can we save a webpage with its dependancies on android and later open it in your applications? Any inputs will be of great help!
First of all, let's save the webarchive from webview
private void initUI{
webView = (WebView) findViewById(R.id.webView);
AndroidWebClient client = new AndroidWebClient();
webView.setWebViewClient(client);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private class AndroidWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url,
android.graphics.Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.saveWebArchive(Environment.getExternalStorageDirectory()
+ File.separator +"myArchive"+".mht");
// our webarchive wull be available now at the above provided location with name "myArchive"+".mht"
}
public void onLoadResource(WebView view, String url) {
}
}
The way to save the webarchive is same in all APIs but to load it, varies
for API less than Kitkat
private void loadArchive(){
String rawData = null;
try {
rawData = getStringFromFile(Environment.getExternalStorageDirectory()
+ File.separator+"myArchive"+".mht");
} catch (Exception e) {
e.printStackTrace();
}
webView.loadDataWithBaseURL(null, rawData, "application/x-webarchive-xml", "UTF-8", null);
}
public String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
for Kitkat and above
private void loadArchive(){
webView.loadUrl("file:///"+Environment.getExternalStorageDirectory()
+ File.separator+"myArchive"+".mht");
}
This is how I would implement that:
Save original web page into a file
Parse saved file and get all image URLs. Save images into the same directory.
Convert URL of the images(bind all links to a local copies)
Here is simple code which demonstrate this idea:
String download(String url) throws Exception {
String filename = "local.html";
save(url, filename);
List<String> imageLinks = getImageURLs(filename);
for (String imageLink : imageLinks) {
String imageFileName = getImageName(imageLink);
save(imageLink, imageFileName);
}
convertImageURLs(filename);
return filename;
}
void save(String url, String saveTo) throws Exception {
HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
conn.connect();
InputStream is = conn.getInputStream();
save(is, saveTo);
}
void save(InputStream is, String saveTo) {
// save actual content
}
List<String> getImageURLs(String localHtmlFile) {
// parse localHtmlFile and get all URLs for the images
return Collections.EMPTY_LIST;
}
String getImageName(String imageLink) {
// get image name, from url
return null;
}
void convertImageURLs(String localHtmlFile) {
// convert all URLs of the images, something like:
// <img src="original_url"> -> <img src="local_url">
}
I want to read several lines from a text file. These line should be displayed one by one, when I click the next button. I am able to store the strings in a file and read the first line. But when I try to read the next line using the next button, it stops working. Can anybody tell me a solution for this. Thanks in advance.
I have defined the following,
BufferedReader buffreader;
String line;
String fav;
StringBuilder text;
InputStream instream;
String favQuote0;
This is in my oncreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
StringBuilder text = new StringBuilder();
try {
// open the file for reading
InputStream instream = openFileInput("myfilename.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
fav = text.toString();
}
}
} catch (IOException e) {}
TextView tv1 = (TextView)findViewById(R.id.textView2);
tv1.setText(fav);
}
This is my next button
public void next (View view1) {
try {
// open the file for reading
InputStream instream = openFileInput("myfilename.txt");
// if file the available for reading
if (instream != null) {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
fav = text.toString();
}
}
} catch (IOException e) {}
TextView tv1 = (TextView)findViewById(R.id.textView2);
tv1.setText(fav);
}
Both answers do it the wrong way. I will post a description below my code. This is the proper way of doing it.
private int mCurrentLine;
private ArrayList<String> mLines;
private TextView mTextView;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
mCurrentLine = -1;
mLines = new ArrayList<String>();
mTextView = (TextView) findViewById(R.id.text_view);
mButton = (Button) findViewById(R.id.button);
try {
readLinesAndSaveToArrayList();
}
catch (IOException e) {
e.printStackTrace();
}
setTextAndIncrement();
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setTextAndIncrement();
}
});
}
private void readLinesAndSaveToArrayList() throws IOException {
File file = new File("myfilename.txt");
if (!file.exists()) {
throw new FileNotFoundException("myfilename.txt was unable to locate");
}
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
mLines.add(line);
}
bufferedReader.close();
}
private void setTextAndIncrement() {
if (mCurrentLine == mLines.size() - 1) {
return;
}
mCurrentLine++;
mTextView.setText(mLines.get(mCurrentLine));
}
What I do is cache the file's contents in a scalable ArrayList. Each line will be assigned to an index in the array, eg. 0, 1, 2 and so on.
mCurrentLine takes care of positioning in the array. It starts at -1 because there is no current line. In the setTextAndIncrement() it will be set to 0, which in the array is the first index (the first line). The continuous calls will increment the position and take the next lines. If you come to the limit I have put in a check that looks if the mCurrentLine is equal to the max size of lines (mLines.size() - 1, a - 1 because arrays starts from 0 instead of 1).
Other than that I would advice you to use full length names on methods and variables; there is no need to keep them short, it will only make reading them harder. XML should also only contain low letters instead of camelCases.
Try this. This i working for me
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuffer bf = new StringBuffer();
String json = reader.readLine();
try {
do {
bf.append(json);
json = reader.readLine();
}while (json != null);
wt.flush();
wt.close();
Log.d("LOG", " read line output "+new String(bf)+" json "+json);
reader.close();
} catch (Exception e) {
e.printStackTrace(); }
wt is the bufferedwriter which i used to write line. I read from reader and write into file stored locally.
try {
// open the file for reading
InputStream instream = new FileInputStream("myfilename.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (buffreader.hasNext()) {
line = buffreader.readLine();
// do something with the line
}
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
instream.close();
}
I have the HTML files in assets named n0.html, n1.html, etc. I want to create a listview with links to these files, but I don't know how to do it.
I have such a decision with a raw folder. How should I change it to assets files?
public class ViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Bundle bundle = getIntent().getExtras();
String itemname = "n" + bundle.getString("defStrID"); //getting string and forming resource name
Context context = getBaseContext(); //getting context
// Reading text file from resources by name
String text = readRawTextFile(context, getResources().getIdentifier(itemname, "raw", "ru.falcon5f.carguide;"));
WebView wWebView = (WebView) findViewById(R.id.webView);
String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
wWebView.loadData(summary, "text/html", "utf-8"); //uploading text to webview
}
public static String readRawTextFile(Context ctx, int resId) // Reading text raw txt file
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
return null;
}
return text.toString();
}
}
Added
I'm sorry if I ask too stupid questions and I ask too much, but I want to work my first application. This is very important for me. So it consists of two activities:
ViewActivity which I've changed according to your advices
public class ViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Bundle bundle = getIntent().getExtras();
String htmlFileName = "n" + bundle.getString("defStrID"); // Getting file name
Context context = getBaseContext(); // Getting context. You still need that
// Reading text file from resources by name
try {
String text = readAssetTextFile(context, htmlFileName);
WebView wWebView = (WebView) findViewById(R.id.webView);
String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
wWebView.loadData(summary, "text/html", "utf-8"); // Uploading text to webview
}
catch (IOException e) {
Log.e("TAG", e); // Note that you will need to import android.util.Log
}
}
public static String readAssetTextFile(Context ctx, String fileName) throws IOException // Reading the HTML file from assets
{
InputStream inputStream = ctx.getAssets().open(fileName);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
return null;
}
return text.toString();
}
}
In Log.e("TAG", e);, Eclipse wants to change type of "e" to "String".
How can I fix this?
It will not be that much different. You know that you can access a file in the assets like this:
InputStream inputStream = ctx.getAssets().open(fileName);
You can place this instead of your line InputStream inputStream = ctx.getResources().openRawResource(resId);. Then you need to pass in the correct file name. When working with assets you need not use IDs.
Editing your snippet:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Bundle bundle = getIntent().getExtras();
String htmlFileName = "n" + bundle.getString("defStrID") + ".html"; // Getting file name
Context context = getBaseContext(); // Getting context. You still need that
// Reading text file from resources by name
try {
String text = readAssetTextFile(context, htmlFileName);
WebView wWebView = (WebView) findViewById(R.id.webView);
String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
wWebView.loadData(summary, "text/html", "utf-8"); // Uploading text to webview
} catch (IOException e) {
Log.e("TAG", "Exception thrown", e); // Note that you will need to import android.util.Log
}
}
public static String readAssetTextFile(Context ctx, String fileName) // Reading HTML file from assets
{
InputStream inputStream = ctx.getAssets().open(fileName);
.....