Problem with id of ListView - android

I have a problem my ListActivity.
I have this xml:
<LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
and inside I have this:
<LinearLayout>
<ImageView android:id="#+id/flechas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView android:id="#+id/textoName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView android:id="#+id/textoPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button android:id="#+id/boton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BUY"
android:layout_marginRight="0dip"
android:onClick="buy"
/>
</LinearLayout>
I use a BaseAdapter to show it, and this is the main file:
public class Info extends ListActivity{
static ArrayList<Quotes> objeto= null;
static final ArrayList<HashMap<String, String>> lista= new ArrayList<HashMap<String,String>>();
private ListView mainListView;
private InfoModel [] model;
private CustomAdapterInfo listAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainListView= (ListView)findViewById(R.id.);
setContentView(R.layout.info);
objeto= new ArrayList<Quotes>();
Bundle extras=getIntent().getExtras();
objeto= extras.getParcelableArrayList("datos");
if ((objeto != null) && (objeto.size() != 0)){
model= new InfoModel[objeto.size()];
for (int i=0;i< objeto.size(); i++) {
model[i]= new InfoModel(0, objeto.get(i).getName(), objeto.get(i).getTrade());
}
}
ArrayList<InfoModel> datos= new ArrayList<InfoModel>();
datos.addAll(Arrays.asList(model));
listAdapter= new CustomAdapterInfo(this, datos);
mainListView.setAdapter(listAdapter);
}
But my mainListView is null. It doesn't find the R.id.
Any ideas?

android:id="#android:id/list"
I guess this should be your own ID. Like this:
android:id="#+id/main_list_view"
After that you can access it using something like:
mainListView= (ListView)findViewById(R.id.main_list_view);

If you follow this example.
If your activity extends the ListActivity, your XML should have a ListView with:
android:id="#android:id/list"
That's correct. But, the way you initialize the ListView is different:
ListView lv = getListView();
This would do the trick.

"#android:id/list"
means it is part of android package you can't call it using R.id.list( try this android.R.id.list) as R class generated for your package by ADT,instead you can get ListView object,
as ListView lView=getListView()
use setContentView method at top before you finding any View objects from XML(layouts),otherwise you will get NullPointerException.

Related

Android ListView does not work

I am trying to make a listview in android but i got some troubles.
This is the code:
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] items = {"red", "blue", "green"};
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, items));
}
}
And this the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Agregar Tarea"
android:id="#+id/btn" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list" />
</RelativeLayout>
The logcat says that there is a NullPointerException in line 21, this line:
ListView listView = (ListView) findViewById(R.id.list);
But I dont know why :(
I want to do the list view this way becouse if I use listactivity the header/footers is not fixed.
Add listview id in the xml layout.
Because of id null pointer exception is thrown.
android:id="#+id/list"
instead of
android:layout_below="#+id/list"
and also change above line like this
android:layout_below="#+id/btn"
Try change this
android:layout_below="#+id/list"
to this:
android:id="#+id/list"
Your listview id doesn't exists
android:id="#+id/list"
android:layout_below="#+id/btn"
You have not added property
android:id=#"+id/list"

View is null even after initialization

I have a listview in my code and I want to set adapter on it.
But the issue is, even after initializing the listview, it is still null resulting into nullPointerException. (I checked it by logging and debugging)
I'm not able to access any view from that xml.
What am I missing? Any help appreciated.
xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:scrollbars="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/lvToday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="#FFF"
android:dividerHeight="2dp" />
<ListView
android:id="#+id/lvTomorrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/lvToday"
android:divider="#FFF"
android:dividerHeight="2dp" />
</RelativeLayout>
</ScrollView>
Activity file
public class DashboardActivity extends Activity {
ListView lvToday, lvTomorrow;
TextView lblCall;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
init();
}
private void init() {
lvToday = (ListView) findViewById(R.id.lvToday);
lvTomorrow = (ListView) findViewById(R.id.lvTomorrow);
TodayAppAdapter adapter = new TodayAppAdapter(DashboardActivity.this,
DashboardActivity.this);
// This line is giving NULL
lvToday.setAdapter(adapter);
TomorrowAppAdapter adapter1 = new TomorrowAppAdapter(
DashboardActivity.this, DashboardActivity.this);
// This line is giving NULL
lvTomorrow.setAdapter(adapter1);
}
}
1) test eclipse menu: Project -> Clean...
2) if you have more than one version for your xml layout (example layout-large, layout-xlarge,...), check if all of them have your view.
You are missing a TextView in your layout
Put a String []
along with name of your Adapter in your
OnDraw()
Method

