I want to show the whole c program on screen in android - android

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();
}
}

Related

How to create a string / string array from a .txt/.xml file?

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");

Parsing XML error, arrayindexoutofbounds exception.

I'm trying to parse some XML to a string and I'm getting an outofbounds exception. I'm fairly new to android as well as trying to get text from a website, namely the CTA Bus Tracker API . One block of the XML looks like this:
<route>
<rt>1</rt>
<rtnm>Bronzeville/Union Station</rtnm>
</route>
This is my method:
class loadRoutes extends AsyncTask<String, String, String[]> {
#Override
protected String[] doInBackground(String... strings) {
try {
URL routesURL = new URL(strings[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(routesURL.openStream()));
String [] result = new String[2];
String line;
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
in.readLine();
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
in.close();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
The first readline() gets to the line with an rt and grabs that line, then in the if statement, readline() should get the next line, which should contain rtnm. I keep getting indexoutofbounds on the line firstPos = line.indexOf("rtnm").
The while loop is already reading in the next line, so you don't need to in.readLine(); in the if statement. Try running it like this:
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
} else if (line.contains("<rtnm>") {
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
Also, it might be easier to write your own XML parser in a different class. This XML parser android documentation has an example of exactly what you are trying to do.

How to identify textview reached the bottom of screen?

I am developing book reader application. I have LinearLayout.
<LinearLayout
android:id="#+id/llReader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical" >
</LinearLayout>
I am taking html files from internal storage line by line. I am assigning one text view for one line and putting them into LinearLayout.
private void readFile(LinearLayout ll) throws IOException {
fileName = myDatabase.getBookById(book_id) + ".html";
FileInputStream fis = openFileInput(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = "";
while (null != (line = br.readLine())) {
TextView tv = new TextView(this);
tv.setTextSize(24);
tv.setText(Html.fromHtml(line));
ll.addView(tv);
}
br.close();
}
How to identify that TextViews reached the bottom of the screen?
You can via pixel manipulation:
private void readFile(LinearLayout ll) throws IOException {
fileName = myDatabase.getBookById(book_id) + ".html";
FileInputStream fis = openFileInput(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = "";
int parentHeight = ll.getHeight(); // in pixels
int sumHeigth = 0;
while (null != (line = br.readLine())) {
TextView tv = new TextView(this);
tv.setTextSize(24);
tv.setText(Html.fromHtml(line));
ll.addView(tv);
sumHeigth += tv.getHeight();
if(sumHeigth>parentHeight) {
// if can't fit in LinearLayout
ll.removeView(tv);
// break; // or what you want in this situation
}
}
br.close();
}

How to create listview with links to assets html file?

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.

How to read whole chapter from epub files?

I want to make epub reader app.Now i am getting only chapter name in the file but how to get whole data in the chapter.
I think I have already posted this out before.
Using nl.siegmann.epublib which you can google.
In my code I will show you how I did it as you look at Book class which shows how the the epub works.
Using Spine on book class I get the maximum spine of the book which means the entire book.
I then convert it to string.
Here is my code on how I did it.
public String getEntireBook()
{
String line, linez = null;
Spine spine = amBook().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;
}

Categories

Resources