Edittext field Not detecting. Throws Null Pointer Exception [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
java.lang.NullPointerException- error in Android
(1 answer)
How to Handle NullPointerException in android?
(2 answers)
Closed 3 years ago.
I tried a number of things but my Application keeps Crashing.
I tried debugging it is returned this error when I run the application.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
package com.zybooks.pigdice;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
final Context context = this;
//private EditText playerName;
private String name;
private int target_score_display;
//public TextView player_name;
private EditText targetScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//player_name = findViewById(R.id.player_name);
targetScore = dialog.findViewById(R.id.enter_target_score);
//playerName = findViewById(R.id.enter_player_name);
Button start_game = findViewById(R.id.start_game);
start_game.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialogbox);
dialog.setTitle("Title...");
Button dialogButton = dialog.findViewById(R.id.start_game_dialog);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String value = targetScore.getText().toString();
target_score_display = Integer.parseInt(targetScore.getText().toString());
Intent intent = new Intent(getApplicationContext(),Gameplay.class);
intent.putExtra("TARGET_SCORE",target_score_display);
Bundle bundle = new Bundle();
bundle.putString("TARGET_SCORE",value);
intent.putExtras(bundle);
startActivity(intent);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
});
dialog.show();
}
});
}
}
Trying to pass input taken in the dialog box to the next Activity. Have been struggling with this for over 3 hours.

You can only call dialog.findViewById after the dialog is created (inside the onClick). It has no content when the Activity is created, so you can't find its views. For example, dialogButton is gotten correctly
So when you try to get the text from the non existing view, it will throw the exception

Related

Text file not found android studio? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to build a simple app for Android can't figure out why my app keeps crashing I have traced it down to this line of code
<code>WG.setRandomWord(words.get(rand.nextInt(words.size())));</code>
I have check my logcat and it showing that my word file is not even being detected com.sagproductions.gamertaggenerator W/System.err: java.io.FileNotFoundException: words.txt: open failed: ENOENT (No such file or directory) but I have my file word file in the document structure.
for more context here is my code:
JAVA wordGenerator
package com.sagproductions.gamertaggenerator;
public class WordGenerator {
private String mRandomWord;
private int mRandomNum;
public WordGenerator(String randomWord, int randomNum){
mRandomNum=randomNum;
mRandomWord=randomWord;
}
public int getRandomNum(){
return mRandomNum;
}
public void setRandomNum(int randomNum){
mRandomNum=randomNum;
}
public String getRandomWord(){
return mRandomWord;
}
public void setRandomWord(String randomWord){
mRandomWord=randomWord;
}
}
Java MainActivity
package com.sagproductions.gamertaggenerator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.lang.String;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
WordGenerator WG;
private Button mSingleWordGenerator;
private Button mTwoWordGenerator;
private Button mThreeWordGenerator;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSingleWordGenerator = (Button)findViewById(R.id.button);
mSingleWordGenerator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generateWord();
editText=(EditText)findViewById(R.id.editText);
editText.setText(WG.getRandomWord(),TextView.BufferType.EDITABLE);
}
});
mTwoWordGenerator = (Button)findViewById(R.id.button2);
mTwoWordGenerator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mThreeWordGenerator = (Button)findViewById(R.id.button3);
mThreeWordGenerator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void generateWord(){
final File file = new File("words.txt");
ArrayList<String> words= new ArrayList<String>();
Random rand=new Random();
try(final Scanner scanner=new Scanner(file)){
while(scanner.hasNextLine()){
String line = scanner.nextLine();
words.add(line);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}
WG.setRandomWord(words.get(rand.nextInt(words.size())));
}
}
The WG field is never initialized, so it's null. So you're probably getting a NullPointerException when you call that method. You should initialize it somewhere, perhaps when you declare it (so WordGenerator WG; would be replaced by something like WordGenerator WG = new WordGenerator(INITIAL_RANDOM_WORD, INITIAL_RANDOM_VALUE);, where INITIAL_RANDOM_WORD and INITIAL_RANDOM_VALUE are some values you define elsewhere).
Edit: It seems that that line is causing the problem because words.size() is 0, which is because of the FileNotFoundException. The correct way to read that file will depend on where you're putting it. See the answers to this question (and the pages they link to) for different ways to correctly read text files in Android.

Crash program of android [duplicate]

