In my android app
in message if i give message "hi #name,welcome your username:#username and password:#password" and in message #name,#username,#password are to be replaced with values iam reading from csv file
and it should send message as example:"hi praveen,welcome your username:neevarp and password:12345"
and those values are from csv .while searching i got some link
Named placeholders in string formatting
Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
but in android
StrSubstitutor
class is not there i think so is there any way to implement this
here is my code of reading values from csv and sending messages by replacing place holders
public void sendingSms(String message, String file_path) {
File file = new File("", file_path);
// Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int iteration = 0;
while ((line = br.readLine()) != null) {
if (iteration != 0) {
StringBuilder text = new StringBuilder();
text.append(line);
String[] contact = text.toString().split(",");
String phoneNumber = contact[4];
String name = contact[1];
String username = contact[2];
String password = contact[3];
//here i have to replace place holders with name,username,password values
//message.replace("#name", name);
//message.replace("#user", username);
Toast.makeText(Message.this, "" + message,
Toast.LENGTH_SHORT).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null,
null);
}
iteration++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
You should really be using the built in string formatting Android provides via string resources: http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
The functionality that you want is built right into the String class itself if you want to design your own StrSubstitutor class. Essentially building/designing a foreach with your Mapped values into the function.
String result = inputString.replace(valueString, replacedValueString);
But I am unaware of the function that you are requesting being built-in. Alex Fu as well has provided alternate means by which you could handle your string replacement.
Related
The android default Email is filter by subject, sender or receiver. But how to filter by content? The message body is not saved to database, which is saved to the file in after Android 5.0. Should I put the message body to the database, which do like before Android 5.0? And then filter the content according the keyword? Please give me some advice, Thanks!
case BODY:
final ContentValues dbValues = new ContentValues(values);
// Prune out the content we don't want in the DB
dbValues.remove(BodyColumns.HTML_CONTENT);
dbValues.remove(BodyColumns.TEXT_CONTENT);
// TODO: move this to the message table
longId = db.insert(Body.TABLE_NAME, "foo", dbValues);
resultUri = ContentUris.withAppendedId(uri, longId);
// Write content to the filesystem where appropriate
// This will look less ugly once the body table is folded into the message table
// and we can just use longId instead
if (!values.containsKey(BodyColumns.MESSAGE_KEY)) {
throw new IllegalArgumentException(
"Cannot insert body without MESSAGE_KEY");
}
final long messageId = values.getAsLong(BodyColumns.MESSAGE_KEY);
// Ensure that no pre-existing body files contaminate the message
deleteBodyFiles(context, messageId);
writeBodyFiles(getContext(), messageId, values);
break;
public static String buildLocalSearchSelection(Context context, long mailboxId,
String queryFilter, String queryFactor) {
StringBuilder selection = new StringBuilder();
selection.append(" (");
queryFilter = queryFilter.replaceAll("\\\\", "\\\\\\\\")
.replaceAll("%", "\\\\%")
.replaceAll("_", "\\\\_")
.replaceAll("'", "''");
String[] queryFilters = queryFilter.split(" +");
boolean isAll = false;
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_ALL)) {
isAll = true;
}
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_SUBJECT) || isAll) {
selection.append(buildSelectionClause(queryFilters, MessageColumns.SUBJECT));
}
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_SENDER) || isAll) {
selection.append(buildSelectionClause(queryFilters, MessageColumns.FROM_LIST));
}
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_RECEIVER) || isAll) {
selection.append(buildSelectionClause(queryFilters, null));
}
selection.delete(selection.length() - " or ".length(), selection.length());
selection.append(")");
return selection.toString();
}
it can use the ' MessageColumns.SNIPPET' to filter the email content.
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 searched a bit and couldn't find anything so I'm asking it here:
It'd be great if there's a tutorial or example project where I can look at. So far I've only found on how to populate this database using the data that is generated locally, by programmer's input.
Question:
I have an URL to a website that is a .txt with some data, how do I parse it, populate it to a SQLite database that I'll create in my Android application?
Edit:
This is the format:
Item1 <newline>
Description <newline>
LocalFilePathToPicture1<newline>
Item2 <newline>
Description <newline>
LocalFilePathToPicture2<newline>
...
Ok as your comments and latest edits, lets say your text file url is something like this
http://www.example.com/myTextFile.txt
What you can do something like this
StringBuffer myString = new StringBuffer("");
try {
// Create a URL
URL url = new URL("http://www.example.com/myTextFile.txt");
// Read the text
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String string;
while ((string = in.readLine()) != null) {
// string is one line of text; readLine() reads the newline
myString.append("__"+string);
}
in.close();
}
catch (Exception e) {
}
return myString;
And here is a sample of doInBackground() method inside your AsyncTask class where you will be splitting the string and inserting them into sqlite
#Override
protected String doInBackground(String... params) {
String myString = params[0];
String[] splitedString = myString.split("__");
ContentValues cv=new ContentValues();
cv.put("firstline", splitedString[0]); //where firstline is your column name
cv.put("secondline", splitedString[1]);
db.insert(yourTable, null, cv); //where db is your instance of writable database
db.close(); //Close the connection
}
Here I am reading file word by word and manipulating List view with these word. Problem here is First name and Last name are appearing in different rows. e.g. Name = "John Clerk" then I am getting "John" in first row and "Clerk" in second row of List view. They must be in single row and so forth for other data. What should I make changes to work it properly? My code...
String myData = "";
String strLine;
String listName = "" ;
FileOutputStream fos;
FileInputStream fstream;
DataInputStream in;
String[] SavedFiles;
BufferedReader br;
public void readFile(String file) throws IOException
{
fstream = openFileInput(file);
Scanner scanFile = new Scanner(new DataInputStream(fstream));
ArrayList<String> words = new ArrayList<String>();
String theWord, theWord1, theWord2;
while (scanFile.hasNext())
{
theWord = scanFile.next();
words.add(theWord);
}
Toast.makeText(getBaseContext(), "" + size, 1000).show();
adapterFriends = new ArrayAdapter<String>(getBaseContext(), R.layout.text, words);
lvFinal.setAdapter(adapterFriends);
adapterFriends.notifyDataSetChanged();
}
Try to use nextLine() instead of next(), as it should return every string between \n chars.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextLine()
hope that helps
If I understand correctly what you need, try this:
while (scanFile.hasNext())
{
String name = scanFile.next();
if (scanFile.hasNext())
{
name = String.format("%s %s", name, scanFile.next());
}
words.add(name);
}
I want to display multiple values in the text message body, however the following code below display no body message even when the textArray has values. Is there any way of adding values to a body of an email through a loop?
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Example");
int sizeOfArray = list.size();
String textArray [] = new String[sizeOfArray];
for(int i = 0;sizeOfArray > i;i++)
{
HashMap<String, String> arrayString = list.get(i);
String user = arrayString.get("user");
String book = arrayString.get("book");
textArray[i] = user + " - " + book;
}
sharingIntent.putExtra(Intent.EXTRA_TEXT, textArray);
startActivity(Intent.createChooser(sharingIntent,"Share using"));
}
});
It's difficult to get proper documentation on what Intent Receivers are expecting as extra values, but I'm pretty sure you need to pass a String and not a String[] to putExtra, since the Receiver will anyway end up converting the value to a String, so better to control that.
Thats being said, your implementation of the loop is weird. Do you really have a list of HashMap<String, String>as input ?
I would do :
StringBuffer sb = new StringBuffer();
for(HashMap<String, String> item: list){
String user = item.get("user");
String book = item.get("book");
sb.append(user + " - " + book+", ");
}
String value = sb.substring(0, Math.max(0,sb.length()-2));
Intent.EXTRA_TEXT expects CharSequence according to the documentation:
http://developer.android.com/reference/android/content/Intent.html#EXTRA_TEXT
I would guess as you are passing in an array, the receiving activity doesn't know what to do with it and just skips over it.
Trying joining your array values and passing them in as a String.
String arg = org.apache.commons.lang.StringUtils.join (textArray, '\n');
sharingIntent.putExtra(Intent.EXTRA_TEXT, arg);