Tuesday, November 25, 2014

Android Rookie Diary 11/25/2014

Just started a project that allows android phone talk to a STM32f103 (ARM 32bit Cortex-M3). It's been quite a while since I touched Android whose version was Gingerbread (2.3.3). As an android rookie right now, I'd like to keep a "diary" that could remind me of any mistakes that I made while I'm working on this project.

null exception.
It's easy to make such a stupid mistake if you've been off Java/Android for a while.
First, it's null exception in regards of View.
1:  @Override  
2:  protected void onCreate(Bundle savedInstanceState) {  
3:      super.onCreate(savedInstanceState); 
4:      mTextView = (TextView) findViewById(R.id.textview);  
5:      mTextView.setText("JunEnd");
6:      setContentView(R.layout.activity_register);
7:  }  
setContentView() sets the activity content from a layout resource, so should be called before findViewById(). Otherwise findViewById() will return null because of no layout resource and thus line 5 throws a null exception.

Second, it's null exception in regards of Spinner.
1:  public class RegisterActivity extends Activity implements OnItemSelectedListener {  
2:      private Spinner mSpinner;  
3:      private ArrayList<String> mArrayList_SpinnerList;  
4:      @Override  
5:      protected void onCreate(Bundle savedInstanceState) {  
6:          super.onCreate(savedInstanceState);  
7:          setContentView(R.layout.activity_register);  
8:          ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,  
9:                  android.R.layout.simple_spinner_item, mArrayList_SpinnerList);  
10:          adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
11:          mSpinner.setAdapter(adapter);  
12:          mSpinner.setOnItemSelectedListener(this);  
13:      }  
14:      @Override  
15:      public void onItemSelected(AdapterView<?> parent, View view, int pos,  
16:              long id) {  
17:          // TODO Auto-generated method stub  
19:      }  
20:      @Override  
21:      public void onNothingSelected(AdapterView<?> arg0) {  
22:          // TODO Auto-generated method stub  
23:      }  
24:  }  
I forgot to instantiate mArrayList_SpinnerList and passed it to constructor ArrayAdapter() and then thus gave Spinner this adapter holding an uninstantiated object. I believe this is causing a null exception and killed the app.