Hi i am reading sqlite db data and store into string buffer. I want to display it in the list view in android. i am facing little problem. please help me to solve this issue.
String studentno=cursor.getString(1);
String date=cursor.getString(2);
buffer.append("student: "+studentno+" Time:"+date+"\n");
String data=buffer.toString();
Log.d("student: "+studentno+" Time:"+date);
the output is:student: 1234 Time:12:13
student: 1234 Time:12:14
student: 1234 Time:12:15
I want to store string buffer like this
values[0]=student: 1234 Time:12:13
values[1]=student: 1234 Time:12:14
values[2]=student: 1234 Time:12:15
i tried below coding but its not working.
String[] values = data.split("");
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
is there any way to do this. thanks in advance.
You seem to be adding the data into the buffer with new line delimiter at the end. Splitting them should look like this: data.split("\n");
This does not seem like a good idea, however. Mainly because you can have a very large data set and split is an expensive operation.
Why not create an ArrayList<String> and call list.add("student: " + studentno + " Time: " + date) or some other more efficient structure?
Code:
List<String> list = new ArrayList<String>();
String studentno=cursor.getString(1);
String date=cursor.getString(2);
list.add("student: " + studentno + " Time: " + date);
This makes no sense. If you want to store the data in an array, don't store it in a StringBuffer in the first place. Store it directly in the array.
You must have some loop in which you read the data :
String[] arr = new String [...];
int count = 0;
while (cursor.next() && count < arr.length) {
String studentno=cursor.getString(1);
String date=cursor.getString(2);
arr[count] = "student: "+studentno+" Time:"+date+"\n";
count++;
}
You could try to replace your split call with this:
String[] values = data.split("\n");
Related
I have a CSV file generated in other platform (Salesforce), by default it seems Salesforce is not handling break lines in the file generation in some large text fields, so in my CSV file I have some rows with break lines like this that I need to fix:
"column1","column2","my column with text
here the text continues
more text in the same field
here we finish this","column3","column4"
Same idea using this piece of code:
List<String> listWords = new ArrayList<String>();
listWords.add("\"Hi all");
listWords.add("This is a test");
listWords.add("of how to remove");
listWords.add("");
listWords.add("breaklines and merge all in one\"");
listWords.add("\"This is a new Line with the whole text in one row\"");
in this case I would like to merge the elements. My first approach was to check for the lines were the last char is not a ("), concatenates the next line and just like that until we see the las char contains another double quote.
this is a non working sample of what I was trying to achieve but I hope it gives you an idea
String[] csvLines = csvContent.split("\n");
Integer iterator = 0;
String mergedRows = "";
for(String row:csvLines){
newCsvfile.add(row);
if(row != null){
if(!row.isEmpty()){
String lastChar = String.valueOf(row.charAt(row.length()-1));
if(!lastChar.contains("\"")){
//row += row+" "+csvLines[iterator+1].replaceAll("\r", "").replaceAll("\n", "").replaceAll("","").replaceAll("\r\n?|\n", "");
mergedRows += row+" "+csvLines[iterator+1].replaceAll("\r", "").replaceAll("\n", "").replaceAll("","").replaceAll("\r\n?|\n", "");
row = mergedRows;
csvLines[iterator+1] = null;
}
}
newCsvfile.add(row);
}
iterator++;
}
My final result should look like (based on the list sample):
"Hi all This is a test of how to remove break lines and merge all in one"
"This is a new Line with the whole text in one row".
What is the best approach to achieve this?
In case you don't want to use a CSV reading library like #RealSkeptic suggested...
Going from your listWords to your expected solution is fairly simple:
List<String> listSentences = new ArrayList<>();
String tmp = "";
for (String s : listWords) {
tmp = tmp.concat(" " + s);
if (s.endsWith("\"")){
listSentences.add(tmp);
tmp = "";
}
}
Thanks for reading this. I'm currently making a phonebook project which required me to use only one array to store values. My question is how can you split a String inside of an array into two value? So I can search someone's name and get their name and number.
You can simply use the String#split method on any element of the array, whose delimiter can be any character. Here is an example where I chose : to be the delimiter.
String[] information = { "Castiel Li:123-456-7890" };
String[] args = information.split(":");
String name = args[0];
String phoneNumber = args[1];
If you have an array like the following:
String[] records = {"Bob, 1", "Mary, 2", "Castiel, 3"};
Then you can iterate over the record array in a loop and apply the String#split() method to each String object. In this case, the delimiter (character that separates tokes) in each string is the ',', so for a given String "name, number", you'd do:
String[] oneRecord = records[i].split(',');
Where oneRecord[i] would contain the two String objects "name" and "number"
You haven't given sample inputs and outputs. But I think you are saying that you are storing the phone book in a single dimension array like following:
String[] array = {"Abc123", "xyz234", "pqr343"};
You can try something like following:
String phone1 = array[0].replaceAll("[^0-9]", "");
String name1 = array[0].replaceAll("[0-9]", "");
System.out.println(name1 + " " + phone1);
Something like this perhaps that use str.split()
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String phoneBook[] = new String[2];
phoneBook[0] = "John 1234567";
phoneBook[1] = "Max 2345678";
System.out.println(Arrays.toString(phoneBook));
for(String contact : phoneBook)
System.out.println("Name: " + contact.split(" ")[0] + " Phone Number: " + contact.split(" ")[1]);
}
}
Output:
[John 1234567, Max 2345678]
Name: John Phone Number: 1234567
Name: Max Phone Number: 2345678
Try it here!
I need to make a program that let's you add CD titles, remove them etc.
I need to use an Arraylist for my program (to store the songs)
Code:
ArrayList songlist = new ArrayList();
Collections.addAll(songlist, "Something", "Hard Days Night", "I am the Walrus", "Yesterday", "All the Lonely People");
Collections.sort(songlist);
int songlistsize = songlist.size ();
for (int i = 0; i < songlistsize; i++) {
outputField.setText(i + ": " + songlist.get(i));
The problem is that the program will only display "Yesterday", and not anything else.
outputField.setText(i + ": " + songlist.get(i));
Because you are setting the last value and not appending. Do something like this:
StringBuilder string = new StringBuilder();
for (int i = 0; i < songlistsize; i++) {
string.append(songlist.get(i));
}
outputField.setText(string);
There are many other problems with the code but I am sticking to the point.
If you try to print your output on the console you will see that the part that deals with the collection works fine.
But since setText() replaces the current String with the latest song name you only see "Yesterday" because its at the end of your collection.
That´s why you should try to append() the next song name to your String or make sure you copy your current String, add the next item and finally use setText()
For example:
String string = "";
for (int i = 0; i < songlistsize; i++)
{
string = outputField.getText() + songlist.get(i);
outputField.setText(string);
}
I need help to generate empty string with particular no of spaces.
I tried this,
String opCode= " ";
for(int l=0;l<opCodelen;l++)
{
opCode+= " " ;
}
//opCodelen will get change every time
This worked but I want better solution.becoz using this I will have to use multiple loops for multiple columns.Is there any other way to do this?
Try String.format()
int opCodelen = 5;
String opCode = String.format("%" + opCodelen + "s", "");
System.out.println("[" + opCode + "]");
output
[ ]
Another way (uglier but for many probably simpler) to solve it could be
creating array of characters with same length as number of spaces you want to end up with,
filling it with spaces
and passing it as argument in String constructor.
Something like
char[] arr = new char[10]; // lets say length of string should be 10
Arrays.fill(arr, ' '); // fill array with spaces
String mySpaceString = new String(arr);
System.out.println(">" + mySpaceString + "<");
output:
> <
I have a requirement where I have Multiple Customer Invoices as different files. I am able to read the Customer Name and the Invoice Amount from each Invoice. The requirement is that for one customer, I should add up all the invoice amounts.
Here Is My Code:
String[] filenames1 = laf.splitFileNames();
FileInputStream fs;
BufferedReader br;
String line;
for (String filename1 : filenames1) {
fs = new FileInputStream(outFolder + filename1);
br = new BufferedReader(new InputStreamReader(fs));
for (int m = 0; m < 1; m++) {
br.readLine();
}
line = br.readLine().trim();
String cust_name = line.substring(12);//Returns the Customer Name
String amount = rll.lastNonBlankLine(new File(outFolder + filename1));//Returns Invoice Amount in String format
System.out.println(cust_name + "-" + rll.lastNonBlankLine(new File(outFolder + filename1)));
}
My Out put:
TAITA TAVETA TEACHERS SACCO-25,101.53
TAITA TAVETA TEACHERS SACCO-12,927.62
TAITA TAVETA TEACHERS SACCO-12,927.62
NOT FOR CUSTOMER-12,927.62
Ideally I should be able to get:
TAITA TAVETA TEACHERS SACCO-50,956.77
NOT FOR CUSTOMER-12,927.62
Please assists at this point where I am stuck.
You would have to somehow parse the amount string into some number type, probably BigDecimal. Then you could keep a Map from customer names to the current sum, which you continually update, while you read values.
Only when you are done reading in the files, you would then output the accumulated sums.
So you next steps should be:
Look up the reference documentation for BigDecimal, looking for a way to parse them.
Look up the reference documentation of Map, figuring out how they work and how that would help you.
I don't really think if this really help bu i should say, that your problem maybe when Returns Invoice Amount in String format, you do:
String amount = rll.lastNonBlankLine(new File(outFolder + filename1));
but when you print it, you will get another Invoice amount:
System.out.println(cust_name + "-" + rll.lastNonBlankLine(new File(outFolder + filename1)));
I think You have to do something like:
System.out.println(cust_name + "-" + amount);