I implemented Sharing intent button in my application. I have strings in textviews, but it is not always filled with any text. So, I would like to check it is empty or not. If a string is empty, sharing intent should ignore/remove/get ride of this string and go to next string. I tried to do this programmatically, but without success. How can I do this? I need some helpo:
public void buttonClick2(View view) {
TextView textView1 = (TextView)findViewById(R.id.word);
TextView textView2 = (TextView)findViewById(R.id.definition);
TextView textView3 = (TextView)findViewById(R.id.definition2);
TextView textView4 = (TextView)findViewById(R.id.definition3);
boolean hasDefinition2 = false;
if (textView3 !=null){
String text3 = textView3.getText().toString();
if(text3 !=null && !text3.isEmpty()){
hasDefinition2 = true;
}
}
String def2 ="";
if(hasDefinition2){
def2 +="\n Definition 2: "+textView3.getText().toString();
}
boolean hasDefinition3 = false;
if (textView4 !=null){
String text4 = textView4.getText().toString();
if(text4 !=null && !text4.isEmpty()){
hasDefinition3 = true;
}
}
String def3 ="";
if(hasDefinition3){
def3 +="\n Definition 3: "+textView4.getText().toString();
}
Intent shareIntent1 = new Intent(android.content.Intent.ACTION_SEND);
shareIntent1.setAction(android.content.Intent.ACTION_SEND);
shareIntent1.setType("text/plain");
shareIntent1.putExtra(android.content.Intent.EXTRA_SUBJECT, "Word"); //<=adding blank quotes
shareIntent1.putExtra(Intent.EXTRA_TEXT, textView1.getText().toString()+
"\n"+Definition: +textView2.getText().toString()+
"\n"+def2+
"\n"+def3+
"\n"+"\n"+"#2016 Dictionary"+
"\n"+"Visit us:");
startActivity(Intent.createChooser(shareIntent1, "Share"));
}
you can try the following to check if textView3/4 is empty or not: -
String extra =textView1.getText().toString()+
"\n"+Definition: +textView2.getText().toString();
if (textView3 !=null){
String text = textView3.getText().toString();
if(text !=null && !text.isEmpty()){
extra +="\n Definition 2:"+ textView3.getText().toString();
}
}
if (textView4 !=null){
String text = textView4.getText().toString();
if(text !=null && !text.isEmpty()){
extra +="\n Definition 3:"+ textView4.getText().toString();
}
}
extra += "\n"+"\n"+"#2016 Dictionary"+
"\n"+"Visit us:"
shareIntent.putExtra(Intent.EXTRA_TEXT, extra);
startActivity( ... )
also do consider using StringBuilder instead of String for the extra.
Related
How can I get element Id in android
<EditText
android:id="#+id/etCustomerNo"
I need access to id of editText in my activity (for example get "etCustomerNo" as a String).
Thank you.
I need to know id of all editText on layout
for (int i = 0; i < rl.getChildCount(); i++) {
if (rl.getChildAt(i) instanceof EditText) {
String id = String.valueOf(rl.getChildAt(i).getId());
}
}
getId() returns an int value instead of "etCustomerNo"
String s = getResources().getResourceEntryName(et.getId());
Et is your EditText object.
s is your id name.
by looking at View's source code inside toString() method, we can see how you can get the id name as string:
final int id = getId();
if (id != NO_ID) {
out.append(" #");
out.append(Integer.toHexString(id));
final Resources r = mResources;
if (Resources.resourceHasPackage(id) && r != null) {
try {
String pkgname;
switch (id&0xff000000) {
case 0x7f000000:
pkgname="app";
break;
case 0x01000000:
pkgname="android";
break;
default:
pkgname = r.getResourcePackageName(id);
break;
}
String typename = r.getResourceTypeName(id);
String entryname = r.getResourceEntryName(id);
out.append(" ");
out.append(pkgname);
out.append(":");
out.append(typename);
out.append("/");
out.append(entryname);
} catch (Resources.NotFoundException e) {
}
}
}
the entryname string is what you're looking for.
Simple.
EditText et=(EditText)FindViewById(R.id.etCustomerNo);
EditText edittext = (EditText) this.findViewById(R.id.etCustomerNo);
If you already have the editText, then try calling getId(). If you need to do anything further you'd like need to put together a switch statement formed of the various options:
private String getIdAsString(EditText editText) {
String value = null;
int id = editText.getId();
switch (id) {
case R.id.etCustomerNo:
value = "etCustomerNo";
break;
case R.id.edit_text_two:
value = "edit_text_two";
break;
}
return value;
}
I'm developing an app for android, and currently the only thing it does is calculate grades. There's two input boxes, one that takes the current grade, and another that takes a possible exam grade, and then it tells you the final grade. However, when there is no value in at least one of those boxes, it crashes. I tried to make an if statement to detect if the final value was null, but that didn't work. Here's my code:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}
and here's the code that renders it:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView1 = new TextView(this);
textView1.setTextSize(30);
textView1.setText("Your final would be " + message);
setContentView(textView1);
Just for reference, the .8 and .2 is because the current grade is weighted at 80%, and the exam is weighted at 20%. How can I make it so it won't crash when nothing is put into the boxes?
usernameEditText.getText().toString(); would not return null. It will return an empty string. What you can do before calculating finalResult is to check stringGrade and stingExam are non-empty and numerical values and if one is not then stop the operation. i.e.
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if (stringGrade.isEmpty() || stringExam.isEmpty()) {
Toast.makeText(this, "Invalid values", Toast.LENGTH_SHORT);
return;
}
try this:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if(stringGrade.equals("") ){
stringGrade = "0";
}
if(stringExam.equals("") ){
stringExam= "0";
}
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}
Hi everybody, I stucked in how to use two delimiters in
StringTokenizer in android for storing null values into db I have
string like this, string1=IMPS 2223 9481851276 7654321 , , 33
But empty fields missing in when used stringtokeniser
I want store result in db like this,
IMPS
2223
9481851276
7654321
null
null
33
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getactivity_layout);
LinearLayout layout = (LinearLayout) findViewById(R.id.details);
sms = getIntent().getStringExtra("value");
merchantName = getIntent().getStringExtra("merchantName");
tv = (TextView) findViewById (R.id.textview_getactivity_key);
tv.setText("Enter the Detail for-"+merchantName);
keyText = (EditText) findViewById(R.id.edittext_getactivity_value);
//finalKey = "Pay"+" "+merchantName+"-";
keyText.setText(finalKey);
View submitButton = findViewById(R.id.finish);
inputMap = new LinkedHashMap<String, EditText>();
Pattern p = Pattern.compile("\\|.*?\\|");
Matcher m = p.matcher(sms);
while (m.find())
{
//String to be replaced
String s = m.group(0);
Log.d("TestTag", "Value of string in getdetails"+s);
if (!" ".equals(s.replaceAll("\\|", "")))
{
TextView t = new TextView(this);
t.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
t.setText(s.replaceAll("\\|", ""));
t.setPadding(0, 0, 0, 5);
t.setTextColor(getResources().getColor(android.R.color.black));
EditText et = new EditText(this);
et.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
//et.setInputType(1234);
layout.addView(t);
layout.addView(et);
inputMap.put(s, et);
}
}
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
keyValue = keyText.getText().toString().trim();
ArrayList<String> tempArray = new ArrayList<String>();
String string=null;
if(sms != null && inputMap != null){
for(String s : inputMap.keySet()){
String inputValue = inputMap.get(s).getText().toString().trim();
if(inputValue.equalsIgnoreCase("") || inputValue.equals(null)){
//showDialog(s.replaceAll("\\|", "")+ " is mandatory.", inputMap.get(s));
return;
//sms = sms.replace(s, inputValue);
//tempArray.add(sms.replace(s, inputValue));
}
else{
sms = sms.replace(s, inputValue);
tempArray.add(sms.replace(s, inputValue));
}
string = sms.replaceAll("\\|\\s\\|",",");
}
StringTokenizer tokens = new StringTokenizer(string, " ");
String first = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String second =tokens.hasMoreTokens() ? tokens.nextToken() : null;
String third = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String fourth =tokens.hasMoreTokens() ? tokens.nextToken() : null;
String fifth = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String sixth = tokens.hasMoreTokens() ? tokens.nextToken() : null;
String seventh =tokens.hasMoreTokens() ? tokens.nextToken() : null;
Log.d("Test123", "Split String is : "+first+" "+second+" "+third+" "+fourth+" "+fifth+" "+sixth+" "+seventh);
in.setKeyValue(keyValue);
in.setSmsKeyword(first);
in.setCustomerAccountNo(second);
in.setMobileNo(third);
in.setMmid(fourth);
in.setAmount(fifth);
in.setCustomerPin(sixth);
in.setRemarks(seventh);
in.setTempName(merchantName);
accessDB.open();
accessDB.insertMerchant(in);
accessDB.close();
Intent detailsIntent = new Intent(GetDetailsActivity.this,MainScreenTab.class);
detailsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(detailsIntent);
}
I am showing text as link in my text view by android:autoLink="web" property. And it showing successfuly. But now i also want to show text as link which starts from #, for example "FleeGroups" in word "User pressed FOH button of this post via #FleeGroups"
Use a Spanable String
public class MainActivity extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String s= "User pressed FOH button of this post via #FleeGroups";
tv = (TextView) findViewById(R.id.tv);
String split[] = s.split("#");
SpannableString ss1= new SpannableString(split[1]);
Log.i("....",""+split[0]+"........."+split[1]);
ss1.setSpan(new MyClickableSpan(split[1]), 0,split[1].length(), 0);
tv.append(split[0]);
tv.append(ss1);
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
class MyClickableSpan extends ClickableSpan
{
String mystring;
public MyClickableSpan(String s)
{
mystring =s;
}
#Override
public void updateDrawState(TextPaint ds) {
// TODO Auto-generated method stub
super.updateDrawState(ds);
ds.setColor(Color.BLUE);
}
#Override
public void onClick(View widget) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, mystring, 1000).show();
}
}
}
More on styling #
http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring
Snap shot
For reference if you need it later.
You can also use a regex to match words that start with #
String s= "User pressed #FOH button of this post via #FleeGroups some text";
Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(s);
while (matcher.find()) {
spanstring= matcher.group(1);
Log.i(".............",spanstring);
}
You could use Html.fromHtml() and then set the LinkMovementMethod movement method.
Like this:
String link = "#FleeGroups";
String message = "User pressed FOH button of this post via ";
textView.setText(Html.fromHtml(message + link));
textView.setMovementMethod(LinkMovementMethod.getInstance());
/*Method in which you can pass the string to convert the into
spannableString and call this method form where ever you want
to set the text. It even work if you have mutiple # symbols
in your string.*/
TextView tv=(TextView) findViewById(R.id.textview);
tv.setText(getSpannableString("hi #StackOverFlow android"));
public SpannableStringBuilder getSpannableString(String str) {
SpannableStringBuilder builder = new SpannableStringBuilder();
String feed = str.replaceAll("\n", " ");
String[] individualfeed = feed.split(" ");
for (int i = 0; i < individualfeed.length; i++) {
if (individualfeed[i].contains("#")
) {
SpannableString redSpannable = new SpannableString(
individualfeed[i] + " ");
Pattern p = Pattern.compile(".*(\\w+)");
Matcher m = p.matcher(individualfeed[i]);
String str123 = null;
if (m.find()) {
str123 = m.group(1);
}
int startFrom = 0;
if (individualfeed[i].contains("#")) {
startFrom = individualfeed[i].indexOf("#");
}
if(individualfeed[i].trim().length()==1)
{
builder.append(individualfeed[i] + " ");
continue;
}
// I am using Green Color in this code change it accordingly
redSpannable.setSpan(
new ForegroundColorSpan(Color.parseColor("#00FF00")),
startFrom, individualfeed[i].lastIndexOf(str123) + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
final String tag = (String) individualfeed[i].subSequence(
startFrom, individualfeed[i].lastIndexOf(str123) + 1);
builder.append(redSpannable);
} else {
builder.append(individualfeed[i] + " ");
}
}
return builder;
}
I want to do the following: when a CheckBox is checked a TextView appears then the user can put whatever he needs, but the problem is I can't get the text written in the EditText to put it in a String variable, because it takes the initial value which is "nothing" when it enters the if statement. Any help?
i am new at this website , here is the part of the code i am talking about
SendSMS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked == true) {
sendText.setVisibility(0);
smstext = sendText.getText().toString();
} else if (isChecked == false) {
sendText.setVisibility(8);
smstext = "";
}
}
});
here.. after checking the sendsms to true edittext (sendText) will appear
.
.
.
.
.
.
here when the user enter any text i need to put it into a string (sms) to be stored in the data base ,, sorry for the mistakes
break;
case R.id.SaveImage:
String x = EventName.getText().toString();
if (x.contentEquals("")) {
Toast.makeText(getApplicationContext(), "Enter a Title",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(getApplicationContext(), Swipe.class);
startActivity(i);
Toast.makeText(getApplicationContext(), "Event saved",
Toast.LENGTH_SHORT).show();
String typename = type;
String name = EventName.getText().toString();
String location = EventLocation.getText().toString();
String dateFrom = DateFrom.getText().toString();
String dateTo = EbDate.getText().toString();
String timeFrom = mPickTime.getText().toString();
String timeTo = EbTime.getText().toString();
String duration = durationresult.getText().toString();
String alarm = alarmresult.getText().toString();
String repeat = repeatresult.getText().toString();
String audios = Audios;
String sms = smstext;
String call = calltext;
mySQLiteAdapter.insert(name, location, dateFrom, dateTo,
timeFrom, timeTo, duration, alarm, repeat, typename,
audios, sms, call);
updateList();
// reset form
EventName.setText(null);
EventLocation.setText(null);
break;
}
}
}
It appears that the only time you are setting smstext is when the value of the checkbox changes. The user can only enter text into that textbox when it is visible, so when the value of the checkbox changes, logically the textbox is empty and smstext will always be null.
Have you tried something like this:
case R.id.SaveImage:
...
String sms = sendText.getText().toString();
...