If condition is ignored and it always jumps to else statement - java

I am a beginner in android and this might be something pretty easy but i cant figure it out
public void login (View view){
EditText et = (EditText) findViewById(R.id.txtUserName);
String text= et.getText().toString();
System.out.println("text = "+text);
if(text.matches("User")){
System.out.println("Im in if");
Intent intent = new Intent(this, Order.class);
startActivity(intent);
}else if(text.matches("HOD")){
Intent intent = new Intent(this,HOD.class);
startActivity(intent);
}else if(text.matches("HR")) {
Intent intent = new Intent(this,HR.class);
startActivity(intent);
}else{
System.out.println("Im in else");
}
}
the if statement doesn't work and it always jumps to the else statement

The method matches() expects a regex as a parameter. But you want to check if the Strings are the same. So you should use if(text.equals("")) instead of matches("").

Try this code because matches func is use for regex
public void login (View view){
EditText et = (EditText) findViewById(R.id.txtUserName);
String text= et.getText().toString();
System.out.println("text = "+text);
if(text.equals("User")){//if you want exact value otherwise you can use text.equalsIgnoreCase("your string")
System.out.println("Im in if");
Intent intent = new Intent(this, Order.class);
startActivity(intent);
}else if(text.equals("HOD")){
Intent intent = new Intent(this,HOD.class);
startActivity(intent);
}else if(text.equals("HR")) {
Intent intent = new Intent(this,HR.class);
startActivity(intent);
}else{
System.out.println("Im in else");
}
}

Related

Failed to pass value from one activity from another (only null value passed)

I tried to pass variable from one activity to another. In the main activity I managed to call back the values using Toast message.
MainActivity.java
search = (Button) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View w) {
subreg = spinner_subregion.getSelectedItem().toString();
reg = spinner_region.getSelectedItem().toString();
pettype = spinner_pet.getSelectedItem().toString();
petnumber = spinner_num.getSelectedItem().toString();
Intent intent = new Intent(MainActivity, Result.class);
intent.putExtra("subregion", subreg);
intent.putExtra("region", reg);
intent.putExtra("petnum", petnumber);
intent.putExtra("pet", pettype);
startActivity(intent);
}
}
However, when I passed the value to Result.java, it only returns null. I tried searching for solutions and still does not work for me. Anyone knows how can I pass the data?
Result.java
Bundle extras = getIntent().getExtras();
if (extras!=null){
subreg = extras.getString("subreg");
reg = extras.getString("reg");
pettype = extras.getString("pettype");
petnumber = extras.getString("petnumber");
}
Try this
MainActivity.java
Intent myIntent = new Intent(this, NewActivity.class);
intent.putExtra("subregion", subreg);
intent.putExtra("region", reg);
intent.putExtra("petnum", petnumber);
intent.putExtra("pet", pettype);
startActivity(myIntent)
Result.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
if(intent ==null){
........
.......
}else{
String subregion= intent.getStringExtra("subregion");
String region= intent.getStringExtra("region");
String petnum= intent.getStringExtra("petnum");
String pet= intent.getStringExtra("pet");
}
}
This is my code after changing it.
MainActivity.java
search = (Button) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View w) {
subreg = spinner_subregion.getSelectedItem().toString();
reg = spinner_region.getSelectedItem().toString();
pettype = spinner_pet.getSelectedItem().toString();
petnumber = spinner_num.getSelectedItem().toString();
Intent intent = new Intent(Pet_sitting.this, Pet_sitting_result.class);
intent.putExtra("subreg", subreg);
intent.putExtra("reg", reg);
intent.putExtra("pettype", pettype);
intent.putExtra("petnumber", petnumber);
startActivity(intent);
}
});
Result.java
Intent intent = getIntent();
if (intent == null){
Toast.makeText(getApplicationContext(),"Null value passed",Toast.LENGTH_SHORT).show();
}
else{
subreg= intent.getStringExtra("subreg");
reg= intent.getStringExtra("reg");
pettype = intent.getStringExtra("pettype");
petnumber = intent.getStringExtra("petnumber");
Toast.makeText(getApplicationContext(),subreg + " " + reg + " " + pettype + " " + petnumber,Toast.LENGTH_SHORT).show();
}
As i can see you are using a Spinner in your code.
So it's Obvious a spinner can give you only one value at a time after Spinning the wheel...
you need to set the Code inside in null value Exception...
like...if it's null don't pass empty value inside intent
maybe it's worked...if it's then reply
MainActivity.java
if(subreg != null){
reg = spinner_region.getSelectedItem().toString();
intent.putExtra("reg", reg);
}
startActivity(intent);
Rsult.java
Intent intent = getIntent();
if (intent == null){
Toast.makeText(getApplicationContext(),"Null value passed",Toast.LENGTH_SHORT).show();
}else{
reg= intent.getStringExtra("reg");
Toast.makeText(getApplicationContext(),reg.toString,Toast.LENGTH_SHORT).show();
}

Making required EditText field in Android Studio

