Capturing part of string from a txt file? - android

I have a text file like this, separated by ";"
1022-3, 1603-4, 2012-5, 2489-6;
Gotta catch the first part before the "-" and pass to variable, and compare with milliseconds, if is equal the number, capture the number after of "-".
And do so with the next number after the semicolon, and so front.
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
And the beginning of the code to do what I need this here
private void LerArquivo() {
String lstrNomeArq;
File arq;
String lstrlinha;
long tempoInicio = 0;
long tempoDecorrido = 0;
try {
tempoDecorrido = (RecordSound.MilliSeconds() - tempoInicio);
lstrNomeArq = "/Android/data/br.com.couldsys.drumspro/cache/GravaSound.TXT";
String conteudotexto = "";
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
String capturaIndex = ("Conteudo do texto: "
+ conteudotexto.substring(
conteudotexto.indexOf("-") + 1,
conteudotexto.indexOf(";",
conteudotexto.lastIndexOf("-"))));
if (tempoDecorrido == capturatempo) {
DrumsProActivity.vsm.playSound(capturaindex);
// ler a nova linha
// se chegar ao final do string então para o while
if (conteudotexto.length() > 0) {
executar = false;
}
}
} catch (Exception e) {
trace("Erro : " + e.getMessage());
}
}

use this simpler code : create an array of substrings each contain a string formated ####-#
string[] MyStr = conteudotexto.split(',');
string sss= MyStr[0];
string sss2= MyStr[1];
....
now sss is 1022-3
sss2 is 1603-4 and so on ....
then reuse split function:
string[] MyStr2 = sss.split('-');
now we have :
MyStr2[0] = 1022
MyStr2[1] = 3

Maybe not particular elegant but just pragmatic for me - use the String split method. First split with ","
String[] parts = conteudotexto.split(",");
and then with each of the parts (here for the first)
String[] subParts = parts[0].split("-");
Just gives you everything in the pieces you need to look at and no danger get mixed up with positions etc.

What I need now is know how to catch part of text.
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
The text may vary more separation has two, the first number is separated from the second number by a "-" (dash) which is then separated by "," (comma)
549-8,1019-9,1404-3,1764-3,2208-10,2593-5,2938-9,3264-6,3700-0,4174-7,4585-8,4840-2,5192-9,5540-10,5932-0,
As has been shown
String[] parte1 = conteudotexto.split(",");
e em seguida
String[] parte2 = parte1[0].split("-");
The rule I'm trying to do is: Turn within a millisecond while the method and compare with the first part of the text
type
**If valor_milissegundos first part is equal to the number of text then
---> enters and runs the function playSound (the second number of the text);
------> goes to the next number in the text loop, capturing the second number of the text and compares it to the millisecond, if equal enters the IF block and catch the second number after the dash, and so on, until you reach the end of the text.**
Method return milliseconds calculates milliseconds
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
I hope understand why I used the google translator
thank you

Related

Divide long TextView into small parts and make a cardview around these parts | Android

I have a question: Is it possible to divide a very long text, which the app gets from the Internet in a Json-data, into small parts of the text? Then these parts should be shown in single cardviews.
If it's possible, can somebody show me how? I tried a very long time and didn't get it. Thanks for help!
EDIT
That's the jsonRequest and it builds the TextView.
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://example.com/document.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data1");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String a = obj.getString("a");
String b = obj.getString("b");
String c = obj.getString("c");
String d = obj.getString("d");
textView.append(Html.fromHtml("<p><b>" + a + "</b><br>" + b + "<br>" + c + "<br>" + d + "</p>"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}
);
requestQueue.add(jsonObjectRequest);
;
Now the TextView should be divided into small parts. In every part should be the Strings a, b, c and d. And around these small parts should be a cardview.
One attempt would be :
Break the text parts with something unique like , and then you can use
StringTokenizer tokens = new StringTokenizer(comma_string_here, ",");
String first_text = tokens.nextToken();
String second_text = tokens.nextToken();
You can loop through and set background as you desire for those text.
you can split text based on any special character or space if you provide me sample data, so I can give you proper solutions.
First let me say I think there must be a better approach to do what you want to do, but if you want to really cut a string in pieces to show it different cardviews, another way of doing it is to cut it based on a fixed number of characters.
This function will take the text and the fixed limit. And it will return an array. In the first position it will have the thext that has been cut out and in the second position the remaining text.
The cut part may fall in the middle of a word. If you don't want that, you can add some more logic using rtn[0].lastIndexOf(" ") to search for the last blank space and adjust the results accordingly.
public static String[] limitToNChars(String text, int limit){
String rtn[] = new String[2];
if(text.length() <= limit){
rtn[0] = text;
rtn[1] = "";
}else{
rtn[0] = text.substring(0,limit);
rtn[1] = text.substring(limit);
}
return rtn;
}
You can call this function in a loop pasing the result's second position as the first parameter of the function until the second position is an empty string to get all the substrings from the initial string.

Returning rows from a csv

