Reputation: 73
I'm trying to put my messages in a chat to make something look like this:
This is my String of messages:
String messages = "Me said: Hola\n"+
"Steven said: Hola android client\n"+
"Me said: como estas ?\n"+
"Steven said: Yo muy bien y tu?\n"+
"Me said: bueno si esto funciona me sentire magnifico ;)\n"+
"Me said: ah cierto me olvidaba veamos si dos mensajes seguidos funcionan\n"+
"Steven said: bien\nVeamos si funciona\n"+
"Me said: se xd\n";
I tried this to make it read each line:
while(messagesToRead.contains("Me said:") || messagesToRead.contains("Steven said:")){
if(messagesToRead.indexOf("Me said:")==0)
{
// 8 because 'Me said:' size is 8 , -1 because i don't want to read the last \n
String messageToAdd=messagesToRead.substring(8,(messagesToRead.indexOf("Steven said:"))-1);
// if the first @param is false i set it to right
adapter.add(new DataProvider(false,messageToAdd));
messagesToRead = messagesToRead.substring(messageToAdd.length()+9);
}
else if(messagesToRead.indexOf("Steven said:")== 0)
{
// 12 because of 'Steven said:' size
String messageToAdd=messagesToRead.substring(12,messagesToRead.indexOf("Me said:")-1);
adapter.add(new DataProvider(true,messageToAdd));
messagesToRead = messagesToRead.substring(messageToAdd.length()+13);
}
}
I know I have a problem with the logic, and it is not the best way to read each line but I just wanted to make it work with that way for now.
Upvotes: 1
Views: 61
Reputation:
This should work. I just tested it.
String messagesToRead = "Me said: Hola\n"+
"Steven said: Hola android client\n"+
"Me said: como estas ?\n"+
"Steven said: Yo muy bien y tu?\n"+
"Me said: bueno si esto funciona me sentire magnifico ;)\n"+
"Me said: ah cierto me olvidaba veamos si dos mensajes seguidos funcionan\n"+
"Steven said: bien\nVeamos si funciona\n"+
"Me said: se xd\n";
String[] messages= messagesToRead.split("\n");
ArrayList<String> arr = new ArrayList<String>(Arrays.asList(messages));
messages=null;
String pattern1 = "Me said:";
String pattern2 = "Steven said:";
int size = arr.size(); //you need to have the initial size before processing
// lines you are talking about
for(int i=size-1;i>=0;i--)
{
String str = arr.get(i);
if(str!="" && str.indexOf(pattern1)==-1 && str.indexOf(pattern2)==-1)
{
String tmp = arr.remove(i);
String old =arr.get(i-1) ;
arr.set(i-1,old+"\n"+tmp);
}
}
messages = new String[arr.size()];
messages = arr.toArray(messages);
for(String mess : messages)
{
if(mess!="" && mess.indexOf(pattern2) == 0)
{
/*code here*/
System.out.println(mess);
}
}
Upvotes: 1