This question already has answers here:
Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
(9 answers)
Closed 5 years ago.
I wrote the code to receive name from EditText, but when I initialize EditText variable my app crashes
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class test_activity extends AppCompatActivity {
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_activity);
}
final EditText editText = (EditText) findViewById(R.id.editText);**
public void set_text(View view){
name = editText.getText().toString();
}
}
You need to initialize your views inside onCreate or after it is called. Move your line which is causing the error inside the onCreate method.

I want to make password protected android application

I want to make password protected android app, but when in this simple program system is not matching two strings.
package com.pokmgr;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainPM extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pm_layout);
final EditText pin = (EditText) findViewById(R.id.pinET);
final String pass = pin.getText().toString();
final String code = "ajaj";
Button enter = (Button) findViewById(R.id.enterBtn);
enter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (pass.equals(code)) {
Intent in = new Intent(MainPM.this, Menu.class);
startActivity(in);
}
else {
Intent in = new Intent(MainPM.this, Menu2.class);
startActivity(in);
}
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pm_layout, menu);
return true;
}*/
}
I have made Menu and Menu2 class, but every time Menu2 class is accessed. Even if I enter same pass that is "ajaj" [in this code to test]
i have defined both activities in manifest file.
Can't understand why pass.eqals(code) is not working
The problem is that you are setting pass to the contents of the EditText when the activity gets created. Instead you have to retrieve the contents of your EditText inside the OnClickListener.
Like this:
public void onClick(View v) {
final String pass = pin.getText().toString();
if (pass.equals(code)) {
// do something
} else {
// do something different
}
}
Put pin.getText().toString(); inside onClick of button. You are setting variable pass before the user actually entered something in pinEt EditText.

Button to vibrate makes android app force close

Im just making a simple app that will vibrate when the button is clicked, but for some reason when i click the button the app says it unexpectedly stopped and needed to force close, below is the source code to the main java file and i have used the android vibrate permission in my manifest. can someone tell me why every time I click the vibrate button it gives me the error that it unexpectedly stopped?
package com.test;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.EditText;
public class Main extends Activity {
public final static String EXTRA_MESSAGE = "com.test.MESSAGE";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/* Called when the user clicks the button */
public void sendMessage(View view) {
// do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
public void vibrateMe() {
Vibrator vibrate = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrate.vibrate(500);
}
public void stopVibrating(Vibrator vibrate) {
vibrate.cancel();
}
}
You have to change your vibrateMe() to vibrateMe(View v) if you use android:onClick="vibrateMe"
For instance, if you specify android:onClick="sayHello", you must
declare a public void sayHello(View v) method of your context
(typically, your Activity).
Check the developer page
public void stopVibrating(Vibrator vibrate) {
vibrate.cancel();
}
remove this and then check.

Finish class and get int from class finished to main class

I have a MainClass which one is the full app, when I click one button I go to another class (PopupValores) which one I make it looks like a popup. In this class I have a EditText where you type a integer and a button to close this class. My question is how to get that int typed in PopupClass and use it in MainClass. Heres the code for the PopupValores.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PopupValores extends Activity implements OnClickListener {
TextView texto;
String mensaje;
EditText editable;
Button ok;
public static int cantidad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupvalores);
ok = (Button) findViewById (R.id.Bok);
texto = (TextView) findViewById (R.id.textView1);
editable = (EditText) findViewById (R.id.editText1);
mensaje = editable.getText().toString();
ok.setOnClickListener(this);
ok.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View arg0) {
finish();
return true;
}
});
}
public void onClick(View v){
switch(v.getId()){
case R.id.Bok:
String mensaje;
mensaje = editable.getText().toString();
cantidad = Integer.parseInt(mensaje);
texto.setText("New value " + cantidad + ".");
}
}
}
Then in my MainClass I click a button and it shows the int
int id, vaas = PopupValores.cantidad;
public void onClick (View v)
{
posicion = (ImageCell) v;
seleccion = posicion.mCellNumber;
if (seleccion == -1){
....
toast (id + " " + vaas);
....
}
}
But instead of showing the value declared in PopupValores it shows 0. What I'm doing wrong here?
You need to call the popup Activity with Activity.startActivityForResult()
Once finishing the popup Activity, set the requested result via Activity.setResult() (you can save your data in the intent's bundle)
In your main Activity, override onActivityResult and retrieve the data
Its called startActivityforResult
and has been answered soo many times here on stackoverflow Here is one

Categories