Reputation: 67
Execution of the following code crashed. There are no error messages.
It should open Web.java
upon a button press and creates a Key-Value.
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends Activity {
private Button btnGo;
final Spinner page = (Spinner)findViewById(R.id.txtPage);
String pageChoice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPref =PreferenceManager.getDefaultSharedPreferences(this);
btnGo = (Button)findViewById(R.id.btnGo);
btnGo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pageChoice = page.getSelectedItem().toString();
//Hopefully will allow for "global" url setting.
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key1", pageChoice);
editor.commit();
startActivity(new Intent(MainActivity.this, Web.class));
}
});
}
}
Upvotes: 0
Views: 69
Reputation: 10299
Put final Spinner page = (Spinner)findViewById(R.id.txtPage);
after setContentView(R.layout.activity_main);
statment
Look for a child view with the given id. If this view has the given id, return this view. So While class load it looks for Spinner with txtPage id but it isn’t there. so you are getting null value. Which you are trying to access in onClick Method result is NPE.
Upvotes: 1
Reputation: 10110
This not suppose to be in class variables:
final Spinner page = (Spinner)findViewById(R.id.txtPage);
This need to be inside onCreate()
method. After setContentView()
, as a method variable.
findViewById()
use the context to lookup the View, and this need to have a context (and the layout resource need to be inflated). You only get the context in onCreate
execution, not when the class is loaded.
Upvotes: 1