I'm making an Android application that (is supposed to):
1. Gets the value of a Spinner on button click.
2. If the value is 2, make a random number between 1 and 2
3. If it is 1, set TextView text into "A"
4. If it is 2, set TextView text into "B"
I get the error "NullPointerException"
My code is here:
package org.infinitech.iguess.app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends ActionBarActivity{
public Button button;
public TextView text=(TextView)findViewById(R.id.answer);
public Spinner a=(Spinner)findViewById(R.id.choices);
public String b;
public int d;
public Random r=new Random();
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
text=(TextView)findViewById(R.id.textBox);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
b=(String)a.getSelectedItem();
if(b=="2"){
d=2+r.nextInt(1);
if(d==1){
text.setText("A");
}
else if(d==2){
text.setText("B");
}
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
int id=item.getItemId();
if(id==R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
}