I have an activity which I want to show ListView with list of topics, which linked to html files in assets folder.
Here is a code for files from res/raw folder (they named as n0.txt, n1.txt etc.):
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();
}
}
How can I do this for html files from assets (they named n0.html etc)?
To get an InputStream to a file from your assets you could use :
InputStream is=getAssets().open("n0.txt");
then you should process the stream as you did with your raw resources.
Related
I know it has been asked a million times, but I just can't find anything that Works, and I just started learning to code
I'm trying to use regex to tell when the user types any of 118 different patterns, so you can guess it'd be a really long string, and I have all the patterns in a .txt/.xml file and I want to create a string or array with these patterns
The code:
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private EditText et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
et3 = (EditText)findViewById(R.id.et3);
}
public void boton (View view){
String text = et3.getText().toString();
//String[] symbolsArr = {"He|","H|","Os|","O"};
//StringBuffer sb = new StringBuffer();
//for(int i = 0; i < symbolsArr.length; i++) { //all of this is just to convert an array to a single string
// sb.append(symbolsArr[i]);
//
String symbols = "Zr|Zn|Yb|Y|Xe|W|V|U|Ts|Tm|Tl|Ti|Th|Te|Tc|Tb|Ta|Sr|Sn|Sm|Si|Sg|Se|Sc|Sb|S|Ru|Rn|Rh|Rg|Rf|Re|Rb|Ra|Pu|Pt|Pr|Po|Pm|Pd|Pb|Pa|P|Os|Og|O|Np|No|Ni|Nh|Ne|Nd|Nb|Na|N|Mt|Mo|Mn|Mg|Md|Mc|Lv|Lu|Lr|Li|La|Kr|K|Ir|In|I|Hs|Ho|Hg|Hf|He|H|Ge|Gd|Ga|Fr|Fm|Fl|Fe|F|Eu|Es|Er|Dy|Ds|Db|Cu|Cs|Cr|Co|Cn|Cm|Cl|Cf|Ce|Cd|Ca|C|Br|Bk|Bi|Bh|Be|Ba|B|Au|At|As|Ar|Am|Al|Ag|Ac";
//The really long string with all the patterns
Pattern p = Pattern.compile(symbols);
Matcher m = p.matcher(text);
tv1.setText("");
while (m.find()){
tv1.append("found " + m.group() + "\n");
}
}
}
It depends of how do you want to storage the file.
For example let`s use assets.
Put file data.txt in assets(you can create this in File/New/Folder/Assets Folder)
After that you can create method, wich help you to get string from assetFile
public String getStringFromAssetFile(Context context, String nameFile)
{
String str = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(nameFile)));
String line;
while ((line = reader.readLine()) != null) {
str += line;
}
} catch (IOException ex) {
ex.printStackTrace();
}
return str;
}
Now you can use this method to create a string or array with these patterns
String symbols = getStringFromAssetFile(MainActivity.this, "data.txt");
I'm using internal storage to store multiple strings entered by the user through multiples edit text.
So the layout is composed of multiples Textviews which correspond to the title of the fields, and multiples Edittexts which correspond to the fields where the user can enter his string.
When the user has finished, he presses the save button and this function is triggered :
public void save(View view) // SAVE
{
File file= null;
String name = editname.getText().toString()+"\n";
String marque = editmarque.getText().toString()+"\n";
String longueur = editlongueur.getText().toString()+"\n";
String largeur = editlargeur.getText().toString()+"\n";
String tirant = edittirant.getText().toString()+"\n";
String immatri = editImmatriculation.getText().toString()+"\n";
String port = editPort.getText().toString()+"\n";
String contact = editContact.getText().toString()+"\n";
String panne = editPanne.getText().toString()+"\n";
String poste = editPoste.getText().toString()+"\n";
String police = editPolice.getText().toString()+"\n";
String assurance = editAssurance.getText().toString();
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(name.getBytes());
fileOutputStream.write(marque.getBytes());
fileOutputStream.write(longueur.getBytes());
fileOutputStream.write(largeur.getBytes());
fileOutputStream.write(tirant.getBytes());
fileOutputStream.write(immatri.getBytes());
fileOutputStream.write(port.getBytes());
fileOutputStream.write(contact.getBytes());
fileOutputStream.write(panne.getBytes());
fileOutputStream.write(poste.getBytes());
fileOutputStream.write(police.getBytes());
fileOutputStream.write(assurance.getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Than, in another file I retrieve this data through another button that triggers this function :
public void load(View view)
{
try {
FileInputStream fileInputStream = openFileInput("Code.txt");
int read = -1;
StringBuffer buffer = new StringBuffer();
while((read =fileInputStream.read())!= -1){
buffer.append((char)read);
}
fileInputStream.close();
String tab[] = buffer.toString().split("\n");
String boatname = tab[0];
String marque = tab[1];
String longueur = tab[2];
String largeur = tab[3];
String tirant = tab[4];
String immatri = tab[5];
String port = tab[6];
String contact = tab[7];
String panne = tab[8];
String poste = tab[9];
String assurance = tab[10];
String police = tab[11];
getboatname.setText(boatname);
getmarque.setText(marque);
getlongueur.setText(longueur);
getlargeur.setText(largeur);
getTirantdeau.setText(tirant);
getImmatriculation.setText(immatri);
getPort.setText(port);
getContact.setText(contact);
getPanne.setText(panne);
getPoste.setText(poste);
getAssurance.setText(assurance);
getPolice.setText(police);
} catch (Exception e) {
e.printStackTrace();
}
}
So in the save function I'm splitting the entered strings with \n, and I save the file to the internal storage, and in the load function I retrieve the strings using an array and splitting with every \n and I set the text with the correct index.
What I don't understand is that the results are all mixed up, the string of the first field is displayed in the last field for example, why ?
You can Make a Single String and write it. Also, use a different separator. You can use StringBuffer for it.
StringBuffer s=new StringBuffer();
s.append(editname.getText().toString());
s.append("##########");
s.append(editmarque.getText().toString());
s.append("##########");
s.append(editlongueur.getText().toString());
s.append("##########");
s.append(editlargeur.getText().toString());
s.append("##########");
s.append(edittirant.getText().toString());
s.append("##########");
s.append(editPort.getText().toString());
s.append("##########");
s.append(editContact.getText().toString());
s.append("##########");
s.append(editPanne.getText().toString());
s.append("##########");
s.append(editPoste.getText().toString());
s.append("##########");
s.append(editPolice.getText().toString());
s.append("##########");
s.append(editAssurance.getText().toString());
s.append("##########");
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(s.toString().getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When you get FileInputStream split the String with this "##########" vlaue
this is the example text int text file
title: get this string and
desc: get this string
I want to split it with "title:" and "desc:"
it is simple :
after getting file content (https://stackoverflow.com/a/14768380/1725748), do :
String mystring= "title: xxxxxx desc: yyyyy";
String[] splits = mystring.split("title:|desc:");
splits[0] // is the title
splits[1] // is the description
There are various ways to get a String how you like, here I found the index of desc and split the String where desc appears:
try{
InputStream inputStream = getResources().openRawResource(R.raw.textfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
String title_content, desc_content;
// Read each line
while((line = reader.readLine( )) != null)
{
// title: get this string and desc: get this string
// ^
// (desc_location)
int desc_location;
if((desc_location = line.indexOf("desc:")) > 0)
{
title_content = line.substring(0, desc_location);
desc_content = line.substring(desc_location, line.length( ));
}
}
} catch (Exception e) {
// e.printStackTrace();
}
I am creating a book reader using siegmann epub library. I am not able to display anything on the screen but in the logcat. What type of layout to use for display?
Here is my main.java
public class MainActivity extends Activity {
private WebView webview;
private String line, line1="", finalstr="";
int i = 0;
private String fullBook;
private Book book;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
AssetManager assetManager = getAssets();
try{
//find input Stream for book
InputStream epubInputStream = assetManager.open("oliver_twist.epub");
//Load book from input stream
book = (new EpubReader()).readEpub(epubInputStream);
Log.i("epublib", "title: "+book.getTitle());
//Log the book's cover image property
//Bitmap coverImage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
//Log.i("epublib", "CoverImage is" + coverImage.getWidth()+" by "+coverImage.getHeight()+" pixels");
//Log the tables of contents
logTableOfContents(book.getTableOfContents().getTocReferences(),0);
fullBook = getEntireBook();
}
catch(IOException e){
Log.e("epublib", e.getMessage());
}
String javascrips = "";
try {
// InputStream input = getResources().openRawResource(R.raw.lights);
InputStream input = this.getAssets().open(
"poe-fall-of-the-house-of-usher.epub");
int size;
size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
javascrips = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
// String html = readFile(is);
webview.loadDataWithBaseURL("file:///android_asset/", javascrips,
"application/epub+zip", "UTF-8", null);
//webview.setwe
}
private void logTableOfContents(List<TOCReference> tocReferences, int depth){
if(tocReferences == null){
System.out.println("---->>>"+tocReferences);
return;
}
for(TOCReference tocReference:tocReferences){
StringBuilder tocString = new StringBuilder();
for(int i=0;i<depth;i++){
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
Log.i("epulib", tocString.toString());
try {
InputStream is = tocReference.getResource().getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while ((line = r.readLine()) != null) {
// line1 = Html.fromHtml(line).toString();
Log.v("line" + i, Html.fromHtml(line).toString());
// line1 = (tocString.append(Html.fromHtml(line).toString()+
// "\n")).toString();
line1 = line1.concat(Html.fromHtml(line).toString());
}
finalstr = finalstr.concat("\n").concat(line1);
Log.i("Content " + i, finalstr);
i++;
} catch (IOException e) {
}
logTableOfContents(tocReference.getChildren(), depth+1);
}
webview.loadDataWithBaseURL("", finalstr, "text/html", "UTF-8", "");
}
public String getEntireBook(){
String line, linez = null;
Spine spine = book.getSpine();
Resource res;
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
int start = 0;
StringBuilder string = new StringBuilder();
for (int i = start; count > i; i = i +1) {
res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
return linez;
}
}
In main.xml, I have just created a webview. What otehr elemnets I can add? Is it a text view on which book is displayed?
I solved it using the following code and it worked!!
public class MainActivity extends Activity {
private WebView webview;
private String line, line1="", finalstr="";
int i = 0;
private String fullBook;
private Book book;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
AssetManager assetManager = getAssets();
//tv = (TextView) findViewById(R.id.tv);
try{
//find input Stream for book
InputStream epubInputStream = assetManager.open("TheThreeBears.epub");
//Load book from input stream
book = (new EpubReader()).readEpub(epubInputStream);
Log.i("epublib", "title: "+book.getTitle());
//Log the book's cover image property
// Bitmap coverImage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
//Log.i("epublib", "CoverImage is" + coverImage.getWidth()+" by "+coverImage.getHeight()+" pixels");
//Log the tables of contents
logTableOfContents(book.getTableOfContents().getTocReferences(),0);
getEntireBook();
}
catch(IOException e){
Log.e("epublib", e.getMessage());
}
}
private void logTableOfContents(List<TOCReference> tocReferences, int depth){
// Load entire text into particular no. of lines and display each
// then with next button navigate through pages
String lineXX = "p";
if(tocReferences == null){
System.out.println("---->>>"+tocReferences);
return ;
}
for(TOCReference tocReference:tocReferences){
StringBuilder tocString = new StringBuilder();
for(int i=0;i<depth;i++){
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
//tv.setText(tocString.toString());
//Log.i("epulib", tocString.toString());
try {
InputStream is = tocReference.getResource().getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while ((line = r.readLine()) != null) {
//String lineX = Html.fromHtml(line).toString();
//lineXX = lineX;
Log.v("line" + i, Html.fromHtml(line).toString());
line1 = line1.concat(Html.fromHtml(line).toString());
}
finalstr = finalstr.concat("\n").concat(line1);
//tv.setText(finalstr);
//Log.i("Content " + i, finalstr);
i++;
} catch (IOException e) {
}
logTableOfContents(tocReference.getChildren(), depth+1);
}
//return lineXX;
webview.loadDataWithBaseURL("", finalstr, "text/html", "UTF-8", "");
}
public void getEntireBook(){
String line, linez = null;
Spine spine = book.getSpine();
Resource res;
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
int start = 0;
StringBuilder string = new StringBuilder();
for (int i = start; count > i; i = i +1) {
res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
webview.loadData(linez, "text/html", "utf-8");
}
}
I wanted to show the whole c program on screen which should be visible to user.
I used textView but i am getting errors as the code contains special symbols.
for example:
android:text=" #include <stdio.h>
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x;
x = y;
y = temp;
printf("After Swapping\nx = %d\ny = %d\n",x,y);
return 0;
}" />
I also want that the user should be able to scroll the code as the codes may be larger than the example.I am a noob so please suggest me any alternate for the textView to display the code.
Save your C code in a file in assets folder, for example "res/assets/code.c".
Write a function that reads the content of a file to a String:
private String readFileInAssetsDir(String filename) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(filename)));
String line;
while((line = br.readLine()) != null)
sb.append(line + "\n");
} catch(Exception e) {
// TODO
}
return sb.toString();
}
And now define a WebView (not a TextView) in your layout (the advantages are that you can show any character, and WebView provides zoom and scroll directly):
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
And finally I would enclose all C code in a <pre></pre> tag and then show it inside the WebView widget:
String plainCode = readFileInAssetsDir("code.c");
String htmlCode = "<pre>" + plainCode + "</pre>";
webView.loadDataWithBaseURL("", htmlCode, "text/html", "utf-8", "");
EDIT: THIS WORKS BUT READS ONLY A SINGLE LINE OF THE TEXT IN THE TXT FILE
String line;
TextView view;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addingprogrammultipletimes);
AssetManager am = getAssets();
try {
InputStream is = am.open("add.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine();
view = (TextView) findViewById(R.id.textView);
view.setText(line);
} catch (Exception e) {
e.printStackTrace();
}
}