Remove first 3 letters from String in list Dart - android

I want to remove the first 3 letters from every item (String) in my List.
My Listitems look like this:
{2: test1.mp4
3: test2.mp4
4: test3.mp4
10: test4.mp4
11: test5.mp4
I want to remove the "{2: " from the firs item and for every other item i want to remove the number + the space, so that i only have the file name.

the substring method is the solution for your case :
String text = "11: test5.mp4";
String result = text.substring(3); // test5.mp4
and if you just want to remove extra space on sides, use trim method
String text = " test5.mp4 ";
String result = text.trim(); // test5.mp4

It will probably be better to use split() instead of trimming off the white space and using a set index.
const track = '11: test5.mp4';
final splitted = track.split(': ');
print(splitted); // [11, test5.mp4];

Currently it's a little bit unclear how your list looks exactly. I am assuming, you have the following list:
List<String> myList = [
"2: test1.mp4",
"3: test2.mp4",
"4: test3.mp4",
"10: test4.mp4",
"11: test5.mp4",
];
In this case, it's not necessarily only the first 3 letters that you want to remove. A scalable solution would be the following:
final List<String> myList = [
"2: test1.mp4",
"3: test2.mp4",
"4: test3.mp4",
"10: test4.mp4",
"11: test5.mp4",
];
//We are splitting each item at ": ", which gives us a new array with two
//items (the number and the track name) and then we grab the last item of
//that array.
final List<String> myFormatedList = myList.map((e) => e.split(": ").last).toList();
print(myFormatedList);
//[test1.mp4, test2.mp4, test3.mp4, test4.mp4, test5.mp4]

Related

Google Sheets API v4 - How to get the last row with value?

How to get the last row with value in the new Google Sheets API v4 ?
i use this to get a range from a sheet:
mService.spreadsheets().values().get("ID_SHEET", "Sheet1!A2:B50").execute();
how to detect the last row with value in the sheet ?
You can set the range to "A2:D" and this would fetch as far as the last data row in your sheet.
I managed to get it by counting the total rows from current Sheets.
Then append the data to the next row.
rowcount = this.mService.spreadsheets().values().get(spreadsheetId, range).execute().getValues().size()
Rather than retrieving all the rows into memory just to get the values in the last row, you can use the append API to append an empty table to the end of the sheet, and then parse the range that comes back in the response. You can then use the index of the last row to request just the data you want.
This example is in Python:
#empty table
table = {
'majorDimension': 'ROWS',
'values': []
}
# append the empty table
request = service.spreadsheets().values().append(
spreadsheetId=SPREADSHEET_ID,
range=RANGE_NAME,
valueInputOption='USER_ENTERED',
insertDataOption='INSERT_ROWS',
body=table)
result = request.execute()
# get last row index
p = re.compile('^.*![A-Z]+\d+:[A-Z]+(\d+)$')
match = p.match(result['tableRange'])
lastrow = match.group(1)
# lookup the data on the last row
result = service.spreadsheets().values().get(
spreadsheetId=SPREADSHEET_ID,
range=f'Sheetname!A{lastrow}:ZZ{lastrow}'
).execute()
print(result)
😢 Google Sheets API v4 does not have a response that help you to get the index of the last written row in a sheet (row that all cells below it are empty). Sadly, you'll have to workaround and fetch all sheet rows' into memory (I urge you to comment if I'm mistaken)
Example:
spreadsheet_id = '1TfWKWaWypbq7wc4gbe2eavRBjzuOcpAD028CH4esgKw'
range = 'Sheet1!A:Z'
rows = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range).execute().get('values', [])
last_row = rows[-1] if rows else None
last_row_id = len(rows)
print(last_row_id, last_row)
Output:
13 ['this', 'is ', 'my', 'last', 'row']
💡 If you wish to append more rows to the last row, see this
You don't need to. Set a huge range (for example A2:D5000) to guarantee that all your rows will be located in it. I don't know if it has some further impact, may be increased memory consumption or something, but for now it's OK.
private List<String> getDataFromApi() throws IOException {
String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
String range = "A2:D5000";
List<String> results = new ArrayList<String>();
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
results.add("Name, Major");
for (List row : values) {
results.add(row.get(0) + ", " + row.get(3));
}
}
return results;
}
Look at the loop for (List row : values). If you have two rows in your table you will get two elements in values list.
Have a cell somewhere that doesn't interfere with your datarange with =COUNTA(A:A) formula and get that value.
In your case
=MAX(COUNTA(A:A50),COUNTA(B:B50))
?
If there could be empty cells inbetween the formula would be a little more tricky but I believe it saves you some memories.
2022 Update
I I don’t know if this will be relevant for someone in 2022, but now you can do it differently.
You can just set next value as range :
const column = "A"
const startIndex = 2
const range = column + startIndex + ":" + column
In resolve you get all data in column and range with last index.
I tested it on js and php
Following Mark B's answer, I created a function that performs a dummy append and then extracts the last row info from the dummy append's response.
def get_last_row_with_data(service, value_input_option="USER_ENTERED"):
last_row_with_data = '1'
try:
dummy_request_append = service.spreadsheets().values().append(
spreadsheetId='<spreadsheet id>',
range="{0}!A:{1}".format('Tab Name', 'ZZZ'),
valueInputOption='USER_ENTERED',
includeValuesInResponse=True,
responseValueRenderOption='UNFORMATTED_VALUE',
body={
"values": [['']]
}
).execute()
a1_range = dummy_request_append.get('updates', {}).get('updatedRange', 'dummy_tab!a1')
bottom_right_range = a1_range.split('!')[1]
number_chars = [i for i in list(bottom_right_range) if i.isdigit()]
last_row_with_data = ''.join(number_chars)
except Exception as e:
last_row_with_data = '1'
return last_row_with_data

