How to get value of checkbox into textview in Eclipse Android? - android

I already made multiple checkbox in dialog and want to get the checkbox value to textview in another activity, but i don't know the code, anyone can help?

Try the following.
CheckBox cb=(CheckBox)findViewById(R.id.checkbox1);
TextView tv=(TextView)findViewById(R.id.textview1);
cb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(cb.isChecked()){
cb.setChecked(true);
tv.setText(cb.getText().toString());
}
}
});
If you want to use it in another activity,either you can save it in local storage like sharedpreference or to a global variable.

first you get the value form the check box like ..
if (chk_Other_friOff.isChecked()) {
Global.newOther_fir = "1";
Log.e("Check box", "1st May ;;;" + Global.newOther_fir);
} else {
Global.newOther_fir = "0";
}
if (chk_Other_satOff.isChecked()) {
Global.newOther_sat = "1";
} else {
Global.newOther_sat = "0";
}
if (chk_Other_decOff.isChecked()) {
Global.newOther_dec = "1";
} else {
Global.newOther_dec = "0";
}
if (chk_Other_phone.isChecked()) {
Global.newOther_phone = "1";
} else {
Global.newOther_phone = "0";
}
Hear is Global is store a static value from conman class in my application.
and is get to another Activity like
TextView tv;
tv.setText(Global.newOther_phone);
its very simple.
Thanks...

Related

How to split phrase into word and display corresponding image in each word?

I've already tried this codes below but it only reads word not a phrase and this codes worked and didn't meet what I want.Each word that the user input it will only add and add to an empty array-list. What I want to achieve is when an user input a phrase it will split by space and store in an empty array-list. That array-list will compare to another array-list that contains words when the condition is true it will display a corresponding image and will now read the next word in the phrase.
private List<String> wordsList;
private ArrayList<String>wordsToDisplay=new ArrayList<>();
boolean missingGIF;
int counter;
wordsList= new ArrayList(Arrays.asList(getResources().getStringArray(R.array.sample)));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = editText.getText().toString();
String[]splited = input.split("//s+");
int count = splited.length;
for(int i=0;i<count;i++){
String word = splited[i];
if(wordsList.contains(word)){
wordsToDisplay.add(splited[i]);
}
else
missingGIF = true;
}
sample();
}
});
}
This is the sample method.
if(wordsToDisplay.size()>0){
counter=0;
gifImageView.setImageResource(getResources().getIdentifier(wordsToDisplay.get(0),"drawable",getPackageName()));
animation = (GifDrawable)gifImageView.getDrawable();
resetAnimation();
startAnimation();
animation.addAnimationListener(this);
}
And this is my animation listener which display corresponding images in all the words that have been inputted by the user.
#Override
public void onAnimationCompleted(int loopNumber) {
if(wordsToDisplay.size()>1){
if(counter<wordsToDisplay.size()){
try{
counter++;
gifImageView.setImageResource(getResources().getIdentifier(wordsToDisplay.get(counter),"drawable",getPackageName()));
animation = (GifDrawable)gifImageView.getDrawable();
resetAnimation();
startAnimation();
animation.addAnimationListener(this);
}
catch(IndexOutOfBoundsException e){
Log.d("Expected",e.toString());
}
}
}
}
Remove counter and use below logic
#Override
public void onAnimationCompleted(int loopNumber) {
if(!wordsToDisplay.isEmpty()){
String nextWord = wordsToDisplay.remove(0);
gifImageView.setImageResource(getResources().getIdentifier(nextWord,"drawable",getPackageName()));
animation = (GifDrawable)gifImageView.getDrawable();
resetAnimation();
startAnimation();
animation.addAnimationListener(this);
}
}

Compare data from edit text with data from if statement

