Intent.EXTRA_SUBJECT multiple values in Android - android

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);

Related

Is it possible to share multiple text by using share intent?

I intend to share 6 text information, however it always shows the last information only, i.e.
share.putExtra(Intent.EXTRA_TEXT, Contact);
I also tried to use a string array to store all 6 information, i.e:
share.putExtra(Intent.EXTRA_TEXT, stringArray);
However, it still doesn't work. Can anyone help ? Thank you.
My code:
public class SingleJobActivity extends Activity {
// JSON node keys
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
String PostName;
String Location;
String Salary;
String Responsibility;
String Company;
String Contact;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_job_json_parsing);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
PostName = in.getStringExtra(TAG_POSTNAME);
Location = in.getStringExtra(TAG_LOCATION);
Salary = in.getStringExtra(TAG_SALARY);
Responsibility = in.getStringExtra(TAG_RESPONSIBILITY);
Company = in.getStringExtra(TAG_COMPANY);
Contact = in.getStringExtra(TAG_CONTACT);
// Displaying all values on the screen
TextView lblPostName = (TextView) findViewById(R.id.PostName_label);
TextView lblLocation = (TextView) findViewById(R.id.Location_label);
TextView lblSalary = (TextView) findViewById(R.id.Salary_label);
TextView lblResponsibility = (TextView) findViewById(R.id.Responsibility_label);
TextView lblCompany = (TextView) findViewById(R.id.Company_label);
TextView lblContact = (TextView) findViewById(R.id.Contact_label);
lblPostName.setText(PostName);
lblLocation.setText(Location);
lblSalary.setText(Salary);
lblResponsibility.setText(Responsibility);
lblCompany.setText(Company);
lblContact.setText(Contact);
// listeners of our button
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.share:
shareTextUrl();
break;
}
}
};
// our button
findViewById(R.id.share).setOnClickListener(handler);
}
// Method to share either text or URL.
private void shareTextUrl() {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide
// what to do with it.
share.putExtra(Intent.EXTRA_SUBJECT, "Job Information:");
share.putExtra(Intent.EXTRA_TEXT, PostName);
share.putExtra(Intent.EXTRA_TEXT, Location);
share.putExtra(Intent.EXTRA_TEXT, Salary);
share.putExtra(Intent.EXTRA_TEXT, Responsibility);
share.putExtra(Intent.EXTRA_TEXT, Company);
share.putExtra(Intent.EXTRA_TEXT, Contact);
startActivity(Intent.createChooser(share, "Share via"));
}
}
Could anyone help ?
Concatenate the six strings into one larger string, and share that larger string.
You can Concatenate the individual strings to larger string, and can get it
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
String j = (String) b.get("name");
JSONObject name = new JSONObject(j);
Textv.setText(name.getString("postName"));
TextvDesc.setText(name.getString("location"));
}
What's wrong with your actual code
Let's first understand why you only get the last piece of data.
Your problem is by convention in Java (and this also applies to the android.content.Intent.html#putExtra(String, String[]) method you are using) the methods "putXXX" replace the actual value (if it exists) with the new one you are passing.
This is similar to java.util.Map.html#put(K, V) method.
First possible solution
For your current code to work, you would have needed to use a different key for your extra data each time, that is, something like that:
share.putExtra(SingleJobActivity.EXTRA_TEXT_NAME, PostName);
share.putExtra(SingleJobActivity.EXTRA_TEXT_LOCATION, Location);
share.putExtra(SingleJobActivity.EXTRA_TEXT_SALARY, Salary);
share.putExtra(SingleJobActivity.EXTRA_TEXT_RESPONSIBILITY, Responsibility);
share.putExtra(SingleJobActivity.EXTRA_TEXT_COMPANY, Company);
share.putExtra(SingleJobActivity.EXTRA_TEXT_CONTACT, Contact);
This would work fine (assuming you declare as public static final the keys used, and you respect the Android contract for extra data keys, such as using the full package name for the key (e.g. public static final EXTRA_TEXT_NAME = "com.yourpackage.EXTRA_DATA_NAME";).
Second possible solution
Another way of doing it is to pass one extra with a String[] (see method documentation).
String[] extraParams = new String[6];
extraParams[0] = PostName;
extraParams[1] = Location;
extraParams[2] = Salary;
extraParams[3] = Responsibility;
extraParams[4] = Company;
extraParams[5] = Contact;
share.putExtra(SingleJobActivity.EXTRA_TEXT, extraParams);
Then in your new activity you retrieve this array using android.content.Intent.html#getStringArrayExtra(String) method.
Intent intent = getIntent();
String[] extraParams = intent.getStringArrayExtra(SingleJobActivity.EXTRA_TEXT);

Named placeholders in Android

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.

Capturing part of string from a txt file?

I have a text file like this, separated by ";"
1022-3, 1603-4, 2012-5, 2489-6;
Gotta catch the first part before the "-" and pass to variable, and compare with milliseconds, if is equal the number, capture the number after of "-".
And do so with the next number after the semicolon, and so front.
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
And the beginning of the code to do what I need this here
private void LerArquivo() {
String lstrNomeArq;
File arq;
String lstrlinha;
long tempoInicio = 0;
long tempoDecorrido = 0;
try {
tempoDecorrido = (RecordSound.MilliSeconds() - tempoInicio);
lstrNomeArq = "/Android/data/br.com.couldsys.drumspro/cache/GravaSound.TXT";
String conteudotexto = "";
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
String capturaIndex = ("Conteudo do texto: "
+ conteudotexto.substring(
conteudotexto.indexOf("-") + 1,
conteudotexto.indexOf(";",
conteudotexto.lastIndexOf("-"))));
if (tempoDecorrido == capturatempo) {
DrumsProActivity.vsm.playSound(capturaindex);
// ler a nova linha
// se chegar ao final do string então para o while
if (conteudotexto.length() > 0) {
executar = false;
}
}
} catch (Exception e) {
trace("Erro : " + e.getMessage());
}
}
use this simpler code : create an array of substrings each contain a string formated ####-#
string[] MyStr = conteudotexto.split(',');
string sss= MyStr[0];
string sss2= MyStr[1];
....
now sss is 1022-3
sss2 is 1603-4 and so on ....
then reuse split function:
string[] MyStr2 = sss.split('-');
now we have :
MyStr2[0] = 1022
MyStr2[1] = 3
Maybe not particular elegant but just pragmatic for me - use the String split method. First split with ","
String[] parts = conteudotexto.split(",");
and then with each of the parts (here for the first)
String[] subParts = parts[0].split("-");
Just gives you everything in the pieces you need to look at and no danger get mixed up with positions etc.
What I need now is know how to catch part of text.
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
The text may vary more separation has two, the first number is separated from the second number by a "-" (dash) which is then separated by "," (comma)
549-8,1019-9,1404-3,1764-3,2208-10,2593-5,2938-9,3264-6,3700-0,4174-7,4585-8,4840-2,5192-9,5540-10,5932-0,
As has been shown
String[] parte1 = conteudotexto.split(",");
e em seguida
String[] parte2 = parte1[0].split("-");
The rule I'm trying to do is: Turn within a millisecond while the method and compare with the first part of the text
type
**If valor_milissegundos first part is equal to the number of text then
---> enters and runs the function playSound (the second number of the text);
------> goes to the next number in the text loop, capturing the second number of the text and compares it to the millisecond, if equal enters the IF block and catch the second number after the dash, and so on, until you reach the end of the text.**
Method return milliseconds calculates milliseconds
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
I hope understand why I used the google translator
thank you

How to use Dictionary (like iphone NSDictionary) in android?

I have worked in soap message, and to parse the value from Webservice, the values are stored in ArrayList.
Example:
values are Employee name (Siva) and Employee id (3433fd), these two values are stored in arraylist, but I want to stored in Dictionary, How?
you can use HashMap like this
Map <String,String> map = new HashMap<String,String>();
//add items
map.put("3433fd","Siva");
//get items
String employeeName =(String) map.get("3433fd");
You can use Bundle.
as it offers String to various types of Mapping.
Bundle b = new Bundle();
b.putInt("identifier", 121);
b.putString("identifier", "Any String");
b.putStringArray("identifier", stringArray);
int i = b.getInt("identifier");
...
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText textview = (EditText) findViewById(R.id.editTextHash);
EditText textviewNew = (EditText) findViewById(R.id.editTextHash2);
Map<String, String> map = new HashMap<String,String>();
map.put("iOS", "100");
map.put("Android", "101");
map.put("Java", "102");
map.put(".Net", "103");
String TextString = "";
// Set<E> keys = map.keySet();
Set keys = map.keySet();
System.out.println("keys "+keys);
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
System.out.println("key "+key);
String value = (String) map.get(key);
System.out.println("value "+value);
textview.append(key + " = " + value);
TextString+=(key + " = " + value);
}
//textviewNew.setText(TextString);
// Iterator iterator = map.keySet().iterator();
//
// while (iterator.hasNext())
// {
// String object = (String) iterator.next();
// textview.setText(object);
// }
//
// //textview.setText(map.get("Siva"));
//
// System.out.println(map);
}
}
A Dictionary is an abstract class that maps keys to values and there is Dictionary Class in android refer link you can find a note at Class Overview
Do not use this class since it is obsolete. Please use the Map
interface for new implementations.
An attempt to insert either a null key or a null value to a dictionary will result to a NullPointerException,but you can use Map interface,it provides the exact same functionality of a dictionary.you can use it as bellow
//put values
Map Message = new HashMap();
Message.put("title", "Test message");
Message.put("description", "message description");
Message.put("email", "email#gmail.com");
//get values
Log.d("get Message","Message title -"+Message.get("title"));
you can also use A custom class as below
public class MessageObject {
String title;
String description;
String email;
}
you can use Getters and Setters to get and put values,not needed to remember the key names every time you may get some other advantages by this way.

