Why does this code give me a null pointer exception? [duplicate] - java

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)
When do activity's instance variables get initialized?
(2 answers)
Closed 4 years ago.
public class FindBeerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
}
Spinner color = (Spinner) findViewById(R.id.color);
TextView brands = (TextView) findViewById(R.id.brands);
public void onClickFindBeer(View view) {
//Get the selected item in the spinner
String beerType = String.valueOf(color.getSelectedItem());
//Display the selected item
brands.setText(beerType);
}
}
I know if I move the findviewbyid's into the onclick method, the code will run fine but i would like to understand why it wont work this way even though the setContentView has already been called.

Perhaps you misplaced the closing curly-brace. This one should fix your NPE.
public class FindBeerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
Spinner color = (Spinner) findViewById(R.id.color);
TextView brands = (TextView) findViewById(R.id.brands);
}
public void onClickFindBeer(View view) {
//Get the selected item in the spinner
String beerType = String.valueOf(color.getSelectedItem());
//Display the selected item
brands.setText(beerType);
}
}

Related

RecyclerView Problems With The Adapter [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Alright I'm trying to display data called by an api on a recyclerview and I get the error. It has nothing to do with butterknife I think. Please help.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)'
on a null object reference
at com.example.myflickrproject.PhotoDisplayView.onCreate(PhotoDisplayView.java:40)
public class PhotoDisplayView extends AppCompatActivity { //implements AdapterView.OnItemClickListener
#BindView(R.id.recView)
RecyclerView rViewDis;
#BindView(R.id.addToDatabse)
Button download;
#BindView(R.id.backButton)
Button goBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_display_view);
System.out.println("My photolist is " + DataCollection.photoList);
rViewDis.setLayoutManager(new GridLayoutManager(this, 3));
PhotoAdapter myAdapter = new PhotoAdapter(this, DataCollection.photoList);
rViewDis.setAdapter(myAdapter);
ButterKnife.bind(this);
}
#OnClick({R.id.addToDatabse, R.id.backButton})
public void onClick(View v) {
int btns = v.getId();
switch (btns) {
case R.id.addToDatabse:
addToDatabse();
break;
case R.id.backButton:
backToMenu();
break;
}
}
public void addToDatabse() {
}
public void backToMenu() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
Bind your views after setContentView(R.layout.activity_photo_display_view);
So, your code should be like this
setContentView(R.layout.activity_photo_display_view);
ButterKnife.bind(this);

how can i assign functions to buttons in android studio with out having the vm shut down [duplicate]

This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 2 years ago.
i am new to java and android studio ; i have set myself the goal of making a simple counter app in which one taps a button and a counter increases. Android studio shows no errors until i run t on my phone where it crashes as soon as i touch a button
i have tried to define the buttons as TextView tv; with no luck
public class MainActivity extends AppCompatActivity {
private int score;//this lets me use it else where within the public class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startCounter(View v) {
score = 0;
TextView tv = findViewById(R.id.textView); //the text view defines it as tv
tv.setText(score); //set the text of the label
}
public void buttonOnClick(View v) {
score++; //adds 1 to score
TextView tv = findViewById(R.id.textView); //the text view defines it as tv
tv.setText(score); //set the text of the label
}
}
i expect that the result is that the text view is updated to show the variable score but instead i get the error Invalid ID 0x00000000. and then D/AndroidRuntime: Shutting down VM
I just replace your code so please copy and follow
int score=0;
public class MainActivity extends AppCompatActivity {
private int score;//this lets me use it else where within the public class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewByID(R.id.tvID);
Button myButton = (Button)findViewByID(R.id.buttonID);
myButton.setOnClickListener(new View.OnClickListener{
score++;
tv.setText(score.toString());
});
}

How to save checkbox states using simple_list_item_multiple_choice?