I'm making a quiz app. User has to finish the phrase shown on display and write the name of the car in the edittext, after pushing on button, if the answer right, edittext become green, if doesn't, become red. If all answers right (green), intent move on next activity.
I have some difficulties with if statement edit text become red even the answer was right. Also how to make INTENT to move on next activity if all right, if not it doesn't move?
public class MainActivity extends AppCompatActivity {
EditText et_one_one, et_one_two, et_one_three;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_one_one = (EditText) findViewById(R.id.et_one_one);
et_one_two = (EditText) findViewById(R.id.et_one_two);
et_one_three = (EditText) findViewById(R.id.et_one_three);
final String t1 = et_one_one.getText().toString();
final String t2 = et_one_two.getText().toString();
final String t3 = et_one_three.getText().toString();
buttonCheck = (Button) findViewById(R.id.buttonCheck);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
et_one_three.setBackgroundColor(Color.RED);
}
}
});
}
}
You're changing the color of just the et_one_one each time in your if else statements. Shouldn't it be for different edittexts?
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean allAnswersCorrect = true;
String t1 = et_one_one.getText().toString();
String t2 = et_one_two.getText().toString();
String t3 = et_one_three.getText().toString();
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
allAnswersCorrect = false;
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_three.setBackgroundColor(Color.RED);
}
if(allAnswersCorrect){
Intent intent = new Intent(YourActivity.this, YourSecondActivity.class);
startActivity(intent);
}
}
});
Maintain a allAnswersCorrect boolean to check whether your answers are correct or not. If all are correct the move to your next activity.
You should use t2.equals("maserati"), and it will be ok.

Get and Store text from looped checkboxes into a String

I am kinda new in android and java programming, and I have a question, wish you could help me to solve it :)
I have a Program, it will fetch and loop data from database and convert it into some checkboxes, then user must check the checkboxes and hit the submit button,,
The value(s) of the checked checkboxes will be stored to a String[], then will be send to another activity via Intent.putExtra..
So far, all I can do is fetch and loop the data from database, but I have no idea about how to store all the checked value (of the checkboxes) to string and sent it to another activity via intent. Can you guys please help me with this and where should I put the code?
And here is my code :
private void fetchFromDatabase() {
// TODO Auto-generated method stub
myDb.open();
int totalGroup = myDb.countHowManyGroups(Username);
String groupId[] = myDb.fetchGroupId(Username);
String groupName[] = myDb.fetchGroupName(Username);
String flag[] = null;
for (int i = 0; i < totalGroup; i++) {
listCheckBox = new CheckBox(this);
listCheckBox.setText(groupName[i]);
listCheckBox.setTag(groupId[i]);
if (listCheckBox.isChecked()) {
int x=0;
flag[x]=listCheckBox.getText().toString();
x++;
}
layout.addView(listCheckBox);
}
myDb.close();
Button bSubmit = new Button(this);
bSubmit.setText("Submit");
layout.addView(bSubmit);
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (listCheckBox.isChecked()) {
}
}
});
}
It depends of what you want to store. Do you want to store the id of the selected checkboxes? Then override their setOnCheckedChangeListener to save it's id on an array (remember that id is 0 unless you set it.)
Do you want to save it's tag? Then override the same method but save the tag instead.
Here is an example of the implementation of setOnCheckedChangeListener:
List<String> myTagList = new ArrayList<String>();
listCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
myTagList.add(buttonView.getTag());
else
myTagList.remove(buttonView.getTag());
}
});

onClickListener not triggering

I'm doing a rather round about way of making a solitaire app. What's happening right now is that I'm trying to click on a button that is supposed to deal cards from the deck to the state that you can play cards from. However, the listener is never triggering.
I put a system.out.println statement in to test to see if it ever enters the code block with the listener, and it does not.
public class SolitaireGame extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
buttonSound = MediaPlayer.create(SolitaireGame.this, R.raw.button_click);
//instance variables
theDeck = new Deck();
botCardStacks = new ArrayList<BotCardStack>(7);
aceStacks = new ArrayList<AceCardStack>(4);
playableCards = new CardStack(52);
deckButton = (Button) this.findViewById(R.id.deckButton);
deckButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonSound.start();
dealCardsToPlayableStack();
}
});
As requested, here is my add cards to playable stack method
public void dealCardsToPlayableStack() {
Stack<Card> tempStack = new Stack<Card>();
int i = 0;
Card temp, temp1, temp2, temp3;
if(theDeck.getValueOfNext() == 0) {
while(!playableCards.isEmpty()) {
temp = playableCards.popCard();
temp.setVisible(false);
tempStack.push(temp);
}
while(!tempStack.isEmpty()) {
theDeck.addCard(tempStack.pop());
}
}
else if(theDeck.getValueOfNext() >= 3) {
temp1 = theDeck.popCard();
temp1.setVisible(true);
temp2 = theDeck.popCard();
temp2.setVisible(true);
temp3 = theDeck.popCard();
temp3.setVisible(true);
playableCards.addCard(temp3);
playableCards.addCard(temp2);
playableCards.addCard(temp1);
}
else if(theDeck.getValueOfNext() == 2) {
temp1 = theDeck.popCard();
temp1.setVisible(true);
temp2 = theDeck.popCard();
temp2.setVisible(true);
playableCards.addCard(temp2);
playableCards.addCard(temp1);
}
else if(theDeck.getValueOfNext() == 1) {
temp1 = theDeck.popCard();
temp1.setVisible(true);
playableCards.addCard(temp1);
}
}
First you should use buttonSound.prepare() before buttonSound.start() (I prefer using SoudPool Class instead of Mediaplayer for sound effects as it is less costly in memory). Secondly, can you share the dealCardsToPlayableStack() method. You can put it outside the onClick() method (in onCreate()) and if you have the same behaviour, then the problem is in this method, not the OnClick() method.

