ListView yielding nullpointerexception on setOnItemClickListener

断了今生、忘了曾经 提交于 2019-12-02 11:25:33

问题


I'm attempting to work with through some tutorial code and add in an OnItemClick Listener, but keep throwing an exception when it hits the listener and crashing my app. This is my first attempt at working in the Android environment, so I'm trying to learn how all these things are interrelated.

Here's what I've tried:

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;


public class RssActivity extends ListActivity{

private RssListAdapter adapter;

private OnItemClickListener newsSelectListener = new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            AlertDialog.Builder alert=new AlertDialog.Builder(RssActivity.this);
            alert.setTitle("Clicked").setMessage("Item clicked").setNeutralButton("OK", null).show();

        }
    };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    List<JSONObject> jobs = new ArrayList<JSONObject>();
    try {
        jobs = RssReader.getLatestRssFeed();
    } catch (Exception e) {
        Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
    }   

    adapter = new RssListAdapter(this,jobs);
    setListAdapter(adapter);

    ListView lv = (ListView)findViewById(R.id.list);
    lv.setOnItemClickListener(newsSelectListener);

    }
}       

I also tried to changing setListAdapter to lv.setListAdapter, but that's doesn't appear to be a valid statement.

What am I missing?


回答1:


ListActivity doesn't require you to assign a layout via setContentView() that is if you want to show only a list but if you add a another view, your ListView should contain the android:id attribute set to @android:id/list like this xml below

<ListView
  android:id="@android:id/list"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" >
</ListView>

try changing your code

ListView lv = (ListView)findViewById(R.id.list);

to this

ListView lv = getListView();
lv.setOnItemClickListener(newsSelectListener);



回答2:


I am not sure your code will work

private OnItemClickListener newsSelectListener = new OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AlertDialog.Builder alert=new AlertDialog.Builder(RssActivity.this);
        alert.setTitle("Clicked").setMessage("Item clicked").setNeutralButton("OK", null).show();

    }
};

But in my opinion, I often add setOnClickListener() to convertView in getView method in Adapter class

public View getView(final int position, View convertView, ViewGroup parent) {
......................
convertView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Do Somethings in here
                }
            }
        });



回答3:


I cannot see where you have initialized your layout...so:

Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).

The onCreate(Bundle) method initializes your Activity. It is where you usually call setContentView(int) with your xml layout(main.xml or your xml which defines your UI). Place it after super.onCreate(..)


With regards with this exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{}:

check your AndroidManifest.xml if your Activity is already in there:

<activity android:name=".<ActivityName>" 
          android:label="@string/app_name">
</activity>

If your problem has not been resolved, make use of your Logcat and put Log.d in your methods to see where it's crashing.




回答4:


EDIT

Ok - and where are you setting setContentView(...)? The lv

ListView lv = (ListView) findViewById(R.id.list);

is null because you didn't set contentView.


Probably the reason for this is: you're setting OnClickListener to null in AlertDialog.Builder in setNeutralButton("OK", null).

So when you click "OK" Android invokes (internally) something like this:

neutralButtonListener.onClick(...);

And the neutralButtonListener is null. So you should just provide empty listener at least.



来源:https://stackoverflow.com/questions/10841929/listview-yielding-nullpointerexception-on-setonitemclicklistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!