getText and setText function not working in android studio - java

i tried to make my first converter in android studio with java but 2 functions setText and getText are not working
package com.example.unitconvertor;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity<editTextTextPersonName> extends AppCompatActivity {
private Button button;
private editTextTextPersonName editTextTextPersonName;
private View editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
String s = editText.getText().toString();
int inch = Integer.parseInt(s);
double cm = 2.54 * inch;
editText.setText( "the value is" + cm);
}
});
}
}
i hope that i am clear
thankyou

Try this-
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editText = findViewById(R.id.your_id);//ADD YOUR EDIT TEXT ID HERE
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
String s = editText.getText().toString();
int inch = Integer.parseInt(s);
double cm = 2.54 * inch;
editText.setText( "the value is" + cm);
}
});
}
}

The error is that your "edittext" is declared as view, correct it like this : private EditText edittext;
then, retrieve it by id like this in your onCreate method edittext = findViewById(R.id.your_id);

Related

There is no error in the code but the button doesn't perform any action

I am developing an login and register app. The app is supposed to check if the entered data is correct or not while login or register. The login validation works fine but register doesn't validate data. The register button is supposed to check validations after clicking but nothing happens when I click it. There is no error shown in android studio and the app runs fine.
package com.example.investas;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
private EditText inputUsername,inputEmail,inputPassword,inputCpassword;
Button btnRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
TextView btn=findViewById(R.id.alreadyHaveAccount);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView btn=findViewById(R.id.alreadyHaveAccount);
inputUsername=findViewById(R.id.inputUsername);
inputEmail=findViewById(R.id.inputEmail);
inputPassword=findViewById(R.id.inputPassword);
inputCpassword=findViewById(R.id.inputCpassword);
btnRegister=findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validations();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
}
});
}
private void validations() {
String username=inputUsername.getText().toString();
String email=inputEmail.getText().toString();
String password=inputPassword.getText().toString();
String cpassword=inputCpassword.getText().toString();
if(username.isEmpty() || username.length()<7)
{
showError(inputUsername,"Your username is not valid");
}
else if(email.isEmpty() || !email.contains("#"))
{
showError(inputEmail,"Email is not valid");
}
else if(password.isEmpty() || password.length()<7)
{
showError(inputPassword,"Password must be 7 characters");
}
else if(cpassword.isEmpty() || !cpassword.equals(password))
{
showError(inputCpassword,"Passwords are not matching");
}
else
{
Toast.makeText(getApplicationContext(),"Registration
Successful",Toast.LENGTH_SHORT).show();
}
}
private void showError(EditText input, String your_username_is_not_valid) {
input.setError(your_username_is_not_valid);
input.requestFocus();
}
}
Try to move the following lines out of the OnClickListener, they should be in the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//...
inputUsername = findViewById(R.id.inputUsername);
inputEmail = findViewById(R.id.inputEmail);
inputPassword = findViewById(R.id.inputPassword);
inputCpassword = findViewById(R.id.inputCpassword);
btnRegister = findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validations();
}
});
// ...
}
Doing it this way is necessary for it to be cleaner and to work.
private EditText inputUsername,inputEmail,inputPassword,inputCpassword;
Button btnRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
TextView btn=findViewById(R.id.alreadyHaveAccount);
inputUsername=findViewById(R.id.inputUsername);
inputEmail=findViewById(R.id.inputEmail);
inputPassword=findViewById(R.id.inputPassword);
inputCpassword=findViewById(R.id.inputCpassword);
btnRegister=findViewById(R.id.btnRegister);
TextView btn=findViewById(R.id.alreadyHaveAccount);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validations();
}
});
}

Unknown class 'name'

I am new to Android Studio and trying to get used to it. I have tried to make a trivial app where the user could press a button and a random number would be generated. However, when I used the variables in the code it gave me "unknown class 'get'" and "unknown class 'random'" errors. Code is as follows:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button RollButton = findViewById(id.RollButton);
final TextView resultsTextView = findViewById(id.ResultsTV);
final SeekBar seekBar = findViewById(id.seekBar);
RollButton.setOnClickListener(new onClickListener()
{
Random rnd = new Random(10);
private int random = rnd.nextInt(seekBar.getProgress());
CharSequence get = resultsTextView.getText();
get = String.valueOf(random);
});
}
}
Your OnClickListener looks wrong and you can't use private in this case. So try this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button RollButton = findViewById(id.RollButton);
final TextView resultsTextView = findViewById(id.ResultsTV);
final SeekBar seekBar = findViewById(id.seekBar);
RollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rnd = new Random(10);
int random = rnd.nextInt(seekBar.getProgress());
CharSequence get = resultsTextView.getText();
get = String.valueOf(random);
}
});
}
}

Unable to update TextView with Timer in separate class

