setOnItemClickListener产生NullPoin

setOnItemClickListener产生NullPoin

本文介绍了ListView控件上setOnItemClickListener产生NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过一些教程code一起工作,并添加在OnItemClick监听器,但要当它击中听者抛出一个异常,并撞毁我的应用程序。这是我在Android环境中工作的第一次尝试,所以我想学习这些东西是如何相互关联的。

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.

下面是我已经试过:

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);

    }
}

我也试图改变setListAdapter到lv.setListAdapter,但是这似乎并没有成为一个有效的语句。

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

我在想什么?

推荐答案

ListActivity不要求你指定通过的setContentView()也就是说如果您想布局显示的列表,但如果添加了另一种观点认为,你的ListView应该包含机器人:ID 属性设置为 @机器人:ID /列表这样的XML低于

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>

试着改变你的code

try changing your code

的ListView LV =(ListView控件)findViewById(R.id.list);

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

这篇关于ListView控件上setOnItemClickListener产生NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:07