findViewById causes NullPointerException for no apparent reason - java

I am new to Android development. My app is compiling perfectly fine (no errors, no warnings), but it crashes on launch. I have diagnosed the cause of the crash to be a NullPointerException, and I discovered that if I remove TextView output = (TextView) findViewById(R.id.outputbox); as well as all the lines depending on this declaration, the app launches fine. I did research (both on and off Stack Exchange, and about 5 pages of Google results) and none of the solutions I have found worked, which is why I am asking this question. I have ran setContentView(R.layout.activity_main); before TextView output = (TextView) findViewById(R.id.outputbox); and outputbox is declared in activity_main.xml. This is not a duplicate of the existing questions because the answers to the other ones did not solve my problem.

most probably your declaration and initialization of the variable output is in the class. This is not going to work. The method findViewById will work only after the setContentView method has been invoked. That is why you have to declare your variable in the class, but initialize it in the method onCreate immediately after the setContentView method:
public class MainActivity extends AppCompatActivity {
TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output = (TextView) findViewById(R.id.outputbox)
}
}
The method findViewById searches for your component in the xml. For this to work, you have to point out what xml file will this Activity be using. This is done in the setContentView(R.layout.activity_main); command. It is a common mistake, so no worries :)

Related

I have run error at on Create on Android studio

I get a massage says "app is keep stopping" when I run the project on my mobile.
the error at on Create(MainActivity.java:16)
at the line 16 set Content View method
help me
The method setContentView() sets the View that your MainActivity should display.
The View is usually declared in layout/activity_main.xml.
Some error seems to appear when trying to call this method in your application.
A common reason why android applications crash there is calling some methods in the overridden method onCreate(Bundle savedInstanceState) in a wrong order.
Check if your code follows this pattern:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView call
// other things
}
I cannot help you further now, please copy and paste the stacktrace (crash information) into your question. When your application just crashed on an emulator, you can see it in the Run-section (usually red text).

Getting NullPointerException first time when Activity loads but working fine second time

I am starting EditCardActivity from MainActivity.
The app crashes first time and Android system shows an alert to "Open App Again".
When I reopen the app, it works as expected.
I have seen many answers on this site and I have done following according to those answers but it didn't work.
I have called the setContentView() inside onCreate() method before calling findViewByID().
I have verified that the ID I am passing in findViewByID() is spelled correctly.
I also tried to make the EditText a class member too and initialize it in onCreate() method.
I also tried using onStart(), onPostCreate() methods too.
I feel that the View has not been loaded when I am trying to call it and thus findViewByID() returns null. Hence I tried using Thread.sleep(1000) to give it 1 second to load but still same issue.
Here's the part of code that is having problem.
// MainActivity.java
public void editCard(View v) {
Intent i = new Intent(this, EditCardActivity.class);
startActivity(i);
}
<!--activity_edit_card.xml-->
...
<EditText
android:id="#+id/add_card_category_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin"
android:ems="10"
android:hint="#string/add_card_category_et_hint"
android:inputType="text"
android:textSize="#dimen/font_size" />
...
// EditCardActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_card);
showContents();
}
private void showContents() {
EditText editCardCategoryET = findViewById(R.id.add_card_category_et);
editCardCategoryET.setText(currentCard.getCategory()); // This line is throwing NullPointerException
}
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Edit:
I got what was causing the error.
I was referring to the add_card_category_et instead of edit_card_category_et.
The former view belonged to the different layout file of another Activity of my application.
I am sorry I couldn't catch this small error.
Although small, it made me stuck for 3 days.
Anyway thanks for your answers and comments.
Because editCardCategoryET cant find any value. So it throws Exception. It can be solve by add extra character by adding " " . Then app will not crush. editCardCategoryET.setText(" "+currentCard.getCategory()); .
Also you can handle it in a try(), catch() method.

symbol not recognized buttonplay

I have been trying all day to get this little code to work I got farther because I skipped it but needed to come back to it my buttonPlay is not being recognized and my book is telling me I need to import a directive. How do I this
// this is the entry point to our game
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Here we set our UI layout as the view
setContentView(R.layout.activity_main);
// Get a reference to the button in our layout
final Button buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
I presume that you are talking about this line:
final Button buttonPlay = (Button) findViewById(R.id.buttonPlay);
The compiler is complaining about this part: R.id.buttonPlay. It is saying that that use of buttonPlay is an undefined symbol.
The R class is actually automatically generated from the XML file that contains your app's UI design. It includes names for various elements. The most likely explanation of the compilation error is that either "buttonPlay" has not been defined in the XML, or you deleted it, or you have not spelled the name the same (including capitalization) in the two places.

How to set setContentView in another method?

I have an activity_main.xml with
tools:context="com.example.android.newwine.MainActivity"
and
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="goToNext"/>
In my MainActivity.java file I have
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
and
public void gaNaarNext(View view){
setContentView(R.layout.activity_main2);
}
I have an activity_main2.xml file with
tools:context="com.example.android.newwine.MainActivity"
When I touch the button next now the activity_main2.xml will be used as ContentView, so that's correct, but when I do anything then (like touching a RadioButton or doing doesn't matter what) in my activity_main2.xml file what calls a method, it says: "New Wine is stopped." Whatever I do what calls a method, the app crashes. I tried much and if I'm going to paste everything I tried here this will be a long, long question:).
But has someone an answer? I really don't know what to do now, so I thought; let's ask something on Stackoverflow. Thanks already!
You might prefer to use another activity or fragments to change your UI as using the method setContentView() multiple times is not recomended because of all the drawing involved.
Since it seems like you don't want to switch activities fragments may be the easiest to use.
This stackoverflow question addresses that matter as well.
After you change your content view, the UI Elements on the screen have changed. All of the variables that you previously set up now point to the old screen - which no longer exists. Once you change your content view, you must set these variables to the correct elements on that layout file. Also, you may want to check out Fragments like Carlos Sifuentes said.
When I do anything then (like touching a RadioButton or doing doesn't matter what) in my activity_main2.xml file what calls a method, it says: "New Wine is stopped." Whatever I do what calls a method, the app crashes.
The problem is you have used activity_main2.xml but you did'nt get the reference of RadioButton of activity_main2.xml. You should get all the view reference after setting new layout using setContentView() and then use as per your needs.
Update your gaNaarNext() method as below:
public void gaNaarNext(View view){
setContentView(R.layout.activity_main2);
// For example: If your activity_main2 contains radio_button then do this
RadioButton radioButton = (RadioButton) findViewById(R.id.radio_button);
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// Do something
}
});
}
Hope this will help~

onCreate android os bundle is never used

I'm a noob in java android but I get this error when I hover onCreate method onCreate(android.os.Bundle) is never used. Should I worry about this error?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.addTab(actionbar.newTab().setText("Feed").setTabListener(this));
actionbar.addTab(actionbar.newTab().setText("Browse").setTabListener(this));
actionbar.addTab(actionbar.newTab().setText("Settings").setTabListener(this));
}
Thanks
thats not an error its a warning. the bundle is used for putting information in when the app changes state ie. orientation so you can continue where the user left off.
there is no harm in not using it however the activity will be shown just as it would if you were to launch it from the launcher.
Got it! I just changed extends FragmentActivity into extends Activity and imported android.app.Activity.

Categories

Resources