I am starting to make an app. I currently have one EditText. How do I make it required? When nothing is entered into the EditText! the message Please Enter a username should flash on the screen but it still goes to the next scene/activity. How do I stop the submit if the length is 0. I put return false into the public void but I get the following message cannot return a value from a method with void result type
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//Trim whitespace
message = message.trim();
//Checks if the message has anything.
if (message.length() == 0)
{
editText.setError("Please Enter a username!");
//return false;
}
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
try this
string text=editText.getText().toString().trim();
if (TextUtils.isEmpty(text)){
editText.setError("Please Enter a username!");
}else {
//do something
}
Instead of return false;, just write return; with no return type (because the method's return type is void) and it should let you leave the method.
Modify the function like the following.
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//Trim whitespace
message = message.trim();
//Checks if the message has anything.
if (message.length() == 0) {
editText.setError("Please Enter a username!");
return;
}
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Use if and else clause will achieve what you want.
//Checks if the message has anything.
if (message.length() == 0)
{
editText.setError("Please Enter a username!");
//return false;
} else {
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
Try this
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
if (!emptyEdittext(editText, "Please Enter a username!"))
{
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}}
2.Call below method for validation
public boolean emptyEdittext(EditText editText, String msg)
{
/*check edittext length*/
if(editText.getText().toString().length()==0)
{
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
The issue here is that a TextEdit.getText().toString() doesn't give you a null value... It gives you an empty string, which is still a string. Try this. It is the way I do it.
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//Trim whitespace
message = message.trim();
//Checks if the message has anything. This checks to see if
//it has an empty string rather than a null
if (message.equals(""))
{
Toast.makeText(getApplicationContext(),"Please provide a
message!, Toast.LENGTH_SHORT").show();
}else
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}

Passing data from one activity to another and then printing

The problem I am having is that it prints out Null on the second activity and not the actual username that is entered. Is the data being passed to the second activity correctly? Does the second activity need more code? Sorry but not the best at programming.
I have this code in my main class
if (username.getText().toString().equals("batman") &&
password.getText().toString().equals("Joker")) {
Toast.makeText(MainActivity.this, "Username and
password is correct", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.example.*******.loginpage.User");
intent.putExtra("username",String.valueOf(username));
startActivity(new Intent(MainActivity.this, User.class));
This is the code inside my second class.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
Intent intent = getIntent();
String username = getIntent().getStringExtra("username");
TextView textView = (TextView) findViewById(R.id.textView4);
textView.setText("Welcome" + " " + username );
The problem is your intent in your first class
Intent intent = new Intent("com.example.*******.loginpage.User"); <-- have created an intent
intent.putExtra("username",String.valueOf(username));
startActivity(new Intent(MainActivity.this, User.class)); <-- but using new Intent
You have created an intent but you passing new intent. Use your created Intent instead of passing new Intent.
Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",String.valueOf(username));
startActivity(intent);
EDIT
Instead using String.valueOf(username) you must use username.getText(), because String.valueOf(username) is method to translate your object to String.
Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",username.getText());
startActivity(intent);
Two problems here.
First one is that you have to pass the intent where you put your extra instead of creating new one to startActivity, like
Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",username.getText().toString());
startActivity(intent);
Second problem is that username looks like editText, String.valueOf won't pass actual value, use username.getText().toString() like i mentioned in code.

Android Studio - How to open specific activities from a ListView?

I´ve got problems to finish my code to open activities from a list that I made. I´m making an app of equations and I want to have a list of the subjects and when you click on one, it starts the .xml file that have the equations that I already have. I got already the activities stringed to java classes.
Here is my code:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
//get list view from xml
temasListView = (ListView) findViewById(R.id.temasListView);
String[] Temas = {
"Conversion",
"Suma",
"Trigonometria",
"Primera",
"Momento",
"Centro",
"Segunda1",
"MRU",
"MRUA",
"Tiro",
"Segunda2"};
ListAdapter temasAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Temas);
ListView temasListView = (ListView) findViewById(R.id.temasListView);
temasListView.setAdapter(temasAdapter);
temasListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String temas = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(Temas.this, temas, Toast.LENGTH_LONG).show();
if (position == 0) {
Intent intent = new Intent(this, Conversion.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(this, Suma.class);
startActivity(intent);
}
else if (position == 2) {
Intent intent = new Intent(this, Trigonometria.class);
startActivity(intent);
}
else if (position == 3) {
Intent intent = new Intent(this, Primera.class);
startActivity(intent);}
else if (position == 4) {
Intent intent = new Intent(this, Momento.class);
startActivity(intent);
}
else if (position == 5) {
Intent intent = new Intent(this, Centro.class);
startActivity(intent);
}
else if (position == 6) {
Intent intent = new Intent(this, Segunda1.class);
startActivity(intent);
}
else if (position == 7) {
Intent intent = new Intent(this, MRU.class);
startActivity(intent);
}
else if (position == 8) {
Intent intent = new Intent(this, MRUA.class);
startActivity(intent);
}
else if (position == 9) {
Intent intent = new Intent(this, Tiro.class);
startActivity(intent);
}
else if (position == 10) {
Intent intent = new Intent(this, Segunda2.class);
startActivity(intent);
}
});
}
strings.xml:
<resources>
<string name="app_name"></string>
<string-array name="temas">
<item>Conversión de Unidades</item>
<item>Suma de Vectores</item>
<item>Trigonometría</item>
<item>Primera Ley de Newton</item>
<item>Momento de Fuerzas</item>
<item>Centro de Gravedad</item>
<item>Componente de Velocidad</item>
<item>Segunda Ley de Newton</item>
<item>Movimiento Rectilíneo Uniforme</item>
<item>MRUA</item>
<item>Tiro Vertical</item>
<item>Segunda Ley de Newton (DCL)</item>
</string-array>
And my principal activity:
<LinearLayout
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/temas"
android:id="#+id/temasListView"
android:layout_weight="1.05"
android:background="#dadada" />
</LinearLayout>
I need help to finish this please!
When you are inside anonymous inner class this will not refer to your current activity class.
You should use MainActivity.this instead of this
i.e
Intent intent = new Intent(MainActivity.this, Conversion.class);
startActivity(intent);
You can refactor your code like this, to get rid of switch case.
String className= parent.getItemAtPosition(position).toString();
Class myClass=Class.forName("yourpackagename"+className);
Intent intent = new Intent(MainActivity.this, myClass);
startActivity(intent);
No need to use many switch conditions.
Also as pointed in above answer use MainActivity.this instad of Temas.this in your toast message
Change this line from
Toast.makeText(Temas.this, temas, Toast.LENGTH_LONG).show();
to
Toast.makeText(MainActivity.this, temas, Toast.LENGTH_LONG).show();

How to assign value in button and display the value at other activity?

I want to make the ImageView work as button, because I want it be able to click and go to another activity. Each imageView(button) should contain its own value. The problem is, I don't know how to pass the value in the imageView(button) to another activity. This is what I have tried so far:
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
String value = " ";
switch(view.getId())
{
case R.id.imageView2:
value = "5";
break;
case R.id.imageView6:
value = "10";
break;
case R.id.imageView3:
value = "30";
break;
case R.id.imageView02:
value = "50";
break;
case R.id.imageView06:
value = "100";
break;
default:
break;
}
if(view.getId()==R.id.imageView2){
//get the value from switch case and send to other activity
}
Try this way,hope this will help you to solve your problem.
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
switch (view.getId()) {
case R.id.imageView2:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "5");
startActivity(intent);
break;
case R.id.imageView6:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "10");
startActivity(intent);
break;
case R.id.imageView3:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "30");
startActivity(intent);
break;
case R.id.imageView02:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "50");
startActivity(intent);
break;
case R.id.imageView06:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "100");
startActivity(intent);
break;
default:
break;
}
}
};
String valueFromIntent = getIntent().getStringExtra("YourKeyName");
Intent intent = new Intent(YourSecondActivity.this, YourThirdActivity.class);
intent.putExtra("YourKeyName", valueFromIntent);
startActivity(intent);
You can use :
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("YourValueKey", value);
startActivity(i);
here
if(view.getId()==R.id.imageView2){
//here
}
then you can get it from your second activity by :
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("YourValueKey");
You can use Bundle to do the same in Android
//Create the intent
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“imagebuttonValue”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Now in your second activity retrieve your data from the bundle:
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String imagebuttonValue = bundle.getString(“imagebuttonValue”);
Using Intent you can call another activity and even send data with the help of putExtra from one activity to another activity, simply check below piece of code for understanding:
Intent intent= new Intent(currentActivity.this,nextActivity.class);
intent.putExtra("Key",yourvalue);
startActivity(intent);
On next acitivty to retrieve data:
Intent intent = getIntent();
String yourvalue= intent.getExtras().getString("Key");
Pass data trough Intent to your next activity and get your data in that activity like this
Intent intent = new Intent(Activity.this,SecondActity.class);
intent.putExtra("key",value);
startActivity(intent);
Get like this :
Intent intent = getIntent();
String value = intent.getStringExtra("key");
u want to launch a new activity and pass the label value to that ?
if yes then just create an Intent and add the value to it , and use this intent to launch other acitivty.
for example if your value is "5" then :-
Intent intent = new Intent(context) ;
intent.putExtra("key","5");
(refer here)
startActivity(intent);
and at onCreate() method of newly launched activity :-
String value= getIntent.getStringExtra("key"); (Refer here )
Get the values from the Image view. Use Extras and send it to the other Activity.
Lets Say first Activity is X and Next Activity is Y :-
//Include this in your code in the first activity inside your if condition
if(view.getId()==R.id.imageView2){
Intent main= new Intent(X.this, Y.class);
main.putExtra("key", value);
X.this.startActivity(main);
}
At Y Activity onCreate
Intent intent = getIntent();
String value= intent.getStringExtra("key");
Hope it helps.
Thanks!

Categories

Resources