This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Causing error when setText a value in edittext. Id Given is Correct ,if i give set Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
Code Given Below here i cant setText Otp Code "otpcode.setText("12345");" in oncreate it works perfectely.
when i give it in the method"recivedSms".it didn't work.
public class Change_Password_Activity extends AppCompatActivity {
EditText user_name,pass_wd;
public EditText otpcode;
private Button btn_submit;
private String username,otp,password;
private ProgressDialog prgDialog;
private Typeface typeface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change__password_);
typeface = GlobalVariables.getTypeface(Change_Password_Activity.this);
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
otpcode = (EditText)findViewById(R.id.otpedittext);
user_name = (EditText) findViewById(R.id.edittext_ch_user);
pass_wd = (EditText) findViewById(R.id.edittext_ch_passwd);
btn_submit = (Button) findViewById(R.id.button_changepswd);
otpcode.setTypeface(typeface);
user_name.setTypeface(typeface);
pass_wd.setTypeface(typeface);
btn_submit.setTypeface(typeface);
}
public void recivedSms(String message)
{
try
{
int smsnumbr= Integer.parseInt(message);
otpcode.setText(smsnumbr);
}
catch (Exception e)
{
Log.e("error", String.valueOf(e));
}
if you are trying to set smsnumbr to edittext then it will give null pointer exception as in setText(Integer) android tries to find a resource from R.java file with given integer as id. to achieve what you want you should use String.valueOf(..) instead.
int smsnumbr= Integer.parseInt(message);
otpcode.setText(String.valueOf(smsnumb));
Related
This question already has answers here:
What is an off-by-one error and how do I fix it?
(6 answers)
Closed 1 year ago.
Hello I am new to android java codding I created a "login activity" and "Users class"
and my condition is to add a number of users and pass to the "Users class" and check if the password given is correct then log in,
however, it works correctly when I put the right password but if the password is wrong the app just crashes and the if-else condition does not run.
public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText Password;
private TextView Loginmsg;
public Button Btlogin;
public static int Counter;
public static ArrayList <User> mUsers;
public static int Tester;
private String nameHolder;
private String passHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = findViewById(R.id.etpsudo);
Password = findViewById(R.id.etpaswword);
Loginmsg = findViewById(R.id.txtlog);
Btlogin = findViewById(R.id.btnlogin);
Tester=0;
Btlogin.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
nameHolder=Name.getText().toString();
passHolder=Password.getText().toString();
for(int i=0; i<=mUsers.size();i++){
if((nameHolder.equals(mUsers.get(i).getmNom()))&&(passHolder.equals(mUsers.get(i).getmPass()))){
Counter=i;
i=mUsers.size()+1;
Tester=1;
}
}
if (Tester==1){
Intent drawless = new Intent(MainActivity.this,newacc.class);
startActivity(drawless);
}
else{
Loginmsg.setText("eroor");
}
}
});
mUsers = new ArrayList<>();
mUsers.add(new User("amine","12345"));
mUsers.add(new User("bouhali","4523"));
mUsers.add(new User("khawla","ae12"));
}
}
You have a problem in you for loop
Look carefully at
for(int i=0; i<=mUsers.size();i++).
ArrayLists are index starting at 0. This mean that the last element is less than the total number, not equal to the total number.
Also I agree with Dave, use a break rather than modifying the value of i to end the loop, it is much clearer.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have a problem in my code in android studio, I created it to say "Hello" when the person "abc" writes but that didn't work . can u plz help me. here is my codes
final Button butt=(Button)findViewById(R.id.butt);
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText frag =(EditText)findViewById(R.id.frag);
final TextView hello=(TextView)findViewById(R.id.hello);
String verb =frag.getText().toString();
if (verb=="abc"){
hello.setText("Hello");
Because the condition in if block returns false
Use this code instead.
final Button butt = (Button) findViewById(R.id.butt);
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText frag = (EditText) findViewById(R.id.frag);
final TextView hello = (TextView) findViewById(R.id.hello);
String verb = frag.getText().toString();
if ("abc".equals(verb)) {
hello.setText("Hello");
}
}
}
When comparing string, always use .equals method
Example:
String str1 = "yourstring1";
String str2 = "yourstring2";
if(str1.equals(str2))//return false
{...}
This question already has answers here:
How to disable an Android button?
(13 answers)
Closed 5 years ago.
I have a problem, I want to disable a button in onCreate method, please share the way of disabling any button at runtime in onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_requests_interface);
Intent intent = new Intent(this, AdminPopup.class);
startActivity(intent);
String fName = getIntent().getStringExtra("fName");
TextView tfName = (TextView)findViewById(R.id.fName);
tfName.setText(fName);
String vuEmail = getIntent().getStringExtra("VUEmail");
TextView tEmail = (TextView)findViewById(R.id.vuEmail);
tEmail.setText(vuEmail);
EditText vuEmailTest = (EditText)findViewById(R.id.vuEmail);
String email = vuEmailTest.getText().toString();
String str = email.substring(0,2);
if(str.equals("bc")){
String str2 = email.substring(3,9);
boolean digitsOnly = TextUtils.isDigitsOnly(str2);
if (digitsOnly){
Button accButton = (Button)findViewById(R.id.accButton);
}
}
else{
Button accButton = (Button)findViewById(R.id.accButton);
}
}
Try this:
Button accButton = (Button) findViewById(R.id.accButton);
accButton.setEnabled(false);
Note that in your posted code, you are setting the button with findViewbyId(), which should be findViewById() (the By needs to be capitalized).
Button button =(Button) findViewById(R.id.buttonid);
button.setVisibility(View.GONE);
Use android:enabled="false" in xml or accButton.setEnabled(false) in code
Also, it's better to check is numeric by this method:
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Do this:
Button b = (Button) findViewById(R.id.mybutton);
b.setEnabled(false);
This question already has answers here:
java.lang.numberformatexception: invalid double: " "
(6 answers)
Closed 6 years ago.
I have 6 edit text fields, and I'm trying to input them into a sqlite database and I'm trying to parse 5 of them into doubles, but it throws that error and I can not figure out what to do.
I've tried to use valueOf(String) and parsing, but neither seem to work.
I've used Long's and Integers as well, and have come to the same issue as well
Here's the code:
public class EditClass extends AppCompatActivity {
EditText name, exam, quiz, assignment, participation, lab;
String iName, sExam, sQuiz, sAss, sPart, sLab ;
double iExam, iQuiz, iLab, iAss, iPart;
FloatingActionButton fab;
Database database;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_class);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = (EditText) findViewById(R.id.class_name);
exam = (EditText) findViewById(R.id.exam_weight);
quiz = (EditText) findViewById(R.id.quiz_weight);
assignment = (EditText) findViewById(R.id.assignment_weight);
participation = (EditText) findViewById(R.id.participation_weight);
lab = (EditText) findViewById(R.id.lab_weight);
iName = name.getText().toString();
sExam = exam.getText().toString();
sQuiz = quiz.getText().toString();
sAss = assignment.getText().toString();
sPart = participation.getText().toString();
ImageView create = new ImageView(this);
create.setImageDrawable(getResources().getDrawable(R.drawable.checkmark));
fab = new FloatingActionButton.Builder(this).setContentView(create).build();
fab.setBackground(getResources().getDrawable(R.drawable.button_action_lightblue_ztek));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addData();
}
public void addData(){
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
/**
* Errors with parsing into integer form, comes up with NumberFormatException
*/
database.insertData(iName,
iExam = Double.valueOf(sExam),
iQuiz = Double.valueOf(sQuiz),
iLab = Double.valueOf(sLab),
iAss = Double.valueOf(sAss),
iPart = Double.valueOf(sPart));
Toast.makeText(EditClass.this, "Data was Successfully Inserted", Toast.LENGTH_SHORT).show();
}catch (Exception e){
String error= e.toString();
Toast.makeText(EditClass.this, "Data was Not Inserted", Toast.LENGTH_SHORT).show();
System.out.println(error);
}
}
});
}}
I've now ended up changing the addData method to this, but it comes up as null now, for both the string and doubles.
Here's the method:
public void addData(){
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
/**
* Errors with parsing into integer form, comes up with NumberFormatException
*/
database.insertData(name.getText().toString(),
Double.parseDouble(exam.getText().toString()),
Double.parseDouble(quiz.getText().toString()),
Double.parseDouble(lab.getText().toString()),
Double.parseDouble(assignment.getText().toString()),
Double.parseDouble(participation.getText().toString()));
Toast.makeText(EditClass.this, "Data was Successfully Inserted", Toast.LENGTH_SHORT).show();
}catch (Exception e){
String error= e.toString();
Toast.makeText(EditClass.this, "Data was Not Inserted", Toast.LENGTH_SHORT).show();
System.out.println(error);
}
}
});
}
onCreate() only runs once and is currently the only place you call getText(). Therefore, the values in iName, sExam, etc are all the default values you have for those fields - not the current values when your FloatingActionButton is clicked.
Instead, move the iName = name.getText().toString(); etc lines into your OnClickListener to get the current values when the button is clicked.
Also note that you cannot use Double.valueOf() on an empty field (that's the NumberFormatException you are getting) - consider wrapping each call in TextUtils.isEmpty() to check to see if there is any value at all.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
This is what I'm trying to do for several hours:
I've got a MainActivity.java file (listing below) and a fragment_start.xml file with a start button. Tapping the start-button should display the activity_main.xml file with points-/round- and countdown-Textviews. It doesn't work and this is what is happening:
The logcat tells me:
PID: 1240 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
The emulator displays: Unfortunately, GAME has stopped.
Necessary to mention that I'm rather new in programming?
Thanks for any advice!
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener {
private int points;
private int round;
private int countdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showStartFragment();
}
private void newGame () {
points=0;
round=1;
initRound();
}
private void initRound() {
countdown = 10;
update();
}
private void update () {
fillTextView(R.id.points, Integer.toString(points));
fillTextView(R.id.round, Integer.toString(round));
fillTextView(R.id.countdown, Integer.toString(countdown * 1000));
}
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text);
}
private void showStartFragment() {
ViewGroup container = (ViewGroup) findViewById(R.id.container);
container.removeAllViews();
container.addView(
getLayoutInflater().inflate(R.layout.fragment_start, null) );
container.findViewById(R.id.start).setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.start) {
startGame();
}
}
public void startGame() {
newGame();
}
}
The problem is the tv.setText(text). The variable tv is probably null and you call the setText method on that null, which you can't.
My guess that the problem is on the findViewById method, but it's not here, so I can't tell more, without the code.
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null
But from your code, I can't find why this method returns null. Try to track down,
what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method.
From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text);
}
If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById(), and the actual exception is thrown when you try to call a function setText() on null. You should post your XML for R.layout.activity_main, as it's hard to tell where things went wrong just by looking at your code.
More reading on null pointers: What is a NullPointerException, and how do I fix it?