How to use R to select a ListView when using it with ListActivity

I have this code:
public class MyActivity extends ListActivity implements OnClickListener {
private ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setAdapter();
this.bindButtons();
}
private void setAdapter() {
setContentView(R.layout.siteactivity);
adapter=new ArrayAdapter<String>(this,
R.layout.siteitem,
listItems);
setListAdapter(adapter);
}
private void bindButtons() {
findViewById(R.id.buttonPrevious).setOnClickListener(this);
findViewById(R.id.buttonNext).setOnClickListener(this);
}
// ...
}
with this layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/siteActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/navigation">
<Button
android:text="<="
android:textSize="12dp"
android:id="#+id/buttonPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="=>"
android:textSize="12dp"
android:id="#+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/navigation"
android:layout_above="#+id/transport_selection"
/>
</RelativeLayout>
Note the android:id="#android:id/list" of the ListView. If I replace it by android:id="#+id/list", my activity force closes, because my "content must have a ListView whose id attribute is 'android.R.id.list'", but this is the expected behaviour, I think.
Now, I want to add a context menu to the items of the ListView. I tryed registerForContextMenu(findViewById(R.id.list));, but it doesn't work, because of the android:id.
Then, how can I add a context menu?
Regards,
As you are using ListActivity, you can use the following code to get list view in code:
ListView myListView=getListView ();
Use android.R.id.list instead of R.id.list.
(And by the way, the error message you wrote here turns out to have the answer)
Basically, anything defined in XML as #android:whatever is the same as android.R.whatever in the Java code. Anything that you defined in XML, which will look like #whatever, is the same as R.whatever in Java code.
Final edit: If you're using ListActivity, you are required to have a ListView with the id #android:id/list. Thus, unless you want to add another ListView to your activity, you shouldn't need #+id/list (or R.id.list).
You need to create an AlertDialog and call the dialog to show inside the listview's onItemLongClick() event. Click here for an example.

Activity of android