How to get specific items using jsoup

I'm using this code to select a URL in div tag
Elements mElements = doc.select("a[class^=titr]");
Element linkElement = mElements.select("a").first();
linkElement.attr("href");
but in this cod I just can see first item Because the method is first();
how can I specific that I want to select for example item 0 to 20 instead of first ??
The mElements is returned as a List<Element> - try mElements.get(0) for each one; for all of them iterated:
print("\nElements: (%d)", mElements.size());
for (Element link : mElements) {
print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel"));
}
http://jsoup.org/apidocs/org/jsoup/select/Elements.html
This is however probably not recommended, since arrays change over time; perhaps you want a better selector method.
http://jsoup.org/cookbook/extracting-data/selector-syntax

Delete spaces from Editable object

I have deleted characters in edittext objects with this code
edit = etcalle.getEditableText();
if (edit.length() > 0)
edit.delete(edit.length() - 1, edit.length());
It has been working but when my string looks like this +81 901 it doesn't delete the space. It gets to it and stops deleting characters.
How can I remove the space in my text?
EDIT:
Just to be clear, I don't want to remove everything at once. Just one character at every time I hit my delete button
String original = etcalle.getText().toString();
then
etcalle.setText(original.substring(0,original.length-1));
of course be sure to check that the original is not null or length < 1
use this it will remove all the spaces
String str = "99 85263 9633";
str.replace(" ", ""); // Output is 99852639633
Then Its magic you can do this with this
String str = "99 85263 9633";
str.replaceFirst(" ",""); // Output is 9985263 9633

Removing newline from string

Here's my issue:
I have a database and it is full of episodes of a tv show. One column denotes the episode number. I want to display the episodes in a list like this:
Episode 1
Episode 2
Episode 3
etc.
I'm using my own adapter class that extends SimpleCursorAdapter to do this...
Since I had formatting errors I am using Android.R.layout.simple_list_item_1 and Android.R.id.text1
Basically the only reason I have a custom adapter is so I can do something like this:
textView.setText("Episode " + cursor.getString("column_for_episode_number");
The problem is, I get a list that looks like this:
Episode
1
Episode
2
Episode
3
When I try something like this(which worked in a different portion of my code):
String text = "Episode " + cursor.getString("blah");
text = text.replaceAll("\\n","");
I get the exact same list output :(
Why don't I use create a custom view with two textboxes next to each other? It is hard for me to get that to look pretty :/
text.replaceAll(System.getProperty("line.separator"), "");
There is a mistake in your code. Use "\n" instead of "\\n"
String myString = "a string\n with new line"
myString = myString.replaceAll("\n","");
Log.d("myString",myString);
Check if there is new line at the beginning before you replace and do the same test again:
for(int i=0; cursor.getString("blah").length()-1; i++)
{
if(cursor.getString("blah").charAt(i)=='\\n') <-- use the constant for the line separator
{
Log.i("NEW LINE?", "YES, WE HAVE");
}
}
Or use the .contains("\n"); method:
Check the xml for the width of the textview as well.
Why are you using getString() when you are fetching an integer? Use getInt() and then use Integer.toString(theint) when you are setting the values in a textview.
This could help you:
response = response.replaceAll("\\s+","");
It sounds like you are hitting wrapping issues rather than newline issues. Change this:
String text = "Episode " + cursor.getString("blah");
To this:
String text = "Episode" + cursor.getString("blah");
And see if that changes the output. Post your layout xml please?
this worked for my (on android 4.4):
(where body is a string with a newline entered from an EditText view on handset)
for (int i=0; i<body.length(); i++) {
if (body.charAt(i) == '\n' || body.charAt(i) == '\t') {
body = body.substring(0, i) + " " + body.substring(i+1, body.length());
}
}
have you tried
cursor.getString("blah").trim()

Android String Not Equal

I am brand new to Java and Android so I am sure this will be an easy question/answer. I know that to find out if a string is equal to another string you use the equal function. In my situation, I am scanning a QR Code where the result of the scan is Similar to "EMPLOYEE~~John Smith~~DIVISION~~Maintenance". I need to know how to do the following:
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
// Do Something
}
In the example Java Code, myJunk[0] never equals val1. What am I doing wrong?
i've tried this and it works , so try to display the contents variable , probably the problem is in the extras , try to display it in logCat :
String contents = "EMPLOYEE~~John Smith~~DIVISION~~Maintenance";
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
Toast.makeText(this, "val1 = "+val1, Toast.LENGTH_LONG).show();
Toast.makeText(this, "val2 = "+myJunk[1], Toast.LENGTH_LONG).show();
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
Toast.makeText(this, "equals", Toast.LENGTH_LONG).show();
}
Your string is:
EMPLOYEE~~John Smith~~DIVISION~~Maintenance
So after spliting, myJunk[0] will contain EMPLOYEE (notice the space in front of the word EMPLOYEE).
So before comparing , you will need to trim your value
The method i usually use, is to print out my variables when in doubt. So if you are unsure of where the problem is, you could try something like this.
(It requires you to be able to see the output, in logcat for example)
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
System.out.println("contents is "+contents );
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
System.out.println("Array size is "+myJunk.length);
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
for(int i=0; i < myJunk.length; i++) {
System.out.println("String "+i+ "in array is: "+myJunk[i]);
}
//Here i run through the array and print every element.
if (myJunk[0].equals(val1)){
// Do Something
}
It is a bit overkill, but this is mostly to show one way of getting all the information you need to find the problem :)

Categories

Resources