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