in programming for android, my use of setOnItemClickListener is now throwing an exception. I’ve never had any trouble with it before and I didn’t see any exceptions listed for it in the documentation. Can anybody tell me what the problem is?
package com.name.magicwindow;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MagicWindowActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView mainMenu;
try{
mainMenu = (ListView)findViewById(R.id.main_menu_list);
try{
mainMenu.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View view,int position,long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),Toast.LENGTH_SHORT).show();
}
});
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), "could not set listener",Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), "could not find listview",Toast.LENGTH_LONG).show();
}
setContentView(R.layout.main);
}
}
That one should be pretty simple:
You have to call
setContentView(R.layout.main)before you usefindViewById().So your activity knows what it’s content (view hierarchy) is.