How to change background color of editText? - java

I need to change background color of EditText if it is empty.
Below is my code but doesn't seem to be working.
public void onClick(View v) {
// TODO Auto-generated method stub
Change();
}
public void Change() {
if(("").equals(name)) {
name.setBackgroundColor(Color.RED);
return;
}
}

The easiest way is to check the length:
if (name.length() == 0) {
name.setBackgroundColor(Color.RED);
}

Assuming 'name' is the EditText in question, your if statement should read something like this:
if(("").equals(name.getText().toString()))
Performing an Object.equals(Object) between a String and an EditText (at least currently!) will not return true.

String name = nameedittext.getText().toString();
if(name.isEmpty()){
nameedittext.setBackgroundColor(Color.RED);
}
If you want to give a error message too then you can write this:
if(name.isEmpty()){
nameedittext.setBackgroundColor(Color.RED);
nameedittext.setError("Please Enter Name");
return;
}

Related

Setting Listeners programmatically to an array of CheckBoxes

So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far.
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
//do something
}
}
});
}
Any tips on how to solve this?
Take final String[] x={"defaultvalue Emptry"}
Then after inside onclick Listener set value of x using below code.
x[0]="new value"
and use this value in different function.
as per your code it look likes blow:
final String x[] ={""}
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
x[0]=checkBoxes_fiber[i].getvalue==> value name
}
}
});
}
Outside function get value of x using
String name=x[0]
You can try to create separate class of listener
private View.OnClickListener mCheckboxListener = new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)view).isChecked())
{
int checkBoxId = (int)v.getTag(); //You can get Id for specific checkbox
//do other stuff with checkBoxId
}
}
};
And set Id to each checkbox like
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes.setTag(i); //set check box id as tag for later usage
checkBoxes_fiber[i].setOnClickListener(mCheckboxListener);
}
I guess you are trying to do something base on the checkbox IDs. You can set a tag for a checkBox and get back the tag in future. Also, the view object in method void onClick(View view) is now an CheckBox. Just change a little in your code:
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setTag(i); //mark the check box id for later usage
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(((CheckBox)view).isChecked()){
int checkBoxId = (int)view.getTag();
doSomething(checkBoxId);
}
}
});
}
}
And write a new method for business code:
public void doSomething(int no){
if(no==1){
//do something
}
else if(no==2){
//do something
}
//...
}

IF Condition doesnt work

Am trying to make an IF condition but it's not working well. I want when the EditText is null, the user doesn't go to the next Activity.
when it's filled it goes to the next activity after a button press.
Name = is my EditText assignment
one_next_diaspora_bt = is the Button.
Below is my Code:
final String Name = name_diaspora_edt.getText().toString();
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Name.matches("")){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
else {
Intent i = new Intent(Diaspora.this,DiasporaTwo.class);
i.putExtra("Name",Name);
i.putExtra("Age",Age);
i.putExtra("Gender",Gender);
i.putExtra("MaritalStatus",MaritalStatus);
startActivity(i);
}
}
});
Change your condition to this:
if(edt.getText().toString().isEmpty()){
}
Or
if (edt.getText().trim().equals("")){
}
use:
if (Name.getText() != null && Name.getText().toString().trim().equals(""))
And follow the Java naming convention. variable names should start with lower case character
try this:
if (Name != null && Name.equalIgnoreCase("null") && Name.trim().equalIgnoreCase("")){
}else
{
}
Use this :
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name = name_diaspora_edt.getText().toString().trim();
if(Name.matches("")){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
else{
Intent i = new Intent(Diaspora.this,DiasporaTwo.class);
i.putExtra("Name",Name);
i.putExtra("Age",Age);
i.putExtra("Gender",Gender);
i.putExtra("MaritalStatus",MaritalStatus);
startActivity(i);
}
}
});
}
Try TextUtils.isEmpty, it will check null and empty as well. TextUtils is a built-in class in package android.text
if(android.text.TextUtils.isEmpty(Name)) {
First I would say, you really should follow naming conventions.
But you need to grab the String that lives inside of your EditText and compare it with .equals like so:
if(name.getText().toString().equals("")){
//do something
}
if (TextUtils.isEmpty(Name)){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
Use android default validation, TextUtils class
Use TextUtils.isEmpty(Name) instead of Name.matches("").
TextUtils.isEmpty(CharSequence str) >> Returns true if the string is null or 0-length.
Try this:
final String Name = name_diaspora_edt.getText().toString();
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(TextUtils.isEmpty(Name)) {
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(Diaspora.this, DiasporaTwo.class);
i.putExtra("Name", Name);
i.putExtra("Age", Age);
i.putExtra("Gender", Gender);
i.putExtra("MaritalStatus", MaritalStatus);
startActivity(i);
}
}
});
Hope this will help~
You can directly check the EditText with this method , equals() works with Strings.
Try This
String data = Name.getText().toString();
Then
if(data.isEmpty()){
}