I am working with the xml file ,through which i am accessing a string through a variable passkey.later i am assigning it to strPassword. i am getting error for setListAdapter.Here is my code..
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="passkey">
<item>1234</item>
</string-array>
</resources>
and
public class AdminLogin extends Activity
{
public void onCreate(Bundle bdlActivity)
{
String[] strPassword = getResources().getStringArray(R.array.passkey);
setListAdapter(new ArrayAdapter<String>(this,R.layout.adminlogin,
R.id.Editpassword, strPassword))
//button events
}
You need to extend your class with ListActivty. You cant instantiate ListView in simple activity.
You can do it from a simple Activity too:
say you have a main layout, like:
mylayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button android:id="#+id/btn_ok" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="OK" android:layout_alignParentBottom="true" />
<ListView android:id="#+id/listview" android:layout_width="fill_parent" android:layout_height="fill_parent"
android:layout_above="#id/btn_ok" />
</RelativeLayout>
This would be the layout of your activity, with a list view inside of it (#id/listview)
Your Activity's onCreate method should look like this:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
final ListView listView = (ListView) findViewById(R.id.listview);
listView.setListAdapter(new ArrayAdapter<String>(this, R.layout.adminlogin,
R.id.Editpassword, strPassword))
}

onItemClickListener not firing on custom ArrayAdapter

I have an Activity that retrieves data from a web service. This data is presented in a ListView via an ArrayAdapter which inflates a RelativeLayout with three TextViews inside, nothing fancy and it work fine.
Now I want to implement a Details Activity that should be called when a user clicks an item in the ListView, sounds easy but I can't for the life of me get the onItemClickListener to work on my ArrayAdapter.
This is my main Activity:
public class Schema extends Activity {
private ArrayList<Lesson> lessons = new ArrayList<Lesson>();
private static final String TAG = "Schema";
ListView lstLessons;
Integer lessonId;
// called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// can we use the custom titlebar?
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// set the view
setContentView(R.layout.main);
// set the title
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
// listview called lstLessons
lstLessons = (ListView)findViewById(R.id.lstLessons);
// load the schema
new loadSchema().execute();
// set the click listeners
lstLessons.setOnItemClickListener(selectLesson);
}// onCreate
// declare an OnItemClickListener for the AdapterArray (this doesn't work)
private OnItemClickListener selectLesson = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int i, long l) {
Log.v(TAG, "onItemClick fired!");
}
};
private class loadSchema extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
// ui calling possible
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Schema.this,"", "Please wait...", true);
}
// no ui from this one
#Override
protected Void doInBackground(Void... arg0) {
// get some JSON, this works fine
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
// apply to list adapter
lstLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
}
My ArrayAdapter code:
// custom ArrayAdapter for Lessons
private class LessonListAdapter extends ArrayAdapter<Lesson> {
private ArrayList<Lesson> lessons;
public LessonListAdapter(Context context, int textViewResourceId, ArrayList<Lesson> items) {
super(context, textViewResourceId, items);
this.lessons = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Lesson o = lessons.get(position);
TextView tt = (TextView) v.findViewById(R.id.titletext);
TextView bt = (TextView) v.findViewById(R.id.timestarttext);
TextView rt = (TextView) v.findViewById(R.id.roomtext);
v.setClickable(true);
v.setFocusable(true);
tt.setText(o.title);
bt.setText(o.fmt_time_start);
rt.setText(o.room);
return v;
}
}// LessonListAdapter
The main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="#+id/main"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:screenOrientation="portrait"
>
<!-- student name -->
<TextView
android:id="#+id/schema_view_student"
android:text="Name" android:padding="4dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_vertical|center_horizontal"
style="#style/schema_view_student"
/>
<!-- date for schema -->
<TextView
android:id="#+id/schema_view_title"
android:layout_height="wrap_content"
android:layout_margin="0dip"
style="#style/schema_view_day"
android:gravity="center_vertical|center_horizontal"
android:layout_below="#+id/schema_view_student"
android:text="Date" android:padding="6dip"
android:layout_width="fill_parent"
/>
<!-- horizontal line -->
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#55000000"
android:layout_below="#+id/schema_view_title"
/>
<!-- list of lessons -->
<ListView
android:id="#+id/lstLessons"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_below="#+id/schema_view_title"
/>
</RelativeLayout>
The list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60px"
android:padding="12dip">
<TextView
android:id="#+id/timestarttext"
android:text="09:45"
style="#style/LessonTimeStartText"
android:layout_width="60dip"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent" android:gravity="center_vertical|right" android:paddingRight="6dip"/>
<TextView
android:id="#+id/titletext"
android:text="Test"
style="#style/LessonTitleText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toRightOf="#+id/timestarttext"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" android:gravity="center_vertical|center_horizontal"/>
<TextView
android:id="#+id/roomtext"
android:text="123"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
style="#style/LessonRoomText"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="center_vertical" />
</RelativeLayout>
Been messing with this for the last couple of hours and I can't seem to get my head around what the problem is. My problem looks very similar to this question, but I'm not extending ListActivity, so I still don't know where my onListClickItem() should go.
UPDATE: Now I've puzzled with this for several days and still can't find the issue.
Should I rewrite the activity, this time extending ListActivity instead of Activity? Because it provides the onItemClick method itself and is probably easier to overwrite.
Or, should I bind a listener directly in each getView() in my ArrayAdapter? I believe I have read this is bad practice (I should do as I tried and failed in my post).
Found the bug - it seems to be this issue. Adding android:focusable="false" to each of the list_item.xml elements solved the issue, and the onclick is now triggered with the original code.
I've encountered the same issue and tried your fix but couldn't get it to work. What worked for me was adding android:descendantFocusability="blocksDescendants" to the <RelativeLayout> from the item layout xml, list_item.xml in your case. This allows onItemClick() to be called.
What worked for me :
1) Adding android:descendantFocusability="blocksDescendants" to Relative Layout tag.
The result is shown below :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants" >
2) Adding android:focusable="false" to every element in in list_item.xml
example :
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:focusable="false" />
Once I had a similar problem. Every list item had a text view and a checkbox, and just because the checkbox, the whole listitem wasn't 'enabled' to fire the event. I solved it by making a little trick inside the adapter when I was getting the view.
Just before returning the view I put:
v.setOnClickListener(listener);
(The object listener is an onItemClickListener I gave to the Adapter's constructor).
But I have to tell you, the problem is because the platform, it is a bug.
I had the same problem and I tried to solve it by adding
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
to my item.xml but it still doesn't work !!! Infact I found the issue in the relative layout witch contains
android:focusableInTouchMode="true" android:focusable="true"
And when I removed it All things is ok
protected void onPostExecute(Void result) {
progressDialog.dismiss(); stLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
//add this
ListView lv = getListView(); lv.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
//do stuff
}
});
}

Categories

Resources