I'm making a quiz program for android, and to keep things compatible for different languages, I've put all my quiz questions and labels in my strings.xml file. Basically the functionality I'm looking for is to have the first question display in a TextView, then when the user submits their answer, it updates to the next question.
Here is my code along with the error message I'm getting.
--------- beginning of crash
11-16 10:37:21.723 26952-26952/com.example.neil.bsgquiz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.neil.bsgquiz, PID: 26952
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.neil.bsgquiz/com.example.neil.bsgquiz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2337)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:551)
at com.example.neil.bsgquiz.MainActivity.<init>(MainActivity.java:28)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
package com.example.neil.bsgquiz;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int correctAnswers = 0;
int questionCounter = 0;
//TODO Bug seems to be in this section, about getting resources.
//get question header array from resources
Resources res = getResources();
String[] questionHeaders = res.getStringArray(R.array.question_header_array);
//get answer key array from resources
String[] answerKey = res.getStringArray(R.array.answer_key_array);
//get questions from resources
String[] questions = res.getStringArray(R.array.questions_array);
public void submitAnswer() {
//create Edit Text object, and extract user input answer from it
EditText userAnswerEditText = (EditText) findViewById(R.id.answer_text);
String userAnswer = userAnswerEditText.getText().toString();
//compare against answer key and tell user if right or wrong
if (userAnswer.compareToIgnoreCase(answerKey[questionCounter]) == 0) {
Toast.makeText(this, "That's Correct!", Toast.LENGTH_SHORT).show();
correctAnswers++;
} else {
Toast.makeText(this, "Sorry, That's Incorrect", Toast.LENGTH_SHORT).show();
}
nextQuestion();
}
/**
* #param questionNumber: what question are we getting a hint for
* #return String containing a hint to give to the user
*/
private String getHint(int questionNumber) {
return "0";
}
private void nextQuestion() {
//step forward question header
TextView headerText = (TextView) findViewById(R.id.question_header);
headerText.setText(questionHeaders[questionCounter]);
//step forward question text
TextView questionText = (TextView) findViewById(R.id.question_text_view);
questionText.setText(questions[questionCounter]);
//reset hint for EditText
EditText userAnswerEditText = (EditText) findViewById(R.id.answer_text);
userAnswerEditText.setHint("Answer");
//update correct answer counter
TextView correctAnswers = (TextView) findViewById(R.id.correct_answer_counter);
correctAnswers.setText(correctAnswers + " / 8");
questionCounter++;
}
}
You're accessing resources too early, in MainActivity.<init> e.g. field initialization. You can only use your activity as a Context with Resources in onCreate() or later in the activity lifecycle.
Move the getResources() and getStringArray() calls to onCreate().
For those that are interested, I got my code up and running with the following.
public class MainActivity extends AppCompatActivity {
String[] questionHeaders, answerKey, questions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
questionHeaders = res.getStringArray(R.array.question_header_array);
answerKey = res.getStringArray(R.array.answer_key_array);
questions = res.getStringArray(R.array.questions_array);
}
int correctAnswers = 0;
int questionCounter = 0;
Declared the three String[] arrays in the main activity before onCreate().
Initialize a 'Resources' object named res inside onCreate().
Call getStringArray on res to load each String[] array
My problem turned out to be that I was instantiating my widget (a CardView) with a null Context. Initializing the context object resolved the issue. For example, here is what my working code now looks like, but m_context was null when I was getting the same NullPointerException.
CardView m_cardView = new CardView(m_context);
Related
so I want to create a Rock Paper Scissors app that should work like this:
In the first screen you enter the names of the 2 players.
In the second screen there are the names of the players and the score of each player near it.The progress is that you need to click a button,and after you click it,in each player's side,random image(rock paper or scissors) will appear and the winner will get a point,or nobody will if its a draw.
NOTE:This might not be an error in the code based on what i've seen when I tried to search for the message i'm getting while debugging so you may want to look at it first.
I would appreciate some comments on the code though.
I checked if the names that i'm passing from the first activity to the second one before I had started to work on the button and the app worked fine.
But after I wrote the code for the OnClickListener, the app just crashes instantly after the first activity when I run it. It is my first time working with images like that so i'm not sure that if used it properly. I have created some functions so the code will be more readable without knowing exactly what i'm doing though because i'm pretty new to android.
first activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn;
startBtn = findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText p2Name=findViewById(R.id.p2EditText);
EditText p1Name=findViewById(R.id.p1EditText);
String name1=p2Name.getText().toString();
String name2=p1Name.getText().toString();
Intent intent1 = new Intent(MainActivity.this, Game.class);
intent1.putExtra("name1",name1);
intent1.putExtra("name2",name2);
MainActivity.this.startActivity(intent1);
}
});
}
second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String p1Name;
String p2Name;
if (getIntent().hasExtra("name1")) {
p1Name = getIntent().getStringExtra("name1");
TextView p1NView = findViewById(R.id.p1);
p1NView.setText(p1Name);
}
if (getIntent().hasExtra("name2")) {
p2Name = getIntent().getStringExtra("name2");
TextView p2NView = findViewById(R.id.p2);
p2NView.setText(p2Name);
}
Button NRound=findViewById(R.id.newRoundBtn);
NRound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView score1=findViewById(R.id.score1View);
TextView score2=findViewById(R.id.score2View);
int p1Score = Integer.parseInt(score1.getText().toString());
int p2Score = Integer.parseInt(score2.getText().toString());
String[] RPS = new String[]{"rock", "paper", "scissors"};
Random r = new Random();
String p1Hand;
String p2Hand;
p1Hand = RPS[r.nextInt(3)];
p2Hand = RPS[r.nextInt(3)];
showImages(p1Hand,p2Hand);
String result=findWinner(p1Hand,p2Hand);
switch (result){
case "player1":
p1Score++;
score1.setText(String.valueOf(p1Score));
case "player2":
p2Score++;
score2.setText(String.valueOf(p2Score));
if(score1.getText().equals('3') || score2.getText().equals('3')){
Intent end=new Intent(Game.this,EndScreen.class);
Game.this.startActivity(end);
}
}
}
});
update();
}
public static String findWinner(String hand1,String hand2){
if(hand1.equals(hand2)){
return "draw";
}
String both=hand1.concat(hand2);
if(both.equals("rockscissor") || both.equals("paperrock")||both.equals("scissorspaper")){
return "player1";
}else{
return "player2";
}
}
public void showImages(String hand1,String hand2){
ImageView rock1=findViewById(R.id.rock1);
ImageView paper1=findViewById(R.id.paper1);
ImageView scissors1=findViewById(R.id.scissors1);
ImageView rock2=findViewById(R.id.rock2);
ImageView paper2=findViewById(R.id.paper2);
ImageView scissors2=findViewById(R.id.scissors2);
switch (hand1){
case "rock":
rock1.setVisibility(View.VISIBLE);
case "paper":
paper1.setVisibility(View.VISIBLE);
case "scissors":
scissors1.setVisibility(View.VISIBLE);
}
switch (hand2){
case "rock":
rock2.setVisibility(View.VISIBLE);
case "paper":
paper2.setVisibility(View.VISIBLE);
case "scissors":
scissors2.setVisibility(View.VISIBLE);
}
}
public void update(){
ImageView[] images=new ImageView[6];
for (ImageView image:images)
{
if(image.getVisibility()==View.VISIBLE){
image.setVisibility(View.GONE);
}
}
}
Logs
Edit:now after I have posted and seen the logs I understood what was the problem. I forgot to initialize the imageView array in a function and I was just looping over null array,trying to get its visibility.And Now it does not crash.
I didn't know about this so thanks anyways for telling me to post it.(thought errors should show up in the console or something).
Now I am dealing with another problem,I will try to solve it on my own though.
Process: com.example.rockpaperscissors, PID: 11607
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rockpaperscissors/com.example.rockpaperscissors.Game}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.ImageView.getVisibility()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.ImageView.getVisibility()' on a null object reference
at com.example.rockpaperscissors.Game.update(Game.java:71)
at com.example.rockpaperscissors.Game.onCreate(Game.java:65)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
I tried to debug the app and at the last line of the first activity,the message that shows up is: source code does not match the byte code.
First try to clean the project and rebuild it.
In order for us to help you with the crash, we need to see the logs. Please add that as well.
About your code:
MainActivity.class
Try validating user input before passing it to the next activity.
Game.class (assuming this is also an activity so try renaming it to GameActivity.class)
When you are retrieving data from the intent, it's best practice to create a constant and make it public that you can use in the main activity as well (if you make a typo, it's hard to find the problem)
Something like: public static final String NAME_ONE_KEY = "name1";
I don't see the need of using a string array, identify those actions by integer and comment it so you and others who read your code can understand it.
It seems like you have a lot of child elements in your game layout file
Add the images into the drawable folder, create one image view for each player and update the image source.
Finally, save the state so you don't loose the data on device rotation.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to pass an arraylist between two activities, but my app crashes at the second activity. Can someone help me solve in this problem...
Here,
I have two parts of my MainActivity from where sending arraylist to another Activity which is BankList Activity
Part 1:
Intent intent = new Intent(MainActivity.this, BankList.class);
intent.putStringArrayListExtra("BANKLIST",bankListArrayList);
startActivity(intent);
Part 2:
Result<ArrayList<Bank>> banklist = (Result<ArrayList<Bank>>)data;
if(banklist.getCode().equals("00")){
Toast.makeText(this,"list Banks success",Toast.LENGTH_SHORT).show();
bankListArrayList = new ArrayList<>();
for(Bank bank :banklist.getData()){
bank.getIin();
bank.getLogo();
bank.getName();
b
ankListArrayList.add(bank.toString());
}
Log.d("BANK_ARRAYLIST","BANK_ARRAYLIST"+bankListArrayList);
Toast.makeText(this,"BANK_ARRAYLIST"+bankListArrayList,Toast.LENGTH_SHORT).show();
}
My Second Activity (BankList)
public class BankList extends AppCompatActivity {
ListView bankList;
ArrayList<String> bankdataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_list);
bankList = (ListView)findViewById(R.id.bankList);
Intent intent = getIntent();
intent.getStringArrayListExtra("BANKLIST");
bankdataList.add(intent.toString());
Toast.makeText(BankList.this,"bank list"+bankdataList,Toast.LENGTH_SHORT).show();
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item, bankdataList);
bankList.setAdapter(itemsAdapter);
}
}
And my Log is :-
11-09 12:58:01.548 1941-1941/com.example.rajdeeps.upi_integration E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rajdeeps.upi_integration, PID: 1941
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rajdeeps.upi_integration/com.example.rajdeeps.upi_integration.BankList}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.example.rajdeeps.upi_integration.BankList.onCreate(BankList.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
You forgot to initialize your bankdataList Arraylist just initialize it
ArrayList<String> bankdataList= new ArrayList();;
Sample code
public class BankList extends AppCompatActivity {
ListView bankList;
ArrayList<String> bankdataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_list);
bankdataList= new ArrayList();
bankList = (ListView)findViewById(R.id.bankList);
Intent intent = getIntent();
intent.getStringArrayListExtra("BANKLIST");
bankdataList.add(intent.toString());
Toast.makeText(BankList.this,"bank list"+bankdataList,Toast.LENGTH_SHORT).show();
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item, bankdataList);
bankList.setAdapter(itemsAdapter);
}
}
You have not initialize bankdataList before add items.
bankdataList = new ArrayList<String>();
bankdataList.add(intent.getStringArrayListExtra("BANKLIST"));
I've been testing my app in Android Studio emulator through my Samsung S7 phone (API 23 and 6.0.1) and it works fine. When I unplug it from my laptop and run the app it crashes.
My logcat says that I am trying to call a null array... but it isn't null? I don't understand why when I run the app through Android Studio to my phone everything works fine but when I run it alone it crashes. Thankful for any help!
Here is my logcat
FATAL EXCEPTION: main
Process: com.example.abc.def, PID: 28693
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abc.def/com.example.abc.def.MainActivity}: java.lang.NullPointerException: Attempt to read from null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to read from null array
at com.example.abc.def.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
And here is my code. The issue arises at the bottom when I call btn1.setText(itemArray[0]) because the array is "null"
public class MainActivity extends AppCompatActivity {
Button btn1, btn2;
String btn1Name, btn2Name;
String btnValue = "", itemValue = "", itemPosition = "";
String[] buttonArray = new String[]{"blank", "blank"};
String[] itemArray = new String[]{"blank", "blank"};
String[] positionArray = new String[]{"blank", "blank"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
btnValue = extras.getString("btnValue");
itemValue = extras.getString("itemValue");
itemPosition = extras.getString("itemPosition");
buttonArray = extras.getStringArray("buttonArray");
itemArray = extras.getStringArray("array");
positionArray = extras.getStringArray("positionArray");
if (btnValue != null && btnValue.equals("btn1")){
buttonArray[0] = btnValue;
itemArray[0] = itemValue;
positionArray[0] = itemPosition;
} else if (btnValue != null && btnValue.equals("btn2")) {
buttonArray[1] = btnValue;
itemArray[1] = itemValue;
positionArray[1] = itemPosition;
}
}
btn1.setText(itemArray[0]);
btn2.setText(itemArray[1]);
}
}
I'm guessing here, but is MainActivity the first activity in the project?
I think you wrote the code to handle returning to this activity with data from other activities. I just tried and getIntent().getExtras() returns null when the activity is first created on an emulator.
However, when I ran it on my device, getIntent generated this exception.
Note that onCreate is called once, so if you want to see the results of another activity, take a look at How to manage `startActivityForResult` on Android?.
Brief Description: This is a speech to text app, if the word they spoken is also a word in the database file then it will also have an image of that word spoken.
So I attempted to use imageResource to set the image but it failed, as it is using an ArrayList and a String for the first part of the imageResoruce function. which is assumed to be causing the error message as it crashes when i open the application.
Main.java
public class Main extends Activity {
private static final int VR_Request = 100;
private final String pathname = ".png"; //path name of an image file stored in the drawable folder
TextView speechInput;
TextView matchOrNot;
String[] wordBank; //
ArrayList<String> wordBANK;
ImageButton speechBtn;
ImageView image;
Resources res = getResources();
int resID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reverse_pictionary);
speechInput = (TextView) findViewById(R.id.english_word);
matchOrNot = (TextView) findViewById(R.id.matchOrNot);
wordBank = getResources().getStringArray(R.array.Words);
speechBtn = (ImageButton) findViewById(R.id.mic_pic_button);
wordBANK = new ArrayList<String>(Arrays.asList(wordBank));
image = (ImageView) findViewById(R.id.imageOfword);
}
public void onMic(View view) {
promptSpeechInput();
}
public void promptSpeechInput() {
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == VR_Request && resultCode == RESULT_OK) {
ArrayList<String> result = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(wordBANK.contains(result.get(0).toLowerCase())){
speechInput.setText(result.get(0).toUpperCase());
matchOrNot.setText("MATCH");
resID = res.getIdentifier(result.get(0).toLowerCase()+pathname, "drawable", getPackageName());
image.setImageResource(resID);
}else {
speechInput.setText(result.get(0));
matchOrNot.setText("NO MATCH");
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
RunTime Error Message:
08-10 21:07:37.678 2344-2344/com.example.speechtotext E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.speechtotext, PID: 2344
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.speechtotext/com.example.speechtotext.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at com.example.speechtotext.Main.<init>(Main.java:38)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Any Ideas? Thank you in advance!
Move the code :
Resources res = getResources();
into the onCreate() method.
You can not use getResources() before the activity created.
I am working on an Android project and as I have to test on local machine and on server, I thought of giving a base-url. I keep getting the error as mentioned below. As I checked on SO, this is the way to get URL, what am I doing wrong. Error below and code after that.
07-20 13:19:54.612 3795-3795/com.example.TestLunch E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.TestLunch, PID: 3795
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.TestLunch/com.example.TestLunch.Activity.RestaurantList}: android.content.res.Resources$NotFoundException: String resource ID #0x7f04000e
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f04000e
Code throwing error.
public class RestaurantList extends ListActivity {
// Below line throws the error.
String restaurantList = Resources.getSystem().getString(R.string.baseUrl)+"restaurant/listing";
}
Strings.xml :
<string name="baseUrl">http://192.168.178.60:8080/</string>
Any help would be nice. Thanks.
Update
This also failed :
String restaurantList = getResources().getString(R.string.baseUrl)+"restaurant/listing";
Update
This also failed
public class RestaurantList extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restos);
RestTemplate restTemplate = StaticRestTemplate.getRest();
String restaurantList = Resources.getSystem().getString(R.string.baseUrl)+"restaurant/listing";
}
I think there are 2 problems :
You should not access the resources in the constructor or in field initializers, it is too early. The right place is in the onCreate methods.
Resources.getSystem().getString() can only find system resources, not the one you define in your application. You should use getString from the Activity.
In your case :
public class RestaurantList extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restos);
RestTemplate restTemplate = StaticRestTemplate.getRest();
String restaurantList = getString(R.string.baseUrl) + "restaurant/listing";
}
Please try this:
String restaurantList = getApplication().getResources().getString(R.string.baseUrl) + "restaurant/listing";
The problem is that you try to access at string resource out of method onCreate. If you add your code in the onCreate() method the problem is solved.
like this works
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
String restaurantList = Resources.getSystem().getString(R.string.baseUrl)+"restaurant/listing";
}