I've created a timer and placed it in its own separate class. For some reason when I try to run it it crashes with the following error:
Java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I think it because its trying to update a textview from a class other than Mainactvity but I cant figure out how to get it to work.
Here's the code:
MainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button resetButton;
TextView textTimer;
int elapsedTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elapsedTime = 60;
textTimer = (TextView) findViewById(R.id.textTimer);
resetButton = (Button) findViewById(R.id.resetButton);
final Button resetbttn = (Button) findViewById(R.id.resetButton);
resetbttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CountUp mycountup = new CountUp();
mycountup.count();
}
});
}
}
Timer Class:
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Mat on 24-Feb-17.
*/
public class CountUp extends MainActivity{
TextView textTimer;
Button resetButton;
int elapsedTime;
Handler h;
int RATE = 1000;
MainActivity mainact = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textTimer = (TextView) findViewById(R.id.textTimer);
resetButton = (Button) findViewById(R.id.resetButton);
h = new Handler();
count();
final Button resetbttn = (Button) findViewById(R.id.resetButton);
resetbttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reset();
}
});
}
public void reset(){
elapsedTime = 60000;
}
public void count(){
elapsedTime--;
textTimer.setText(String.valueOf(elapsedTime));
h.postDelayed(r,RATE);
final String endcomparison = textTimer.getText().toString();
if (endcomparison.equals("0")){
reset();
}
}
private Runnable r = new Runnable() {
#Override
public void run() {
count();
}
};
}
findViewById() method actually looks for view in layout file.
when you set layout for activity or fragment using
setContentView(R.layout.activity_main);
findViewById() find those views in that layout. it can't find random objects on the fly.
so in second activity set layout first or create sub class in first activity and then try to update data in textview.
Your are just instantiating an activity, which it's onCreate will never get called.
CountUp mycountup = new CountUp();
mycountup.count(); // view never created so it's null
To load the views you need to use a method like startActivity.
If I am understanding you correctly, if you are extending CountUp from MainActivity then in your manifest, you'd set CountUp as your launching activity. Then using Java inheritance, you don't need to re-find the views, because in CountUp we are calling super.onCreate(savedInstanceState), which calls the MainActivity's onCreate.
public class MainActivity extends AppCompatActivity {
Button resetButton;
TextView textTimer;
int elapsedTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elapsedTime = 60;
textTimer = (TextView) findViewById(R.id.textTimer);
resetButton = (Button) findViewById(R.id.resetButton);
}
}
public class CountUp extends MainActivity{
Handler h;
int RATE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// can access this since inheritance
resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reset();
}
});
h = new Handler();
count();
}
//...
public void count(){
elapsedTime--;
// inheritance
textTimer.setText(String.valueOf(elapsedTime));
h.postDelayed(r,RATE);
final String endcomparison = textTimer.getText().toString();
if (endcomparison.equals("0")){
reset();
}
}
//...
}

What makes the app crash when launched on my phone?

I'm trying to figure out how progress bars work so i made a simple app where you have a plus and minus button which change the progress of the progress Bar. No errors in Android studio, but it crashes when launched on my phone (Honor 5X)
package net.gamepickle.rcap_new;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
int progressStatus = 50;
ProgressBar progressBar = (ProgressBar) findViewById(R.id.happiness_progress);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void run(){
Button plus = (Button) findViewById(R.id.happiness_plus);
Button minus = (Button) findViewById(R.id.happiness_minus);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(progressStatus!=100){
progressStatus += 1;
progressBar.setProgress(progressStatus);
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(progressStatus!=0){
progressStatus -= 1;
progressBar.setProgress(progressStatus);
}
}
});
}
}
Please add your stack trace.
It seems that you are calling
ProgressBar progressBar = (ProgressBar)findViewById(R.id.happiness_progress);
on the class level.
You need to split it.
Declare: ProgressBar progressBar;
and on the onCreate function:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.happiness_progress);
}

Null pointer exception when setting results in a textview

The application is crashing when pressing the Computecost button
package com.example.hw_3;
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import android.content.*;
public class ShoppingExpensesPage extends Activity
{
TextView et;
Button computecost;
Button save;
Button cancel;
RadioGroup drinks;
RadioButton drink;
int tottalcost=0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
et=(TextView)findViewById(R.id.tv11);
Bundle extra = getIntent().getExtras();
String val1 = extra.getString("value");
et.setText(val1);
computecost=(Button)findViewById(R.id.btn11);
computecost.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String val;
int selectedId = drinks.getCheckedRadioButtonId();
drink = (RadioButton)findViewById(selectedId);
val=(String) drink.getText();
if(val=="Juice")
{tottalcost=tottalcost+3;
}
else if (val=="Cola")
{
tottalcost=tottalcost+2;
}
et.setText(Integer.toString(tottalcost));
}
});
save=(Button)findViewById(R.id.btn21);
save.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
String str=Integer.toString(tottalcost);//(String) et.getText();
returnIntent.putExtra("return", str);
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
}
You haven't set the view for drinks.
int selectedId = drinks.getCheckedRadioButtonId();
Find a view for it, before computecost.setOnClickListener:
drinks = (RadioGroup) findViewById(...);
This is the wrong way to compare Strings
if(val=="Juice")
In Java, "==" compares the reference of the Objects but not their values. You need to use .equals()
if("Juice".equals(val))
{ // do something }
If this doesn't solve your problem then please post the logcat from the error but this still needs to be changed.

Categories