Hi I have a csv that looks like this:
r1c1|r1c2|r1c3
r2c1|r2c2|r2c3
As you can see it is delimited by the character "|"
In my application, I am trying to explode this using input stream. Here is my code:
String line = "";
String cvsSplitBy = "|";
try {
File initialFile = new File(myfile.txt);
InputStream targetStream = new FileInputStream(initialFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(targetStream));
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(cvsSplitBy);
String c0 = RowData[0];
String c1 = RowData[1];
String c2 = RowData[2];
Toast.makeText(mainactivity.this, c2, Toast.LENGTH_LONG).show();
}
}catch (IOException ex) {
// handle exception
}
Unfortunately, this appears to return each character in the csv as a row. The toast example above returns 1 then 2.
Any ideas how to return the proper column, anyone?
split() splits string around matches of the given regular expression, therefore use of special character (and vertical bar is one of these) requires escaping to strip its "powers".
String cvsSplitBy = "\\|"
See docs: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

TalkBack decimal announcements

I'm having a problem with Talkback. In my string I have the following number.
1,827
it's a Dutch number so the number means:
1 euro and 82,7 cents.
But Talkback is saying:
18 hundred and 27 euro.
So this problem only occurs when I have a number with more than 2 decimals. How to fix this issue?
---EDIT---
When I'm reading this page: https://english.stackexchange.com/questions/62397/reading-out-decimal-numbers-in-english
it seems I must pronounce the number 1,827 as the following:
one point eight two seven instead to act if it is a number. How to do this?
---EDIT---
I included the following:
StringTokenizer stringTokenizer = new StringTokenizer(value, ".");
String currencyBeforeComma = null;
String currencyAfterComma = null;
while (stringTokenizer.hasMoreTokens()) {
currencyBeforeComma = stringTokenizer.nextToken();
currencyAfterComma = stringTokenizer.nextToken();
}
result = currencyBeforeComma + " point " + currencyAfterComma;
So now its pronouncing: one point eighthunderd twentyseven. So this is still now what i want.
---EDIT---
String value = 1,827;
String result = "";
for (Character chars : value.toCharArray()) {
result = result + chars + " ";
}
String replace = result.replace(getResources().getString(R.string.accessibility_decimal_separator), getResources().getString(R.string.accessibility_decimal_separator_text));
return replace;
This is what i did. I created a whitespace for every char in the value string and for the , or . I replaced it with a comma or point text.
This works for now but it isn't a clean solution. If anybody else has a better solution, please share
Try this and modify your as per your requirement
TextView currencylbl = (TextView) findViewById(R.id.currencylbl);
boolean countryCurrency = true;
String currency = "1,827";
if(countryCurrency==true && currency.contains(",")){
StringTokenizer stringTokenizer = new StringTokenizer(currency, ",");
String currencyBeforeComma = null;
String currencyAfterComma = null;
while (stringTokenizer.hasMoreTokens()) {
currencyBeforeComma = stringTokenizer.nextToken();
currencyAfterComma = stringTokenizer.nextToken();
currencylbl.setText(currency);
}
Double double1 = Double.parseDouble(currencyAfterComma);
double1 = Double.parseDouble(currencyBeforeComma)+double1/1000;
currencylbl.setContentDescription(double1+"");
}
countryCurrency refers to particular Country currency boolean.
Also modify as per your requirement.
Double double1 = Double.parseDouble(currencyAfterComma);
double1 = Double.parseDouble(currencyBeforeComma)+double1/1000;
currencylbl.setContentDescription(double1+"");
xml is
<TextView
android:id="#+id/currencylbl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
/>

Getting OutOfBoundsException while pagination a String

I am creating an epub reader for android. For the pagination part, I am trying to get the whole string content and then search for space in the string. Then I get the text height and compare it with the screen height. if still (text height < screen height) I loop through the string and do the same thing in a while loop.
Every thing went well, but when it comes to the end of the string I get IndexOutOfBoundsException. I have attached the screenshot of the Logcat below.
The code I used to get the no of pages is like this
public String getNoOfPages(String text){
String remainingString = "";
try{
int screenHeight = getScreenHeight();
String originalText = text;
String strToModify = text;
StringBuilder newString = new StringBuilder();
StringBuilder oldString = new StringBuilder();
int startIndex = 0;
String strToFind = " ";
int index = strToModify.indexOf(strToFind,startIndex);
newString.append(originalText.substring(startIndex, index+1));
oldString.append(newString.toString());
startIndex = index+1;
int textHeight = getTextHeight(newString.toString());
while(textHeight < screenHeight){
index = strToModify.indexOf(strToFind,startIndex);
oldString.replace(0,oldString.toString().length(),newString.toString());
newString.append(originalText.substring(startIndex, index+1));
startIndex = index+1;
textHeight = getTextHeight(newString.toString());
}
remainingString = originalText.substring(oldString.length()-1,originalText.length());
}catch(Exception e){
Log.d("chathura123","Error in getNoOfPages " );
e.printStackTrace();
}
return remainingString;
}
The logic is when the remaining string is an empty string("") ,it means that is the end of the content of the page. So I want to check until it returns an empty string.
The above method is called inside another while loop. (In Async Task)
String tmp = null;
try{
tmp = reader.getNoOfPages(content);
while (!tmp.equals("")) {
tmp = reader.getNoOfPages(tmp);
page_count++;
if(page_count==80){
Log.d("chathura123", "80 th iteration");
}
Log.d("chathura123", "inside while "+page_count);
}
}catch(Exception e){
Log.d("chathura123", "error occured in getPageCount");
}
What is the wrong with this? Why I am getting OutOfBoundsException?
Thank you.
may be on the last line, when there are no characters there is an error for originalText.substring(startIndex, index+1) what if originalText doesnt have index+1 length/index.

How can I effectively replace one or more characters

I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);

Categories

Resources