当用户按下手机上的后退按钮时,我成功地重新加载了某些设置。当发生这种情况时,我将它们的位置和第一个元素存储在列表中。现在,通过按下图像按钮生成列表。生成列表后,您可以按下任何元素,它将加载一个新类。
但是当我从列表中回忆起信息并按下它时,应用程序崩溃给了我一个 空指针异常。我知道这是什么,但不明白为什么。这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView( R.layout.new_sightings );
// Initialize location
user_lat_Value = (TextView)findViewById( R.id.lat_Value );
user_long_Value = (TextView)findViewById( R.id.long_Value );
// Have not received coordinates yet
gotCoord = false;
adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, listItems );
setListAdapter( adapter );
SharedPreferences settings = getSharedPreferences( PREFS_NAME,0 );
if( settings.contains( "ARRAY_LIST_VALUE_0" ) || settings.contains( "LAT" ) )
{
user_lat_Value.setText( settings.getString( "LAT", myNewLat ) );
user_long_Value.setText( settings.getString( "LONG", myNewLon ) );
listItems.add( settings.getString( "ARRAY_LIST_VALUE_0",tempStore ) );
adapter.notifyDataSetChanged();
}
reload = (Button)findViewById( R.id.reloadTen );
reload.setOnClickListener( this );
list = getListView();
list.setOnItemClickListener( new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id )
{
// 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 );
}
});
list.setTextFilterEnabled( true );
}
@Override
protected void onStop()
{
super.onStop();
gotCoord = false;
SharedPreferences settings = getSharedPreferences( PREFS_NAME,0 );
SharedPreferences.Editor editor = settings.edit();
// 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 );
/**
for( int i = 0; i < storeList.length; i++ )
{
storeList[i] = listItems.get( i ).toString();
editor.putString( "ARRAY_LIST_VALUE_"+i, listItems.get( i ).toString() );
}
*/
}
editor.commit();
}
如果我错了,请纠正我,但因为我将数据重新加载到列表适配器并按下它不应该模仿列表中项目的行为(如果它刚被加载?)
我很困惑。任何言语?
干杯
答案 0 :(得分:1)
根据您的评论,似乎 data 变量为null,因此data [position]会抛出异常。可能这是与适配器位置相关的数据,但不是在onCreate()中重新加载的内容。