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.
Related
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
Im getting E/AndroidRuntime: FATAL EXCEPTION: main at com.test.megatest.Main4Activity$1.onClick(Main4Activity.java:37).
Ive read tons of posts on this forum but I cant figure out what Im missing,
This is the Main4Activity.java:
package com.test.megatest;
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.FileOutputStream;
import java.io.IOException;
public class Main4Activity extends AppCompatActivity {
EditText inputText;
TextView response;
Button saveButton, readButton;
private String filename = "SampleFile.txt";
private String filepath ="MyFileStorage";
File myExternalFile;
String myData ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
inputText = (EditText) findViewById(R.id.myInputText);
response = (TextView) findViewById(R.id.response);
saveButton =(Button) findViewById(R.id.saveExternalStorage);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile); //LINE 37
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText("");
response.setText("SampleFile.txt saved to somewhere..");
}
});
}
}
Can someone here just point me in the right direction? :)
The file you try to open an output stream for is NULL.
You declared it as a member but never initialized it.
Initialize file as
File myExternalFile=new File("SampleFile.txt");
Your Main4Activity has a "File" variable:
File myExternalFile;
But without assigning any object/value to that variable You are trying to use it in:
FileOutputStream fos = new FileOutputStream(myExternalFile);
Obviously you will get an Exception for that :P
You should initialise "myExternalFile" using any of the 4 public constructors specified at java.io.File (depending on your use case).
For example:
// If you need a "Persistent" file in private directory of your application
//
myExternalFile = new File(this.getFilesDir() ,"name_of_your_file.txt");
//
// or
// If you need a "Cache" file
myExternalFile = new File(this.getCacheDir() ,"name_of_your_file.txt");
Locations of above files on your Android filesystem is:
# Persistent: /data/data/com.test.megatest/files or
(Any File Manager App) /Android/data/com.test.megatest/files
# Cache: /data/data/com.test.megatest/cache or
(Any File Manager App) /Android/data/com.test.megatest/files
Reference:
1) java.io.FileOutputStream -> FileOutputStream (File file) public constructor
"Creates a file output stream to write to the file represented by the specified File object"
So I'm working on an android app and currently having an issue with some code. It's quite simple actually... I fill an arraylist, also check if it gets filled (it does) and then request that arraylist later on. But somehow when I request the arraylist later on it's empty and I'm not making a new instance or anything... Or I'm just plain missing it.
So here's the code where it's going wrong...
package net.serellyn.c2m.cal2movement;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity implements TaskListener{
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private TaskListener listener;
private Exercises exercises;
//...
private ArrayList<String> exerciseArrayList;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setLayout();
sharedPreferences = getSharedPreferences("PreferenceValues", MODE_PRIVATE);
editor = sharedPreferences.edit();
listener = this;
exercises = new Exercises();
new sc_getExercises(listener).execute("http://www.serellyn.net/c2e/app_backend/exercises.php");
}
#Override
public void taskComplete(ArrayList e) {
exercises.setExercises(e);
for(Exercise a : exercises.getExercises()) {
Log.i("DebugInfo", a.getExercise());
}
setLayout();
}
private void setLayout() {
Typeface tf_dinBlack = Typeface.createFromAsset(getAssets(), "DIN_Black.ttf");
Typeface tf_dinMedium = Typeface.createFromAsset(getAssets(), "DIN_Medium.ttf");
Typeface tf_dinLight = Typeface.createFromAsset(getAssets(), "DIN_Light.ttf");
tv_appName = (TextView)findViewById(R.id.tv_appName);
tv_appTagline = (TextView)findViewById(R.id.tv_appTagline);
tv_hourNumber = (TextView)findViewById(R.id.tv_hoursNumber);
tv_hourText = (TextView)findViewById(R.id.tv_hoursText);
tv_minutesNumber = (TextView)findViewById(R.id.tv_minutesNumber);
tv_minutesText = (TextView)findViewById(R.id.tv_minutesText);
tv_yourActivity = (TextView)findViewById(R.id.tv_yourActivity);
s_activities = (Spinner)findViewById(R.id.s_activities);
tv_appName.setTypeface(tf_dinBlack);
tv_appTagline.setTypeface(tf_dinMedium);
tv_hourNumber.setTypeface(tf_dinLight);
tv_hourText.setTypeface(tf_dinLight);
tv_minutesNumber.setTypeface(tf_dinLight);
tv_minutesText.setTypeface(tf_dinLight);
tv_yourActivity.setTypeface(tf_dinLight);
setActivityValues();
}
private void setActivityValues() {
for(Exercise a : exercises.getExercises()) {
Log.i("DebugInfo", a.getExercise());
}
}
}
sc_getExercises is an AsyncTask which works as expected, and fills the 'exercises' array in 'TaskComplete' function. I loop the 'exercises'array to see if it's filled, and it is filled as it should be.
However, when I do the same in the 'setActivityValues' later on, I get a nullpointerexception.
So that's kinda... weird in my eyes. What am I doing wrong?
Here's the exercises class.
package net.serellyn.c2m.cal2movement;
import java.util.ArrayList;
public class Exercises {
private ArrayList<Exercise> exercises;
public Exercises(){
exercises = new ArrayList<Exercise>();
}
public ArrayList<Exercise> getExercises() {
return exercises;
}
public void setExercises(ArrayList<Exercise> exercises) {
this.exercises = exercises;
}
}
I hope someone can spot the problem. Thanks in advance.
This is your method:
private void setActivityValues() {
for(Exercise a : exercises.getExercises()) {
Log.i("DebugInfo", a.getExercise());
}
}
Either exercises is null (it is initialized in onCreate), or exercises in your Exercises class instance is null (gets a value at taskComplete, which invokes setExercises), or one of the exercises in the loop is null, or the getExercise has a NullPointerException bug.
It says nullPointerException, check your json parser it fufills your list properly or not.
I must write a program with android which can find other ssid's and show them. I desinged it with 2 xml pages. I create an imagebutton in page2 and want to make a relation between imagebutton and searching method. It means i want to click on imagebutton and seaching method begin it's work and search ssid's and show them...
My problem is, I download my search method and because of that i can not recognize which method i must call on my setonclick method that i write for an imagebutton in second page? I try to create another class seperately for search method and call it from the second class of page2.
but i dont know how can i make a relation between these 2 calss(i mean the second and third class). Or i must write the method of searching and on click of my imagebutton in one class?
Thanks for your suggestion.this is the code that i was copy:
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class wifiScan extends Activity {
private class WifiReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = wifi.getScanResults();
Date tempDate=new Date();
String info=testNumber+" "+(tempDate.getTime()-testDate.
getTime()) +" "+results.size();
Log.i("wifiScan", info);
wifiText.setText(info);
testNumber++;
testDate=new Date();
wifi.startScan();
}
}
private TextView wifiText;
private WifiManager wifi;
private WifiReceiver receiver;
private Date testDate;
private static int testNumber=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testNumber=0;
wifiText = (TextView) findViewById(R.id.wifiText);
receiver=new WifiReceiver();
registerReceiver(receiver, new IntentFilte
(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi =(WifiManager)getSystemService(Context.WIFI_SERVICE);
if(!wifi.isWifiEnabled()){
wifi.setWifiEnabled(true);
}
startScan();
}
#Override
public void onStop(){
super.onStop();
finish();
}
public void startScan(){
testDate=new Date();
wifi.startScan();
}
}
you_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(this, wifiScan.class);
getApplicationContext().startActivity(i);
}
});
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.