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);
.....
Related
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 trying to get last 10 rows from file but not able to fetch.
i have two activities:
in the first, i want to write text from an EditText to a file.
in the second activity i try to read the stored data and write it to a textView
public class Date_Location extends Activity {
ImageView imageView;
EditText editTextDate, editTextLocation, editTextEdit;
private static final String TAG = Date_Location.class.getName();
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.date_location);
editTextDate = (EditText) findViewById(R.id.editText1);
editTextLocation = (EditText) findViewById(R.id.editText2);
editTextEdit = (EditText) findViewById(R.id.editText3);
imageView = (ImageView) findViewById(R.id.next);
}
public void goNext(View view) {
String Date = editTextDate.getText().toString();
String Location = editTextLocation.getText().toString();
String Comment = editTextEdit.getText().toString();
writeToFile(Date);
writeToFile(Location);
writeToFile(Comment);
Intent intent = new Intent(this, Detail_Data.class);
startActivity(intent);
Date_Location.this.finish();
}
private void writeToFile(String data) {
String newline = "\r\n";
try {
OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(
FILENAME, Context.MODE_APPEND));
oswName.write(newline);
oswName.write(data);
oswName.close();
} catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
}
And my second Activity is below
public class Detail_Data extends Activity {
TextView textView1;
ImageView imageView;
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_data);
textView1 = (TextView) findViewById(R.id.textView1);
imageView = (ImageView) findViewById(R.id.imageView2);
String date = readFromFile();
textView1.setText(date);
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
public void goNext(View view) {
imageView.setColorFilter(0xFFFF3D60, PorterDuff.Mode.MULTIPLY);
Intent intent = new Intent(this, Agreement.class);
startActivity(intent);
Detail_Data.this.finish();
}
}
please if any one have any idea then help me. I have tried with other solution too but then also i am not getting last 10 records. Instead of last 10 data i am getting all the records which is written in file.
Firstly, If you are writing file on SDcard, be sure that you have added the uses-permission tag in AndroidManifest.xml
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Secondly, don't forget flush()
oswName.write(data);
oswName.flush();
oswName.close();
Then, there is something wrong with your readFromFile() method,
remove this line from while loop
stringBuilder.append(receiveString+'\n');
and add this right after the while loop
for(String str : bandWidth)
stringBuilder.append(str + "\n");
readFromFile() should be like following
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
for(String str : bandWidth)
stringBuilder.append(str + "\n");
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
After opening the input/output stream, use that methods:
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Files {
public static String readStringFile(FileInputStream fis) throws java.io.IOException {
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
}
return fileContent.toString();
}
public static void writeStringFile(FileOutputStream fos, String text) throws java.io.IOException {
fos.write(text.getBytes());
}
}
First, create the FileInputStream or FileOutputStream with your desired file name and then call the methods above. Please notice that the methods only work for reading and writing strings.
You store each line to list and remove 0 position only if list size = 10
So as 1st step store all file in list:
Instead
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
Write
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
After copy last 10 lines to new list.
For example if you have :
List<String> bandWidth = new ArrayList<String>(Arrays.asList("a1", "a2", "a3","a4", "a5", "a6","a7", "a8", "a9","a10", "a11", "a12"));
Than with subList:
List<String> bandWidth10rows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
It will copy last 10 list items to new list.
Totally it should be something like:
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
List<String> bandWidthLastTenRows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
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 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);
I had add in this remember me function inside my project, and I need to display the search result in the webview, but now everytime I click on the search button, the search content can be remembered, but the web content can not be displayed.
public class InternalStorageDemo extends Activity {
EditText txt;
Button writeBtn;
Button readBtn;
TextView tv;
WebView wv;
String FILE_NAME = "mFile";
String FILE_CONTENT;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (EditText)findViewById(R.id.txt);
writeBtn = (Button)findViewById(R.id.writeBtn);
readBtn = (Button)findViewById(R.id.readBtn);
writeBtn.setOnClickListener(listener);
readBtn.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.writeBtn:
FILE_CONTENT = txt.getText().toString().equals("")?"null":txt.getText().toString();
try {
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(FILE_CONTENT.getBytes());
fos.close();
//Toast.makeText(InternalStorageDemo.this, "stored done", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.readBtn:
FileInputStream fis;
try {
fis = openFileInput(FILE_NAME);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){}
txt.setText(new String(input));
try{
String str = txt.getText().toString();
URL url = new URL("http://epoly.tp.edu.sg/tpapp/isistt/TTServlet?txtModule=StudentSearch&txtAction=GetTT&txtSelStudentID=" + str);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
// Read the contents line by line (assume it is text),
// storing it all into one string
String content ="";
String line = reader.readLine();
while (line != null) {
//adding on to the string (+=)
//"\n" goes to a new line so that it has a break
content += line + "\n";
line = reader.readLine();
}
//close reader after reading contents
reader.close();
//using substring to get html contents from a specific tag
String myString = content.substring(content.indexOf("</script>"));
int start = myString.indexOf("</script>");
//if start less than 0, no contents from start tag found,
//nothing will be displayed in webview, error message will be logged
if (start < 0) {
Log.d(this.toString(), "Academic calendar start tag not found");
}
else {
int end = myString.indexOf("</body>", start);
if (end < 0) {
Log.d(this.toString(), "Academic calendar end tag not found");
} else {
//load only <newcollection> tag
myString = "<html><body>" + myString.substring(start, end) + "</body></html>";
}
}
//display contents that have been extracted to webview
WebView wv = (WebView)findViewById(R.id.wv);
wv.getSettings().setBuiltInZoomControls(true);
//set the webview contents' size
wv.setInitialScale(80);
//wv.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
//wv.loadData(myString, "text/html", "utf-8");
wv.loadDataWithBaseURL("http://epoly.tp.edu.sg/tpapp/isistt/TTServlet?txtModule=StudentSearch&txtAction=GetTT&txtSelStudentID="+str, myString, "text/html", "UTF-8", "about:blank");
}catch (IOException e) {
e.printStackTrace();
Log.d(this.toString(), "Error!");
}} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Log.d(this.toString(), "Error!");
}break;
}
}
};
}