How do I check if my EditText fields are empty? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have 5 EditTexts in android. I would like to know if I could check if all 5 EditTexts are null. Is there any way to do this??
I did something like this once;
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
OR As Per audrius
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() == 0;
}
If function return false means edittext is not empty and return true means edittext is empty...
For validating EditText use EditText#setError method for show error and for checking empty or null value use inbuilt android class TextUtils.isEmpty(strVar) which return true if strVar is null or zero length
EditText etUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = etUserName.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
etUserName.setError("Your message");
return;
}
try this :
EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = usernameEditText.getText().toString();
if (strUserName.trim().equals("")) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
or use the TextUtils class like this :
if(TextUtils.isEmpty(strUserName)) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
Way late to the party here, but I just have to add Android's own TextUtils.isEmpty(CharSequence str)
Returns true if the string is null or 0-length
So if you put your five EditTexts in a list, the full code would be:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText was empty
// Do something fancy
}
}
Other answers are correct but do it in a short way like
if(editText.getText().toString().isEmpty()) {
// editText is empty
} else {
// editText is not empty
}
Try this
TextUtils.isEmpty(editText.getText());
You can use length() from EditText.
public boolean isEditTextEmpty(EditText mInput){
return mInput.length() == 0;
}
I usually do what SBJ proposes, but the other way around. I simply find it easier to understand my code by checking for positive results instead of double negatives.
You might be asking for how to check for empty EdiTexts, but what you really want to know is if it has any content and not that it is not empty.
Like so:
private boolean hasContent(EditText et) {
// Always assume false until proven otherwise
boolean bHasContent = false;
if (et.getText().toString().trim().length() > 0) {
// Got content
bHasContent = true;
}
return bHasContent;
}
As SBJ I prefer to return "has no content" (or false) as default to avoid exceptions because I borked my content-check. That way you will be absolutely certain that a true has been "approved" by your checks.
I also think the if calling it looks a bit cleaner as well:
if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}
It is very much dependent on preference, but i find this easier to read. :)
Why not just disable the button if EditText is empty? IMHO This looks more professional:
final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
txtFrecuencia.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
toggle.setEnabled(txtFrecuencia.length() > 0);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
I use this method, that uses trim() to avoid blank spaces :
EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
return;
}
an example if you have several EditText´s
if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(textA.getText())){
showToast(it's Null");
}
you can use TextUtils.isEmpty like my Example !
Good luck
with this short code you can delete empty space at start and end of the string. If the string is "" return the message "error" else you ave a string
EditText user = findViewById(R.id.user);
userString = user.getText().toString().trim();
if (userString.matches("")) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
return;
}else{
Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}
private boolean hasContent(EditText et) {
return (et.getText().toString().trim().length() > 0);
}
I used TextUtils for this:
if (TextUtils.isEmpty(UsernameInfo.getText())) {
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
You can also check all the EditText Strings in one If condition: like this
if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
}
I wanted to do something similar. But getting the text value from edit text and comparing it like (str=="") wasn't working for me. So better option was:
EditText eText = (EditText) findViewById(R.id.etext);
if (etext.getText().length() == 0)
{//do what you want }
Worked like a charm.
Try this out with using If ELSE If conditions. You can validate your editText fields easily.
if(TextUtils.isEmpty(username)) {
userNameView.setError("User Name Is Essential");
return;
} else if(TextUtils.isEmpty(phone)) {
phoneView.setError("Please Enter Your Phone Number");
return;
}
You could call this function for each of the edit texts:
public boolean isEmpty(EditText editText) {
boolean isEmptyResult = false;
if (editText.getText().length() == 0) {
isEmptyResult = true;
}
return isEmptyResult;
}
EditText txtUserID = (EditText) findViewById(R.id.txtUserID);
String UserID = txtUserID.getText().toString();
if (UserID.equals(""))
{
Log.d("value","null");
}
You will see the message in LogCat....
"check out this i m sure you will like it."
log_in.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=user_name.getText().toString();
password=pass_word.getText().toString();
if(username.equals(""))
{
user_name.setError("Enter username");
}
else if(password.equals(""))
{
pass_word.setError("Enter your password");
}
else
{
Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
startActivity(intent);
}
}
});
use TextUtils.isEmpty("Text here"); for single line code
The following works for me all in one statement:
if(searchText.getText().toString().equals(""))
Log.d("MY_LOG", "Empty");
First I retrieve a text from the EditText and then convert it to a string and finally comparing it with "" using .equals method.
This function work for me
private void checkForm() {
EditText[] allFields = {
field1_txt,
field2_txt,
field3_txt,
field4_txt
};
List < EditText > ErrorFields = new ArrayList < EditText > ();
for (EditText edit: allFields) {
if (TextUtils.isEmpty(edit.getText())) {
// EditText was empty
ErrorFields.add(edit); //add empty Edittext only in this ArayList
for (int i = 0; i < ErrorFields.size(); i++) {
EditText currentField = ErrorFields.get(i);
currentField.setError("this field required");
currentField.requestFocus();
}
}
}
}
EditText edt=(EditText)findViewById(R.id.Edt);
String data=edt.getText().toString();
if(data=="" || data==null){
Log.e("edit text is null?","yes");
}
else {
Log.e("edit text is null?","no");
}
do like this for all five edit text
You can use setOnFocusChangeListener , it will check when focus change
txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
if (arg1) {
//do something
} else {
if (txt_membername.getText().toString().length() == 0) {
txt_membername
.setError("Member name is not empty, Plz!");
}
}
}
});
if ( (usernameEditText.getText()+"").equals("") ) {
// Really just another way
}
I prefer using ButterKnife list binding and then applying actions on the list. For example, with the case of EditTexts, I have the following custom actions defined in a utility class (in this case ButterKnifeActions)
public static <V extends View> boolean checkAll(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = true;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) && hasProperty;
}
return hasProperty;
}
public static <V extends View> boolean checkAny(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = false;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) || hasProperty;
}
return hasProperty;
}
public interface Check<V extends View> {
boolean checkViewProperty(V view, int index);
}
public static final ButterKnifeActions.Check<EditText> EMPTY = new Check<EditText>() {
#Override
public boolean checkViewProperty(EditText view, int index) {
return TextUtils.isEmpty(view.getText());
}
};
And in the view code, I bind the EditTexts to a list and apply the actions when I need to check the views.
#Bind({R.id.edit1, R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5}) List<EditView> edits;
...
if (ButterKnifeActions.checkAny(edits, ButterKnifeActions.EMPTY)) {
Toast.makeText(getContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
And of course this pattern is extendable to checking any property on any number of views. The only downside, if you can call it that, is the redundancy of views. Meaning, to use those EditTexts, you would have to bind them to single variables as well so that you can reference them by name or you would have to reference them by position in the list (edits.get(0), etc.). Personally, I just bind each of them twice, once to a single variable and once to a the list and use whichever is appropriate.
To editText is empty try another this simple way :
String star = editText.getText().toString();
if (star.equalsIgnoreCase("")) {
Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).show();
}
Try this out:
its in Kotlin
//button from xml
button.setOnClickListener{
val new=addText.text.toString()//addText is an EditText
if(new=isNotEmpty())
{
//do something
}
else{
new.setError("Enter some msg")
//or
Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
}
}
Thank you

Categories

Resources