I'm doing a grocery list app and i want all the list to be sort by department (Meat, fruit, bakery etc.). I try to do the first list which is the fruit list everything is working i can add item the checkbox is there i can use it no problem. the problem is that when i check items and i press the previous button on the phone and then i click back on the button to access the fruit list the items are not checked anymore.
I use the android.R.layout.simple_list_item_multiple_choice for the checkbox.
I try to use onSaveinstance but i cant get it to work ...i would like to save it without using SQl now my array are save in a file for my list.
I eard about shared preference but i'm not sure its what i'm looking for and i would need some help to understand how to use it.
This is the class that call the activity where the fruit list is displayed with the checkbox:
public class SelectDoActivity extends AppCompatActivity {
/*Set the instance variable*/
private ImageButton btn_FruitList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_select_do);
btn_FruitList = (ImageButton) findViewById (R.id.btn_FruitList);
/*Create the method that call the activity*/
btn_FruitList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFruitList_Activity();
}
});
}
public void openFruitList_Activity() {
Intent intent = new Intent (this, FruitList_Activity.class);
startActivity(intent);
}
}
This is the class that display the fruit list with the check mark.
public class FruitList_Activity extends AppCompatActivity {
private ListView fruitsList;
private ArrayAdapter<String> adapterFruit;
private Button btn_Delete;
private Button btn_SelectAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_fruit_list_);
fruitsList = findViewById(R.id.list_Fruits);
fruitsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btn_Delete = findViewById (R.id.btn_delete);
CreateActivity.itemsFruit = FileHelper.readData(this);
adapterFruit = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, CreateActivity.itemsFruit);
fruitsList.setAdapter(adapterFruit);
/*button to Remove items*/
btn_Delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SparseBooleanArray checkedItemPositions = fruitsList.getCheckedItemPositions();
int itemCount = fruitsList.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
fruitsList.setItemChecked(i,true);
adapterFruit.remove(CreateActivity.itemsFruit.get(i));
FileHelper.writeData(CreateActivity.itemsFruit, FruitList_Activity.this );
}
}
adapterFruit.notifyDataSetChanged();
}
});
}
}
I've been stuck with this since 2 weeks i would we really like some precious help i'm ne to java and android so thanks for taking the time to explain how to fix this.

Can't acces TextView defined in onCreate [duplicate]

This question already has answers here:
How do I declare a TextView variable so that I can use it anywhere?
(2 answers)
Closed 6 years ago.
I am still a Java beginner and I have the problem that I have a onClick function and of course the onCreate in which i define the TextView to a value. But when I want to edit the TextView from the onClick i can't do that. Now I would like to know how I can make the TextView value "global".
final TextView result = (TextView) findViewById(R.id.result);
You have to instantiate the TextView after the setcontentView() method :
public class MainActivity extends Activity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textview);
}
}
You can define your TextView above method onCreate.
TextView result;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setContentView(R.layout.yourLayout);
TextView result = (TextView) findViewById(R.id.result);
}
In your class you create an attribute:
private Textview tv;
then in onCreate method you initialise this variable like this :
tv = (TextView) findViewById(R.id.result);
Then you can use it wherever you want in your class by calling "tv".

How to edit global variables with EditText to pass the value to an other activity?

I have a problem here with variables. I created a simple Android game. The levels depend on the input the user does (birthay and birthmonth are the variables).
I made a simpler app which refers to the global variable problem only.
Here are the files:
Global.java
import android.app.Application;
public class Globals extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
MainActivity.java:
public class MainActivity extends Activity {
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
String m = editText.getText().toString();
((Globals) this.getApplication()).setSomeVariable(m);
}
public void saveName(View v) {
Intent first = new Intent(this, FirstActivity.class);
startActivity(first);
}
}
FirstActivity.java:
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
TextView textf = (TextView) findViewById(R.id.textfirst);
String s = ((Globals) this.getApplication()).getSomeVariable();
textf.setText(s);
}
}
The variable is a String so I made the EditText to a String with getText().toString() but it doesn't work.
When I give the value a concrete String value it works properly also
((Globals) this.getApplication()).setSomeVariable(m); to
((Globals) this.getApplication()).setSomeVariable("message");
Any idea how to solve it?
Thank you ^^
You're assigning the EditTexts content to the variable in your onCreate() method where the EditText is probably empty. Do
((Globals) this.getApplication()).setSomeVariable(m);
in your saveName(View v) method and you should be fine.
PS: "it doesn't work" is not a great description of your problem, try to be a bit more precise (what did you expect to happen, what did actually happen).
PPS: Passing your String to the next activity via intent.putExtra() would be a nicer way to pass the data.

Categories