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);
}
Related
The following code comes from a Android App for Handheld Scanner Device; the Device should scan different Barcodes and QR codes, different digit ranges, numbers and digits;
that´s why I decided to go with .matcher instead of Regular Expressions; The following code works fine when it comes to parse combinations like "1367+700" etc.:
editBarcode.setOnClickListener(new View.OnClickListener() { //tv is the TextView.
public void onClick(View v) {
code = editBarcode.getText().toString();
XXXStorageApp.getInstance().setScannedCode(code);
editBarcode.setText("");
if (ScanService.checkEnteredCode(code, basic, content, MainDetailActivity.this) == true) {
return;
}
else {
Pattern p = Pattern.compile(code);
Matcher matcher = p.matcher(Pattern.quote("\\+"));
if (matcher.find()){
retrievedItemNo = String.valueOf(matcher);
}
String intermediateItemNo = code;
String[] splitString = intermediateItemNo.split(Pattern.quote("+"));
retrievedItemNo = splitString [0];
String intermediateString = code.substring(code.indexOf("+") + 1);
retrievedQuantity = intermediateString.split("\\+")[0];
if(XXXStorageApp.getInstance().NoList.contains(retrievedItemNo) || XXXStorageApp.getInstance().EanList.contains(scannedCode)){
Log.d(String.valueOf(XXXStorageApp.getInstance().NoList),"NoList");
Log.d(String.valueOf(XXXStorageApp.getInstance().EanList),"EanList");
}
else {
Log.d(String.valueOf(XXXStorageApp.getInstance().NoList),"NoList");
Log.d(String.valueOf(XXXStorageApp.getInstance().EanList),"EanList");
Vibrator vibrator;
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
Toast.makeText(getApplicationContext(), R.string.not_in_database, Toast.LENGTH_LONG).show();
return;
}
if (!addBooking.isEnabled() == true && removeBooking.isEnabled())
{
AddBookingMessage message = new AddBookingMessage();
message.setType("add-item-to-pallet");
message.setPalNo(receivedPalNo);
message.setItem(retrievedItemNo);
if (String.valueOf(retrievedQuantity).matches("") ||
retrievedQuantity == null ||
retrievedQuantity.trim().isEmpty()) {
final Dialog dialog = new Dialog(MainDetailActivity.this, 0);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView textView = dialog.findViewById(R.id.textView4);
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retrievedQuantity = textView.getText().toString();
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.putBookingOnPallet(basic, message, MainDetailActivity.this);
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
else
{
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.putBookingOnPallet(basic, message, MainDetailActivity.this);
}
}
if (addBooking.isEnabled() && !removeBooking.isEnabled() == true)
{
AddBookingMessage message = new AddBookingMessage();
message.setType("remove-item-from-pallet");
message.setPalNo(receivedPalNo);
message.setItem(retrievedItemNo);
message.setEan(scannedCode);
if (spinner != null && spinner.getSelectedItem() != null) {
source = spinner.getSelectedItem().toString();
}
if (String.valueOf(retrievedQuantity).matches("") || retrievedQuantity == null
|| retrievedQuantity.trim().isEmpty())
{
final Dialog enterDialog = new Dialog(MainDetailActivity.this, 0);
enterDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
enterDialog.setCancelable(true);
enterDialog.setContentView(R.layout.sortiment_layout);
enterDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView enterQuantityView = enterDialog.findViewById(R.id.textView4);
Button okQuantityButton = enterDialog.findViewById(R.id.ok);
okQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retrievedQuantity = enterQuantityView.getText().toString();
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.removeItemFromPallet(basic, message, MainDetailActivity.this);
enterDialog.dismiss();
}
});
Button cancelQuantityButton = enterDialog.findViewById(R.id.cancel);
cancelQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enterDialog.dismiss();
}
});
enterDialog.show();
}
else {
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.removeItemFromPallet(basic, message, MainDetailActivity.this);
}
}
editBarcode.setText("");
}}
however the App crashes with a
java.lang.NumberFormatException: For input string: "4018.B"
So, the problem here is to parse a string like "4018.B+95".
I don´t know how to handle this mixed input String with .matcher and definitely don´t want to use a Regular Expression; so basically, all of the following Input Strings - including Type conversion - should be handled correctly:
1256+70
1235.B+70
1256+70+DB
1235.B+70+DB
1256+70+DB2020-123
1235.B+70+DB2020-123
1256+0+DB2020-123
1235.B+0+DB2020-123
So, basically I need a condition for .matcher() that handles input like
"1235.B"
a mixed Integer and String; I need to store it in one variable which is of type String;
the problem here is that the "." in "1235.B" is not recognized and the App crashes hence, because the Number contains a string (".B")
So, two questions here:
How can I use .matcher() to recognize if a String contains ".B" or ".C" or anything similar?
How do I handle the different Types correctly in one Variable type?
As I am stuck with this, I would appreciate any hints or help.
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();
}
I am doing a project where I have to program a pedometer. The pedometer will work using a button and you have to tell the length of your steps. I made a main activity that let you choose between go anonymous an another one that let you register. The aplication works when I register or when I go anonymous, and the step length is passed well to the third activity, an activity where you can press a button and increase the number of steps done and the meters done. In this activity there is another button to configure the length of your steps and I want to pass all the info to the anonymous activity to change only the length of the steps and I pass all the info. I used the method putExtra() and getIntent().getExtra().getString(), but only works going to the main activity to the registe/anonymous activity and then going to the pedometer activity, but when i want to configure the length of the steps the aplications stops.
This is my code for the anonymous activity:
if(this.getIntent().hasExtra("name")){
names=this.getIntent().getExtras().getString("name");
}else{
names="";
}
if(this.getIntent().hasExtra("user")){
userName=this.getIntent().getExtras().getString("user");
}else{
userName="";
}
if(this.getIntent().hasExtra("pass")){
password=this.getIntent().getExtras().getString("pass");
}else{
password="";
}
if(this.getIntent().hasExtra("feetBefore")){
footBefore=this.getIntent().getExtras().getString("feetBefore");
}else{
footBefore="0";
}
if(this.getIntent().hasExtra("steps")){
stepsDone=this.getIntent().getExtras().getString("steps");
}else{
stepsDone="0";
}
Button continueBtn = findViewById(R.id.continueAnonymous);
foot = findViewById(R.id.lengthFeetAnonymous);
continueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String footSize = String.valueOf(foot.getText());
if(!footSize.equals("")) {
Intent mainAnonymous = new Intent(getApplicationContext(), Main5Activity.class);
mainAnonymous.putExtra("name", names);
mainAnonymous.putExtra("user", userName);
mainAnonymous.putExtra("pass", password);
mainAnonymous.putExtra("feet", footSize);
mainAnonymous.putExtra("steps", stepsDone);
mainAnonymous.putExtra("feetBefore", footBefore);
startActivity(mainAnonymous);
finish() ;
}else{
Toast.makeText(Main4Activity.this, "You have to complete all the backets.",
Toast.LENGTH_SHORT).show();
}
}
});
This is the code of my pedometer activity:
Bundle parameters = this.getIntent().getExtras();
if(parameters != null){
name = parameters.getString("name");
username = parameters.getString("user");
password = parameters.getString("pass");
String foot = parameters.getString("feet");
String footBefore = parameters.getString("feetBefore");
String stepsDone = parameters.getString("steps");
if(stepsDone!=null) cont = Integer.parseInt(stepsDone);
else cont =0;
if(footBefore!=null)feetBefore = Integer.parseInt(footBefore);
else feetBefore =0;
if(foot !=null)feet = Float.parseFloat(foot)/100;
else feet = (float) 0.43;
cont2 = cont*feetBefore;
}else {
name = "";
username = "";
password = "";
feet = (float) 0.43;
}
increase = findViewById(R.id.increaseStep);
configuration = findViewById(R.id.confBtn);
saveMain = findViewById(R.id.saveBtnMain);
resume = findViewById(R.id.resumBtn);
final TextView steps = findViewById(R.id.stepCounter);
final TextView km = findViewById(R.id.kilometerCounter);
steps.setText(String.format(Locale.ENGLISH,"%d Steps",cont));
String aux =String.format(Locale.ENGLISH,"%.2f Meters", cont2);
km.setText(aux);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cont++;
steps.setText(String.format(Locale.ENGLISH,"%d Steps",cont));
cont2 += feet;
String aux =String.format(Locale.ENGLISH,"%.2f Meters", cont2);
km.setText(aux);
}
});
configuration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent conf = new Intent(getApplicationContext(), Main4Activity.class);
conf.putExtra("name", name);
conf.putExtra("user", username);
conf.putExtra("pass", password);
String aux2 = String.valueOf(cont);
conf.putExtra("steps", aux2);
float aux4 =feet*100;
String aux3 = String.valueOf(aux4);
conf.putExtra("feetBefore", aux3);
startActivity(conf);
finish() ;
}
});
}
I started to learn android yesterday so I don't know what I am doing wrong. If you can help me I would apreciate it. In addition, I think it's something about the bundle.
Add all data in a bundle and check only if bundle!=null –by Milan Pansuriya
I don't know the difference between using a bundle to pass al the data and putExtra to my intent but this works for me. Thank you Milan Pansuriya.
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");
}
}
I'm working on an android app where the user presses a button, a text is generated, then there is a menu option to share/export the text.
Here are the relevant code parts (for clarity, I don't paste the entire code, but if you need anything just let me know)
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String savedText = SomeMethod(); //the string used here is obtained through another method
TextView resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
}
});
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_export) {
exportPage();
return true;
}
return super.onOptionsItemSelected(item);
}
public void exportPage() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, savedText);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
My question:
How can I actually send the string generated from the SomeMethod method (i.e. savedText, see comment in line 5 of the code) to the exportPage method? As it stands, the code gets the value for the savedText string from the initialized string value, not the value generated by the SomeMethod method.
What I have tried:
Looking for answers to similar questions, I discovered that one way is the one described here: How to pass a string from one method to another method in Java
I attempted to modify my code accordingly, like this:
TextView resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
exportPage(); // <<< attempting to send the string to the exportPage method
public void exportPage() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, this.savedText); //<<< modified
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
But this gives me the error that the savedText string is not initialized. I attempted to initialize it, but now it again uses that global value instead of the modified one.
At this point I thought that maybe I was working with a local variable instead of an instance one (I'm a real beginner, so I'm still learning these aspects), and tried the other way:
TextView resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
exportPage(savedText); // <<< attempting to send the string to the exportPage method
public void exportPage(String savedText) { //<<<< modified
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, savedText);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
But now there is another error. On the part of the code where the menu item is selected:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_export) {
exportPage();
return true;
}
return super.onOptionsItemSelected(item);
I get an error because the exportPage method expects a String. I tried to modify this with exportPage(savedText); but of course now it doesn't recognize the string savedText and wants me to initialize it (doing that, I go back to the original problem, getting the global string value instead of the generated one).
As I said, I'm a beginner, so I'm sure this is a very simple error on my behalf, but I just can't figure it out. Any ideas?
use this
public void exportPage() { //<<<< modified
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, resp.getText().tostring());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
Declare resp TextView as global variable, then just get text value directly from TextView:
private TextView resp = null;
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String savedText = SomeMethod(); //the string used here is obtained through another method
resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
}
});
public void exportPage() {
String savedText = this.resp != null ? this.resp.getText().toString() : "";
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, savedText);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
Hello Try this if it may help,
1) call the method from the onClick method itself
2) Add the parameter to the method for getting the value
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String savedText = SomeMethod(); //the string used here is obtained through another method
TextView resp = (TextView) findViewById(R.id.TextOutput);
resp.setText(savedText);
//Call method exportPage so that it can get value on the go
exportPage(String savedText);
}
});
public void exportPage(String savedText) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, savedText);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}