Set an image on imageview using arraylist strings and strings - 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.

Related

Blank Screen showing up after Image Selected from Gallery

I am trying to get an image into the ImageView but whenever I click a picture on the Gallery the app shows a blank screen and closes down.
This ImageView is in a fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_auction_add, container, false);
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
dateTimeAction(v);
return v;
}
private void imageSelectAction(View v) {
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_image = v.findViewById(R.id.auction_add_imageView);
choosePicture();
}
private void choosePicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
if (data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
auction_add_image.setImageURI(selectedImageUri);
}
}
}
}
The Inital Declaration
public class auction_add extends Fragment {
private static final int SELECT_PICTURE = 10;
private static final int PERMISSION_CODE = 11;
ImageButton auction_add_imageViewButton;
//References to all Auction Add Page EditText
EditText auction_add_itemNameTxt;
EditText auction_add_descriptionTxt;
EditText auction_add_initialPriceTxt;
EditText auction_add_startTimeTxt;
EditText auction_add_endTimeTxt;
//Reference to ImageView
private ImageView auction_add_image;
final Calendar myCalendar = Calendar.getInstance();
Would Appreciate the help thanks!
Edit:
Followed is the error on the Run tab of Android Studio
W/System: A resource failed to call close.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.projectcrest, PID: 5618
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=242868079, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:31 flg=0x1 }} to activity {com.example.projectcrest/com.example.projectcrest.pages.LandingPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at com.example.projectcrest.fragments.auction_add.onActivityResult(auction_add.java:155)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:377)
at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:336)
at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:624)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
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:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 5618 SIG: 9
By looking into the exception it seems that the App is crashing in #onActivityResult function at line auction_add_image.setImageURI(selectedImageUri); due to NPE (Null Pointer Exception). This expection/crash is caused since the auction_add_image object has null value instead of an ImageView.
After taking an close look into your code, I think the issue has occured due to following code:
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
Note that in #onClick function you are passing view v on which you are going to perform the #findViewById operation. Here the passed view v refers to the auction_add_imageViewButton instead of the v you have captured above.
I would suggest to modify the code as below (just rename the v variable in #onClick function):
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
imageSelectAction(v);
}
});
This way the variable name collision could be avoided and the error would be resolved.
Also, in case this does not solve your problem, then please check whether the #findViewById is returning an ImageView instead of null. In case the Id provided to #findViewById is not present on the screen or in the child views of view (on which the #findViewById) is being performed then the #findViewById will return null value.
Also, check whether you have assigned null value to auction_add_image in anywhere your code.

Getting NullPointerException in a BankList Activity when sending data from MainActivity using intent in android [duplicate]

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"));

Android - Null Array. Runs in Android Studio emulator but not on real device when unplugged

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?.

Null Pointer Exception when calling getResources()

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);

NullPointerException when user choose the background from gallery [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Good Day, I would like to allow user to change background in my app. Try to make it, but face with that problem:
12-09 06:22:15.874 20413-20413/com.vadimsleonovs.horoscope E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vadimsleonovs.horoscope, PID: 20413
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/20 flg=0x1 }} to activity {com.vadimsleonovs.horoscope/com.vadimsleonovs.horoscope.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setBackground(android.graphics.drawable.Drawable)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setBackground(android.graphics.drawable.Drawable)' on a null object reference
at com.vadimsleonovs.horoscope.activities.SettingsActivity.onActivityResult(SettingsActivity.java:76)
at android.app.Activity.dispatchActivityResult(Activity.java:6135)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582) 
at android.app.ActivityThread.access$1300(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
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:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
The code is that:
public class SettingsActivity extends AppCompatActivity {
Button mBcgBtn;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mBcgBtn = (Button) findViewById(R.id.bcg_clr_btn);
mBcgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}catch(NullPointerException e){
e.printStackTrace();
}
LinearLayout mHomeLayout = (LinearLayout) findViewById(R.id.activity_home);
LinearLayout mDetailsPageLayout = (LinearLayout) findViewById(R.id.activity_details_page);
Drawable d = new BitmapDrawable(getResources(), BitmapFactory.decodeFile(picturePath));
mHomeLayout.setBackground(d);
}
}
}
Also, I added write external storage permission, and this code works perfectly in "blank project", but in my project not working at all.
It says mHomeLayout is null. ie, There is no LinearLayout with id activity_home in activity_settings layout.
So what you need to do is save the selected drawable path in storage preferences from Settings Activity. And load it when you open the other activity which has the Linearlayout with id activity_home. And then set it as it's background.
I hope that's your problem.

Categories

Resources