I have an activity that lets the user load some data when they press a button. That data is passed to a list and each list item has different data stored in it. When they click on the list item it launches an intent which passes them to a new class.
But when I store the first value returned from pressing this button, i.e. using the onStop() and using SharedPreferences, and click on it I get an error. I think it may be something to do with the intent – the list item just isn’t attaching to it. Here is part of the code:
adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, listItems );
setListAdapter( adapter );
list = getListView();
list.setOnItemClickListener( this );
if( settings.contains( "ARRAY_LIST_VALUE_0" ) )
{
listItems.add( 0, settings.getString( "ARRAY_LIST_VALUE_0",tempStore ) );
adapter.notifyDataSetChanged();
}
reload = (Button)findViewById( R.id.reloadTen );
reload.setOnClickListener( this );
// Original onItemClicked was in here
list.setTextFilterEnabled( true );
}
@Override
public void onItemClick(AdapterView<?> arg0, View listItem, int position, long arg3)
{
// Start an activity based on what list view item is pressed
Intent intent = new Intent( newSightings.this, newCompass.class );
// Pass the data we retrieved to the next activity
intent.putExtra( "info",data[position] );
startActivity( intent );
}
@Override
protected void onStop()
{
super.onStop();
SharedPreferences settings = getSharedPreferences( PREFS_NAME,0 );
SharedPreferences.Editor editor = settings.edit();
if( usrPrssdBtn )
{
// Store the latitude and longitude values and then reload them if known
editor.putString( "LAT",myNewLat );
editor.putString( "LONG",myNewLon );
// Place first element of array list in storage
if( adapter.getCount() > 0 )
{
Toast.makeText( getApplicationContext(), "Leaving Activity, Adapter Size: "+ adapter.getCount()+"\nStoring: "+listItems.get( 0 ).toString(), Toast.LENGTH_SHORT ).show();
tempStore = listItems.get( 0 ).toString();
editor.putString( "ARRAY_LIST_VALUE_0",tempStore );
editor.putString( "DATA",data[arryTrckr] );
}
}
editor.commit();
}
So – when I run the activity and then press back, then go back to the activity the stored list item is there. Problem is when I click it it crashes the app. What’s the problem? I get a NullPointerException at this line:
intent.putExtra( "info",data[position] );
adapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, listItems );
in the above line you are using listitems array to sidplay the data.
where as onItemclick event you are using
data[position] to fetch the data according to me when you are displaying data from listitems array the you must use listitems[position] to fetch the data