I am trying to create a calculator that shows the result using a toast.
my code is
Button addBtn=(Button)findViewById(R.id.additionBtn);
addBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
EditText inputFirst = (EditText)findViewById (R.id.inputTextFirst);
String message= inputFirst.getText().toString();
EditText inputSecond = (EditText)findViewById (R.id.inputTextSecond);
String message2= inputSecond.getText().toString();
int first = Integer.parseInt(message);
int second = Integer.parseInt(message2);
int sum = first + second;
TextView resTxt = (TextView)findViewById(R.id.viewResult);
resTxt.setText("Result is " +sum);
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
TextView ResTxt=(TextView)findViewbyId(R.id.viewResult);
resTxt.setText("answer is" + sum);
} });
}
it manages to show the result in a label. but with the toast, it is giving me notification that makeText not applicable to arguments.
Change
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
to
Toast.makeText(ActivityName.this ,message, Toast.LENGTH_LONG).show();
makeText takes as first parameter a Context object, but this, in your case, refers to the object of the inner anonymous class new View.OnClickListener
if it inside your activity then you should write this:
Toast.makeText(ActivityName.this ,message, Toast.LENGTH_LONG).show();
if it's outside your class, you'll need to get your activity context
Related
I am trying to change the text of a TextView on my Activity. It happens in a method in the same class as the onCreate method. However, it does not work. I've googled it but found nothing.
This is the error I got:
Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference.
This is the Main Activity, where my TextView is located:
private static TextView welcome;
private static TextView counter;
private static int number;
private static SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Shared Preferences getting called to see if the user has set his name
SharedPreferences sharedpreferences = getSharedPreferences("name", Context.MODE_PRIVATE);
//Getting number
this.number = sharedpreferences.getInt("number", 0);
this.sharedPreferences = sharedpreferences;
Boolean continueName = false;
//Checking if name is set
if (!sharedpreferences.getBoolean("nameSet", false)) {
//If name is not set
Intent intent = new Intent(this, Name.class);
startActivity(intent);
} else {
//if name was already set, default activity pops Up
continueName = true;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting counter and setting it
TextView count = (TextView) findViewById(R.id.txtNumber);
this.counter = count;
//Actionlistener to +1 Button
ActionListeners al = new ActionListeners();
Button plusOne = (Button) findViewById(R.id.btnAddOne);
plusOne.setOnClickListener(al.getPlusOneListener());
//Setting Text View Object
this.welcome = (TextView) findViewById(R.id.welcomeUser);
//If the name is set
if (continueName) {
this.welcome.setText(getString(R.string.welcome) + " " + sharedpreferences.getString("usersName", ""));
}
}
public void setNameNew() throws InterruptedException {
TextView welcomeThis = this.welcome;
new Thread(new Runnable() {
public void run() {
//Setting welcome text
SharedPreferences sp = getSharedPreferences("name", Context.MODE_PRIVATE);
welcomeThis.setText(getString(R.string.welcome) + " " + sp.getString("usersName", ""));
}
});
Thread.sleep(500);
this.welcome.setText(welcomeThis.getText());
}
public void changeViewNumber(int number) {
//Setting new number
this.counter.setText(number);
}
}
Weird is, that the setNameNew method is working and can change the text of the TextField. But the changeViewNumber method is not working.
Im on the activity where the TextView is located. I can't figure it out. May you please help me?
You can call setText for a TextView anywhere in the class as long as the TextView is referenced. When you say one function is working and the other isn't, it's because the reference for the counter is incorrect.
Your counter reference
TextView count = (TextView) findViewById(R.id.txtNumber);
this.counter = count;
Your welcome reference
this.welcome = (TextView) findViewById(R.id.welcomeUser);
You should be referencing the view the way you referenced welcome. You'll want to change the counter reference to the following.
this.counter = (TextView)findViewById(R.id.txtNumber)
Your count variable does nothing and should be removed.
I would also like to make additional notes for your code. You are using the keyword this, it isn't necessary for your code.
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter.
I would also strongly recommend not putting the main thread to sleep, if the thread is sleeping and action is required it will cause your app to crash.
This is useless
TextView count = (TextView) findViewById(R.id.txtNumber);
this.counter = count;
Just do
counter = findViewById(R.id.txtNumber);
This is because you've declared welcome variable globally in class and initialized in onCreate but you forget to initialize counter on the OnCreate method which is why it is throwing a null pointer exception.
this.counter = (TextView) findViewById(R.id.txtNumber);
just initialize your counter variable just like you did on your welcome variable.
The problem was, that I tried to set the text of a TextView with an Integer
The fix was:
String numberString = Integer.toString(number);
counter.setText(numberString);
I'm writing a calculator on Android Studio, in Java, and the app crashes if the user call the result with a dot "." alone or let the EditText field in blank.
I'm looking for a solution for not allowing these two conditions happening, together or individualy, in each of the three fields.
I've already tried TextWatcher and if/else but without success.
The .xml file where the editText field are designed is already set for decimalNumber.
I've already tried this:
if(myfieldhere.getText().toString().equals(".")){myfieldhere.setText("0");}
For each "valor line" and else for the "finalresult" line if everything is fine. Both inside the setOnClickListener block. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peso_layout);
result = findViewById(R.id.layresult);
conc = findViewById(R.id.layconc);
dose = findViewById(R.id.laydose);
peso = findViewById(R.id.laypeso);
calc = findViewById(R.id.laycalcpeso);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
});
}
The ideal output should be the app not crashing if these two conditions happen and sending an error message to the user that input is invalid.
What i'm receiving is the app crashing.
Thank you very much. I'm very beginner in Java and I'm few days struggling with this.
Dear Friend, Your directly trying to convert string input into float and then after your check value but do your code like Below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText edt1,edt2;
TextView txtans;
Button btnsum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1=findViewById(R.id.edt1);
edt2=findViewById(R.id.edt2);
txtans=findViewById(R.id.txtans);
btnsum=findViewById(R.id.btnsum);
btnsum.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.btnsum){
float n1,n2;
String value1=edt1.getText().toString();
String value2=edt2.getText().toString();
if(value1.equals("") || value1.equals(".")){
n1=0;
}else {
n1= Float.parseFloat(value1);
}
if(value2.equals("")|| value2.equals(".")){
n2=0;
}else{
n2= Float.parseFloat(value2);
}
float ans=n1+n2;
txtans.setText(ans+"");
}
}
}
See In above code, First get value from edittext and then check wheather it contain null or "." inside it. if it contains then store 0.0 value in some variable. then after make sum and display in textbox.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String myvalor = myfieldhere.getText().toString();
if(myvalor.equals(".") || myvalor.isEmpty())
{
// toast error : incorrect value
return;
}
try
{
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
catch(Exception exp){// toast with exp.toString() as message}
}
});
use TextUtils for check empty String its better
if(TextUtils.isEmpty(peso.getText().toString())||
TextUtils.isEmpty(conc.getText().toString())||
TextUtils.isEmpty(dose.getText().toString())){
return;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.screenlocked);
//Retrieve stored ID
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
LoginID = unique.getString("identifier", "");
//Retrieve stored phone number
final String phoneNumber = unique.getString("PhoneNumber", "");
phoneView = (TextView) findViewById(R.id.phone);
phoneView.setText(phoneNumber.toString());
//Retrieve user input
input = (EditText) findViewById(R.id.editText1);
userInput = input.getText().toString();
//Set login button
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
compareID();
}
});
}
public void compareID(){
if (userInput.equals(LoginID)){
//phone screen unlocked
//continue
Toast.makeText(ScreenLockActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else{
count += 1;
input.setText("");
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
}
}
I am developing a login activity and I would like to record down how many times the user tried to login, so every time there is a login attempt the count will increment by one... but when i run the activity, this error appears in my logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1,
Can someone help me solve this problem?
Here is your mistake:
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
the makeText you are trying to invoke here, is the makeText that takes as second parameter a resId. See here for more info. Since you want to print the count value, you have to convert it in a String.
String value = String.valueOf(count);
Toast.makeText(ScreenLockActivity.this, value, Toast.LENGTH_SHORT).show();
This line should be inside onClick() or compareID():
userInput = input.getText().toString();
I have an activity, called AddItem, which contains a couple fields that the user fills out and I am now trying to pass them to another activity. I was able to get the first two fields by doing this:
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
The above code worked fun, but then I tried to get another value which I then cast to a double like so:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
It's kind of long and complicated but I'm basically doing the same thing with the exception of parsing the String and converting it to a double value. I determined that this is the problem code because when I comment it out the rest of the app runs fine.
Here is my Activity:
public class AddItem extends AppCompatActivity {
EditText inputedTask, inputedDescription, inputedLatitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
inputedTask = (EditText) findViewById(R.id.inputName);
inputedDescription = (EditText) findViewById(R.id.description);
inputedLatitude = (EditText) findViewById(R.id.Latitude);
}
public void onSaveItemButton(View view) {
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
if (messageText.equals(""));
else {
Intent intent = new Intent();
intent.putExtra(Intent_Constant.INTENT_MESSAGE_FIELD, messageText);
setResult(Intent_Constant.INTENT_RESULT_CODE, intent);
finish();
}
}
}
You need to make a public method for the onClick, from the documentation:
Within the Activity that hosts this layout, the following method
handles the click event:
/** Called when the user touches the button */
public void sendMessage(View view) {
// Do something in response to button click
}
The method you declare in the android:onClick attribute must have a
signature exactly as shown above. Specifically, the method must:
Be public
Return void
Define a View as its only parameter (this will
be the View that was clicked)
So you need to change the method to public:
public void onSaveItemButton(View view) {
...
}
UPDATE:
As the error log says:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at cs4720.cs.virginia.edu.duysalahandroidminiproject02.AddItem.onSaveItemButton(AddItem.java:33)
You need to catch for empty string in the following code:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
so, check it first:
String val = ((EditText) findViewById(R.id.Latitude)).getText().toString();
if(!val.equals("") {
double Latitude = Double.parseDouble(val);
}
You are calling onSaveItemButton method from a view that is not initialized. You must initialize btnChangeDate in the onCreate from the activity.
Check this answer
So in Android/Java, I need to access a global variable that is an EditText[]that I create above the onCreate method of my activity inside of an onClickListener. Here is the variable:
public class NCDTCPRelayActivity extends Activity {
final EditText[] relayLabelEdits = new EditText[n];
Where n is another global variable integer.
My problem is that in order to access these EditText inside an onclickListener i had to make final to access inside the onClickListener, but I need to assign relayLabelEdits to a new EditText[] if the value of n changes which it is wont to do.
Below is the onClickListener (the main portion of the app is to open a tcp socket and control relays via WiFi so just ignore the socket information and those System.out.println that point to the relayLabelEdits return null unless the relayLabelEdits variable is final):
Button save = new Button(this);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText[] saveTargets = relayLabelEdits;
System.out.println("Direct: " + relayLabelEdits[0]);
System.out.println("first try " + saveTargets[0]);
//Creates string to create the database names on the fly
String relayToSave;
int myNum = 0;
try {
myNum = Integer.parseInt(portEditText.getText().toString());
} catch(NumberFormatException nfe) {
Toast toast = Toast.makeText(getBaseContext(), "The Port Number you entered must only contain numbers", Toast.LENGTH_LONG);
toast.show();
return;
}
System.out.println(ipAEditText.getText().toString());
cPanel.saveString("ipA", ipAEditText.getText().toString());
cPanel.saveInt("port", myNum);
for (int i = 0; i < n; i++) {
relayToSave = "relay" + (i+1);
System.out.println("HERE I AM");
System.out.println(relayLabelEdits[i]);
cPanel.saveString(relayToSave, relayLabelEdits[i].getText().toString());
//cPanel.saveString(relayToSave, "It worked");
System.out.println("HERE I AM");
}
if (cPanel.connect() == true){
createMainContainer();
setContentView(sView);
getRelayNames();
displayRelayNames();
updateButtonText();
}
else {
Toast toast = Toast.makeText(getBaseContext(), "Could Not Connect, check IP address and Port Number", Toast.LENGTH_LONG);
toast.show();
}
}
});
So any ideas on how I can access the EditText[] inside the onClickListener without making it final?
Why don't you make the listener a class outside and pass the activity reference to it?