How to create a method inside the onPostExecute?

I tried to put if else inside the button onClick
Here's the onClick
#Override
public void onClick(View view) {
ettext.getText().toString();
viewword.getText().toString();
select();
if(viewword.equals("")) {
Toast.makeText(getBaseContext(), "Does not exist in database.1", Toast.LENGTH_LONG).show();
}else{
sendChatMessage();
}
}
Here's the onPostExecute
#Override
protected void onPostExecute(String result) {
TextView disp = (TextView) findViewById(R.id.view);
try {
JSONObject json_data = new JSONObject(result);
word = json_data.getString("server_response");
disp.setText(word);
} catch (JSONException e) {
disp.setText("");
}
}
The problem is that the app is not reading the if else statement and proceed to onPostExecute. My solution was to create a method inside the onPostExecute but I don't know how.
The problem here isn't onPostExecute but your code.
viewword.getText().toString();
This is just a String value and you need to store it in some variable when you are checking if it is null or not. Hence your code should be either
String checkVariable =viewword.getText().toString();
if(checkVariable.equals(""){
\\your code}
or
if(viewword.getText().toString().equals("")
Hope this helps :)
You can't create a method in a method, you can create a method in the AsyncTask class and call it in onPostExecute method.

How to return user input values (double) from EditText- Android

I'm new to OOP, but I've had experience with C previously. I'm learning Java and working on building an app slowly. I find I learn more when I apply what I've read and learned from other sources to projects.
The problem I've been facing for a while now is in regard to returning values users have inputted into EditText fields and using those values to run some calculations. Here is my code:
public class Linmotion extends Activity {
// Creating the variables
EditText time, acc, dis, ivel, fvel;
Button solve;
int count = 0;
double time1,acc1,dis1,ivel1,fvel1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linmotion1);
time = (EditText) findViewById(R.id.EditText01);
acc = (EditText) findViewById(R.id.EditText02);
dis = (EditText) findViewById(R.id.EditText03);
ivel = (EditText) findViewById(R.id.EditText04);
fvel = (EditText) findViewById(R.id.EditText05);
solve = (Button) findViewById(R.id.buttonSolve);
//Trying to return inputted values
/*
if (!(time.getText() == null)) {
time1=Double.parseDouble(time.getText().toString());
}
if(!(acc.getText()==null)){
acc1=Double.parseDouble(acc.getText().toString());
}
if(!(ivel.getText()==null)){
ivel1=Double.parseDouble(ivel.getText().toString());
}
if(!(fvel.getText()==null)){
fvel1=Double.parseDouble(fvel.getText().toString());
}s
if(!(dis.getText()==null)){
dis1=Double.parseDouble(dis.getText().toString());
}
/*
* Double.parseDouble(time.getText().toString());
* Double.parseDouble(acc.getText().toString());
* Double.parseDouble(ivel.getText().toString());
* Double.parseDouble(fvel.getText().toString());
* Double.parseDouble(dis.getText().toString());
*/
// add button listener
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (time1 < 0) {
count++;
if (acc1 < 0) {
count++;
}
if (ivel1 < 0) {
count++;
}
if (fvel1 < 0) {
count++;
}
if (dis1 < 0) {
count++;
}
if (count > 2) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Linmotion.this);
final AlertDialog alert = alertDialog.create();
alert.show();
alertDialog.setTitle("Error");
alertDialog
.setMessage("Please input values into at least 3 fields");
alertDialog.setPositiveButton("OK",new DialogInterface.OnClickListener() {
// function of dialog button
public void onClick(DialogInterface dialog,
int id) {
alert.cancel();
}
});
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.linmotion, menu);
getActionBar().setDisplayShowTitleEnabled(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The if statements and the other Double.parseDouble lines have been commented out because every time I try to debug the code the app crashes the instant Linmotion is created. I suspect its from the fact that onCreate runs the Double.parseDouble code and the values in the field are null. I tried to fix this with the if statements and it still crashes. I'm not sure where to go from here.
Again, if I wasn't clear I just want the values inputted into the EditText to return a double and then use that double in the Java code to run some equations and an alert dialog if not enough fields have been filled in.
EDIT/UPDATE:
I finally figured out what was wrong with my code. I took in advice from everyone and revised accordingly, so here it is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linmotion1);
time = (EditText) findViewById(R.id.eTexttime);
acc = (EditText) findViewById(R.id.eTextacc);
dis = (EditText) findViewById(R.id.eTextdis);
ivel = (EditText) findViewById(R.id.eTextivel);
fvel = (EditText) findViewById(R.id.eTextfvel);
solve = (Button) findViewById(R.id.buttonSolve);
solve.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
count=0;
if (time.getText().toString().equals("")){
count++;
}
if(dis.getText().toString().equals("")){
count++;
}
if(fvel.getText().toString().equals("")){
count++;
}
if(ivel.getText().toString().equals("")){
count++;
}
if(acc.getText().toString().equals("")){
count++;
}
if (count>2){
// TODO Auto-generated method stub
final AlertDialog alert= new AlertDialog.Builder(Linmotion.this).create();
alert.setTitle("Oops");
alert.setMessage("Please input values in at least 3 fields.");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.cancel();
}
});
alert.show();
count=0;
}
if(!(time.getText().toString().equals(""))){
time1=Double.parseDouble(time.getText().toString());
}
if(!(acc.getText().toString().equals(""))){
acc1=Double.parseDouble(acc.getText().toString());
}
if(!(dis.getText().toString().equals(""))){
dis1=Double.parseDouble(dis.getText().toString());
}
if(!(ivel.getText().toString().equals(""))){
ivel1=Double.parseDouble(ivel.getText().toString());
}
if(!(fvel.getText().toString().equals(""))){
fvel1=Double.parseDouble(fvel.getText().toString());
}
} });
}
In regard to the issues I had with the alertdialog I realized that my count integer would continue to increase every time the solve button was clicked. To fix this I simply equaled the integer to 0 at the beginning of the onclicklistener and at the end of the if statement regarding the dialog. Thanks everyone.
It looks to me like you're doing it right. I think the problem might be that it's in your OnCreate method.
Try making the Button Solve's OnClick method run your commented code before doing the logic!
You can get the value from an EditText using getText()..
See this link for more details
According to the docs getText() returns an Editable.
so,
time = (EditText) findViewById(R.id.EditText01);
String value = time.getText().toString();
Now, as i've said earlier, since getText() returns an Editable you need to convert it into String before you use it..
So, change
if (!(time.getText() == null)) {
to
if (!(time.getText().toString() == null)) {
Also, if you want to check if the EditText is empty or not, try like this..
if (!(time.getText().toString() .equals(""))) {
Try this answer..
Your code isn't working because you are trying to read these text fields on creation. This is not what you want to do.
You are trying to access the EditTexts before the page finishes loading. Instead, you need to do this in an event handler, like you have for the buttons. Read the values in an event handler, not in onCreate.
The simplest option would be to add an "update" button and do all those operations in the onClick handler for that button.
Most likely your EditText fields initially contain text, that cannot be parsed with Double.parseDouble (Something like the empty string). A NumberFormatException is thrown is this case. If you want to get the values at the time solve button is clicked, you have to get the text inside OnClickListener.onClick (otherwise you use the initial strings, i.e. the strings in the android:text attributes in the activity_linmotion1 layout). To handle invalid input, you can simply catch the NumberFormatException:
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
double time1 = Double.parseDouble(time.getText().toString());
double acc1 = Double.parseDouble(acc.getText().toString());
double ivel1 = Double.parseDouble(ivel.getText().toString());
double fvel1 = Double.parseDouble(fvel.getText().toString());
double dis1 = Double.parseDouble(dis.getText().toString());
// ... rest of your original listener code
} catch (NumberFormatException ex) {
// show error in dialog or something
}
}
});
Oncreate is the first method called when an activity is created, so by the time the onCreate is called, the editText is having an empty string which you are giving as an input to parseDouble which will give NumberFormatException.
You can avoid this crash by putting a button and handling the button onClick event. Inside this button click you collect the values from editfield. You can handle on click by defining listeners in the following way
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="yourHandlerName" />
Now define your onClick with getText to get text from editfield in the following way
public void yourHandlerName(View v) {
switch(v.getid()) {
case R.id.mybutton: Double.parseDouble(editField.getText().to string());
}
You have to register a Listener. Because onCreate() is called when the Actvity first start. This means that you can't get the text from your EditTexts because the Actvity is creating. But you can use your OnClickListener or other Listeners. You can easily write your commented lines to the OnClickListener. At the time you are clicking the button the method getText().toString() return the values. If you want to do it without clicking on a button use addTextOnChangedListener() on yout EditText.

Make app more effecient by eliminating extra codes

I currently have the following code which starts from A all the way to Z :
if (someId.matches("A") || someId.matches("a")) {
tvLetCap.setText("A");
tvLetLow.setText("a");
ivLetterIcon.setImageResource(R.drawable.apple);
btnDisplayWord.setText("A is for APPLE");
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopPlaying();
mpSound = MediaPlayer.create(MyClass.this, R.raw.a);
mpSound.setLooping(false);
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
mpSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
});
}
if (someId.matches("B") || someId.matches("b")) {
tvLetCap.setText("B");
tvLetLow.setText("b");
ivLetterIcon.setImageResource(R.drawable.ball);
btnDisplayWord.setText("B is for BALL");
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopPlaying();
mpSound = MediaPlayer.create(MyClass.this, R.raw.b);
mpSound.setLooping(false);
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
mpSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
});
}
Would this work as oppose to the above:
switch(someId) {
case A:
setLetter("A");
addIcon("apple");
break;
case B:
setLetter("B");
addIcon("ball");
break;
default:
break;
}
public void setLetter(String strLetter) {
tvLetCap.setText(strLetter);
tvLetLow.setText(strLetter.toLowerCase());
}
public void addIcon(String iconLetter) {
ivLetterIcon.setImageResource(R.drawable. + iconLetter);
btnDisplayWord.setText(iconLetter.charAt(0).toUpperCase() + " is for " + iconLetter.toUpperCase());
}
I am guessing the only issue might be with this line and how would I fix it?:
ivLetterIcon.setImageResource(R.drawable. + iconLetter);
Also will it be possible to take the entire btnPlay function to a different function and just pass the letter like I did with the other functions so it's not repeated over?
I don't know what R and R.drawable are; and what are R.drawable.apple, R.drawable.ball, etc.? Assuming those all have the same type, you might want to make R.drawable an array where the index is 0 for 'A', 1 for 'B', etc., and initialize it so that R.drawable[0] = (whatever the "apple" is supposed to be), R.drawable[1] = (same for "ball"); then use something like
R.drawable[someId.charAt(0).toUpperCase() - 'A']
and similarly for R.raw. Then you wouldn't need a switch at all.
EDIT by kcoppock:
For example:
int[] icons = {
R.drawable.a,
R.drawable.b,
//etc.
};
int[] sounds = {
R.raw.a,
R.raw.b,
//etc.
}
and use icons[index] and sounds[index] to map your values.
Simplest solution: add another parameter to addIcon:
public void addIcon(String iconLetter, int iconResource){
ivLetterIcon.setImageResource(iconResource);
btnDisplayWord.setText(iconLetter.charAt(0).toUpperCase() + " is for " + iconLetter.toUpperCase());
}
Then call it with
setIcon("apple", R.drawable.apple);
As far as reusing the on click listener, it's certainly possible. You could have a single onClick listener that's listening to all the views. When a view is clicked, it's passed in as the argument to the onClick(View view) method. You can use that to find the start/stop button for that view and do whatever to them. Also, there's a useful (and often abused) method pair: setTag(Object object), and getTag(). You might want to look into using those to store the resource ID for the raw audio file you want to play when a button is clicked.

Categories