i have to show some operations in Android,,,
but Im having some noob problem,
public void calculateButtonPressed() {
// TODO Auto-generated method stub
Button button = (Button) findViewById(R.id.result);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("myTag", "result biatch");
String text=et.getText().toString();
//toast msg
//Toast msg = Toast.makeText(getBaseContext(),text, Toast.LENGTH_LONG);
// msg.show();
//set Text
tv.setText(text);
//result_tv.setText("copao");
int total = 1+2+3;
result_tv.setText(total);
}
});
}
so the app crashes , as im not using the variable correctly??
If I print the result_tv.setText("copao"); it works fine
but on my basic operation the app crashes,
int total = 1+2+3;
result_tv.setText(total);
so what Im I missing?
thanks!
It is assuming your total value as a string resource Id which might not be available in the R class as a valid resource Id, causing the app to crash.
Change:
result_tv.setText(total);
To:
result_tv.setText(String.valueOf(total));
//OR
result_tv.setText(total + ""); //to parse it as string
use
result_tv.setText(total+""); or result_tv.setText(String.valueOf(total));
Related
This question already has answers here:
Form validation on Button click in android
(3 answers)
Closed 5 years ago.
I am new in android programming and still learning. for practice i started to create a very simple and basic app which calculate age on button click which take birth year as an input.
i manage to get it working and want to do some validation on it. like i have done validating that the value we provide should not be more than current year and i successfully done that.
Now my problem is that i also want to put validation that if no input is been made and button is pressed then it should alert the user by Toast. So far i have tried doing but every time i press button without anything in editText the app just crash.
here's my code.
calcAge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(dob > year){
Toast.makeText(getApplicationContext(), "Provide valid Input", Toast.LENGTH_SHORT).show();
}
else if(String.valueOf(dob) == null){
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
}
else{
dob = Integer.parseInt(String.valueOf(inAge.getText()));
currentYear.setText("Your Curret Year is :- " + year);
yourYear.setText("Your Birth Year is :- "+ dob);
int a = year-dob;
finalAns.setText("Your Age is :- " + a);
inAge.setText("");
}
}
});
above code is of button click. Please provide with some solution
I have also tried putting editText1.getText().toString.trim().lenght()==0 in if condition but that also didn't worked and app just crashes.
try this on button click listner
calcAge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (yourEdittext.getText().toString().equals("")) {
yourEdittext.setError(getString("filed can't be empty"));
yourEdittext.requestFocus();
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
}
}
});
Use this:
String dob = yourEditText.getText().toString();
then check it like this:
if (TextUtils.isEmpty(dob)) {
//show toast
}
You have to do validation like this :
doneDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validationDetails()){
//If get all data do Action
}else{
// Toast.makeText(getApplicationContext(),"Field Missing",Toast.LENGTH_SHORT).show();
}
}
This is the validation part method:
private boolean validationDetails() {
if (userNameET.getText().toString().isEmpty()) {
userNameET.setError("Enter Patient Name");
return false;
}
if (ageET.getText().toString().isEmpty()) {
ageET.setError("Enter Age ");
return false;
}
if (gender.getSelectedItem().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Select Gender",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
On button click, you are checking first if dob is greater than a year. which is not correct. First, check if dob is null or empty. then check for if greater than year
If (dob == null && dob.isEmplty){
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
} else if(dob > year){
Toast.makeText(getApplicationContext(), "Provide valid Input", Toast.LENGTH_SHORT).show();
} else {
//do what ever you want
}
try this on your button click :
if ( yourEditText.getText().toString().equal("")) {
Toast.makeText(getApplicationContext(), "Please Give Some Input", Toast.LENGTH_SHORT).show();
}
I am getting an error when I set the counter to subtract and close the application. I get an error "cannot assign value to final variable counter". If the user logins in 3 times with no success quit the application.
final int counter = 3;
//Set the OKButton to accept onClick
OKButton.setOnClickListener(new View.OnClickListener() {
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
//display text that was inputed for userText and passText
user = userText.getText().toString();
pass = passText.getText().toString();
//create if loop which checks if user and pass equals the credentials
if (user.equals("pshivam") && pass.equals("Bway.857661")) {
//display toast access welcome
String welcome = "Access Granted.";
//Create a Toast to display the welcome string in the MainActivity.
Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show();
setContentView(R.layout.account_main);
}
//create else if loop which checks if user or pass does not equals the credentials
else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){
//displays previous entry
userText.setText(user);
passText.setText(pass);
//allows user to re-enter credentials.
user = userText.getText().toString();
pass = passText.getText().toString();
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
}
});
}
}
Do something like this :
OKButton.setOnClickListener(new View.OnClickListener() {
int counter = 3;
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
You can also call a function from inside onClick which will decrement the variable, or use a static field declared in your class
This How to increment a Counter inside an OnClick View Event and How do I use onClickListener to count the number of times a button is pressed? might help.
Edit:
What you are doing in else part doesn't make sense. You are setting text for userText and passText that you just got using getText() from these. Then you are storing these same values to user and pass. But you aren't using these variables anywhere and they get new values when onClick is called again. Why not keep it simple :
else {
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
i have activity and want to connect it through JDBC the connection is working fine but when i click the ok button as previous connection discard and app crash but when i click ok button with wrong values and toast show message for correct values then that connection string runs and activity would be in override state.
i just want to get the solution that how can i fix that override issue as i can get the result and call the function without calling the connection string again and again because it takes time to connect and when click on button without input mistake app crash.
here is the code:
i want that the connection string works without clicking the button and no affect of override. please help
dbcon=DBConnection.instance(this);
final TextView voternumber=(TextView)findViewById(R.id.txt);
final EditText ed=(EditText)findViewById(R.id.vnumberedit);
final ImageView vok=(ImageView)findViewById(R.id.vnumberok);
dbcon.connect("ip:1433", "pass", "login", "db");
vok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dbcon.connect("ip:1433", "pass", "login", "db");
final String st=ed.getText().toString();
int len=st.length();
if(TextUtils.isEmpty(st)){
Toast.makeText(getApplicationContext(), "Provide Input", Toast.LENGTH_SHORT).show();
}
else{
String id=dbcon.GetID(st,);
txt.setText(id);
}
}
});
I am receiving a String Response from the WebService which I have stored in a String Variable.
Sometimes I get the Hyperlinks in that String Response for Which I have implemented the Logic to Catch the Link.
I m showing that String Response in an Alert Dialog.
My Concern is that I need to Open the Link on the Click to that Link, not as soon as it find the Link in the String which is the Case happening right now.
My Code :
String strTipsMessage = beanTXTIconShowTips.getTips();
if (strTipsMessage.contains("http"))
{
String strHyperLink = strTipsMessage.substring(strTipsMessage.indexOf("http"), strTipsMessage.length());
if (strHyperLink != null)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(strHyperLink));
startActivity(intent);
}
AndroidLog.i(TAG, "strHyperLink : --- " + strHyperLink);
AndroidLog.i(TAG, "Tips_Message : --- > " + strTipsMessage);
}
Utility.showDialogForTips(ActConversations.this, "Tip of the Day...", strTipsMessage, R.drawable.icon_tips, "Ok");
Thanks,
David
I think Linkify is the thing which you are looking for. You can make your text linked to some URL so when it gets clicked, it function appropriately.
Refer this and this link.
As i under stood your problem. I can suggest you to make a TextView and set the text or the url value to that TextView. Add a click listener to that TextView and fire the intent when a user clicks the url text.
Code
TextView t = (TextView) findViewById(R.id.url);
t.setText("http://developer.android.com/training/animation/screen-slide.html");
t.setOnClickListener(clickListener);
here is the listener which listen the textview click
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView vi = (TextView) v;
//Toast.makeText(getApplicationContext(), vi.getText(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(vi.getText()));
startActivity(intent);
}
};
I have some textview in my application
and want to check whether the properties of text on my textview has a value or null.
then i want to display a toast if the value on my textview null
but the toast is not running as it should
this is my code :
public class brekeleV2 extends Activity {
static Context context;
brekeleV2Model r = new brekeleV2Model();
private EditText jalan, kota, postal;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
Button go = (Button)findViewById(R.id.go);
go.setOnClickListener(onGo);
Button reset = (Button)findViewById(R.id.reset);
reset.setOnClickListener(onRes);
jalan =(EditText)findViewById(R.id.jalan);
kota =(EditText)findViewById(R.id.kota);
postal =(EditText)findViewById(R.id.post);
jalan.setText(null);
kota.setText(null);
postal.setText(null);
}
and this is the onClick method code:
private View.OnClickListener onGo=new View.OnClickListener() {
public void onClick(View v) {
if (jalan.getText()!= null && kota.getText()!=null){
switch(v.getId()){
case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.brekele", "com.openit.brekele.brekeleV2Nav");
brekeleV2Nav.putLatLong(lat, lon);
startActivity(maps);
break;
}
}else{
Toast msg = Toast.makeText(brekeleV2.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
if(!textview.getText().toString.matches(""))
{
// not null not empty
}else {
//null or empty
}
This is what I would use.
if (mText1.getText().length() > 0 && mText2.getText().length() > 0) {
// Your code.
}
in the end i found my problem solving. here is my code:
if (jalan.getText().toString().length()>0 || kota.getText().toString().length()>0){
//switch(v.getId()){
//case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.razer", "com.openit.razer.mapRazerNav");
mapRazerNav.putLatLong(lat, lon);
startActivity(maps);
//break;
//}
}else{
Toast msg = Toast.makeText(razerNav.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
i used to check the length, because on my xml i add like this :
android:text=" "
see? this is my fault.
anyway thanks for helping me. :)
TextView has a public length() method you can use to check if there are any characters in the TextView.
if (textView.length() > 0) {
// textView is not null
} else {
// textView is null
}
Try textView.getText() != "" instead.
Are you sure that the else condition is invoked? Debug it!
Maybe you need to put the toast into a runOnUiThread statement:
runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + name + "!");
}
});
Method getText() in TextView returns EditAble that cant compare with String
you should convert EditAble to String using String.ValueOf() method.
String jalanContent = String.ValueOf(jalan.getText());
if(jalanContent.equals(""){
//do your action here
} else {
//some action here
}
hope it'd be usefull
if (jalan.getText()!= null && kota.getText()!=null)
This is the line of code that doesn't work for you.
Best solution for such scenario is using matches("") method for String
So the solution will be:
if (!jalan.getText().toString.matches("") && !kota.getText().toString().matches("")){
// code for not null textViews
}
else
{
//Code for nul textView
}
I would have modified the correct answer a bit (missing () after toString but we're not allowed edit code so:
if(textview.getText().toString().matches(""))
{
// is null or empty
}else {
//not null or empty
}