how to read characters from a string for android

how can i read characters from a string variable until a special character has reached, for example a '/'.it should be read from begining.
and how to send this string to another activity from onItemClickListener() method
How about split?
String theSeparator = "/";
String original = "Some string with a special char / and some content after the /";
String myString = original.split(Pattern.Quote(theSeparator))[0];
Now, passing the string when you start a new activity is pretty simple:
Intent i = new Intent(ThisActivity.this, NextActivity.class);
i.putExtra("My Super Special String", myString);
startActivity(i);
In the next activity, you call:
String myStringFromPreviousActivity = getIntent().getStringExtra("My Super Special String");
String myString = "Send this String Out/Leave this one behind";
String toSendOut = "";
for(int i = 0; i < myString.length(); i++){
if(myString.charAt(i) != '/'){
toSendOut = toSendOut + myString.charAt(i);
} else {
break;
}
}
myString is your inputted String, toSendOut is the string you're sending to wherever you want to send it to.
So, in this example, toSendOut will read "Send this String Out". The way it does this is by checking one letter at a time in myString. If the letter isn't "/", it adds that character to toSendOut. The process loops until a "/" is hit, in which case the loop breaks (ends).
String s = "aaaaa/bbbbb";
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '/'){
//Do whatever you like.
}
}
Take a look at the javadocs for the String class you will find lots of useful methods for interacting with and manipulating Strings.

Categories

Resources