我该怎么办这个空指针异常?

时间:2011-10-08 05:02:05

标签: android listview android-linearlayout

public class Display extends ListActivity 
{
    private ForumAdapter faHelper;
    private ProgressDialog dialog;  
    private String Url;
    private int success = 0;

    private SeparatedListAdapter sAdapter;
    private ListView list;

    private List<Map<String,?>> cat_list;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setTitle("Board Index");

        list = (ListView) findViewById(R.id.dlist);
        list.setOnItemClickListener(itemclicklistener());

        setContentView(R.layout.displaylist);

        faHelper = new ForumAdapter(this);

        Url = geturl(savedInstanceState);

        if (faHelper.isGood(Url))
        {
            Load();
        }
        else
        {
            alertdialog(0);
        }
    }

    private class pbar extends AsyncTask<String, Void, Integer> 
    {
        private final String message = "Loading. Please wait...";

        @Override
        protected void onPreExecute() 
        {
            dialog = ProgressDialog.show(Display.this, "", message, true);
        }

        @Override
        protected void onPostExecute(Integer result) 
        {
            success = result;
            dialog.dismiss();
            displaystuff();
        }

        protected Integer doInBackground(String... url) 
        {
            return faHelper.SourceDownload(url[0]);
        }
    }

    private void displaystuff()
    {
        if (success == 1)
        {
            sAdapter = new SeparatedListAdapter(this, R.layout.demoheader);

            for (Object row : faHelper.BoardIndex)
            {
                String[][] theRow = (String[][])row;
                String ctitle = "";
                cat_list = new LinkedList<Map<String,?>>();

                for (int i = 0; i < theRow.length; i++)
                {
                    if (i == 0) ctitle = theRow[i][0];

                    /* + "\n" + theRow[i][2]*/
                    cat_list.add(createObject(theRow[i][1], theRow[i][3]));
                }

                ExAdapter exone = new ExAdapter(this, R.layout.demorow, cat_list);
                sAdapter.addSection(ctitle, exone);
            }
            list.setAdapter(sAdapter);
        }
        else
        {
            alertdialog(1);
        }
    }

    private OnItemClickListener itemclicklistener()
    {
        return new OnItemClickListener() 
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            {
                @SuppressWarnings("unchecked") // Object to Map.
                Map<String,?> one = (Map<String,?>) parent.getAdapter().getItem(position);
                Toast.makeText(getApplicationContext(), one.get("title").toString(), Toast.LENGTH_SHORT).show();
            }
        };
    }

    private void alertdialog(int which)
    {
        switch (which)
        {
        case 0:
            new AlertDialog.Builder(this)
            .setTitle("Alert")
            .setMessage("Connection Error!!!" + "\n\n" + faHelper.rstring)
            .setPositiveButton("OK", new OnClickListener() 
            {
                public void onClick(DialogInterface arg0, int arg1) 
                {
                    Display.this.finish();
                }
            })
            .show();
            break;
        case 1:
            new AlertDialog.Builder(this)
            .setTitle("Alert")
            .setMessage("Error!!" + "\n\n" + "Press OK to try again!")
            .setPositiveButton("OK", new OnClickListener() 
            {
                public void onClick(DialogInterface arg0, int arg1) 
                {
                    Load();
                }
            })
            .setPositiveButton("Cancel", new OnClickListener() 
            {
                public void onClick(DialogInterface arg0, int arg1) 
                {
                    success = 1;
                    Display.this.finish();
                }
            })
            .show();
            break;
        }
    }

    public Map<String,?> createObject(String title, String image) 
    {
        Map<String,String> item = new HashMap<String,String>();  
        item.put("title", title);
        item.put("image", image);
        return item;
    }

    public void refresh(View view)
    {
        Load();
    }

    private void Load()
    {
        new pbar().execute(Url);
    }

    private String geturl(Bundle savedInstanceState)
    {
        String url = (savedInstanceState == null) ? null : (String) savedInstanceState.getSerializable("URL");

        if (url == null) 
        {
            Bundle extras = getIntent().getExtras();
            url = extras != null ? extras.getString("URL") : null;
        }

        return url;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
        outState.putSerializable("URL", Url);
    }

    @Override
    protected void onPause() 
    {
        super.onPause();
    }

    @Override
    protected void onResume() 
    {
        super.onResume();
    }
}

这行代码是出于某种原因创建空指针异常,我不明白为什么。

list.setOnItemClickListener(itemclicklistener());

当我只是用代码创建一个listview时,它似乎工作得很好。但是当我实际上将它设置为linearlayout中的listview时,除了点击监听器之外,一切都很好。任何建议都会有所帮助。

xml如下:

displaylist.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:orientation="vertical">    

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button 
            android:onClick="refresh" 
            android:text="Refresh" 
            android:id="@+id/refresh" 
            android:layout_width="match_parent"
            android:layout_height="32dp">
        </Button>
    </LinearLayout>
    <ListView 
        android:id="@+id/dlist" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content">
        </ListView>
</LinearLayout>

header.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/demoheader_title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="2dip"
    android:paddingBottom="2dip"
    android:paddingLeft="5dip"
    android:background="#FFFFFF"
    style="?android:attr/listSeparatorTextViewStyle"
    />

row.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:width="50dp"
        android:height="50dp"
        android:scaleType="fitStart"
        android:paddingRight="5dp"
        />

    <TextView
        android:id="@+id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:singleLine="false"
        android:textAppearance="?android:attr/textAppearanceSmall"  
        />  
</LinearLayout>

3 个答案:

答案 0 :(得分:1)

setContentView(R.layout.something)在写了findviewbyid函数后把它放在第一位然后你就找不到这个空指针异常了

答案 1 :(得分:1)

如果您未使用ListView的机器人ID,则无法通过ListActivity扩展该类,您必须使用Activity扩展它。

如果你通过ListActivity扩展Class

,你应该使用Androids id
android:id="@android:id/list

但是如果您使用android:id="@+id/dlist",则必须使用Activity

扩展类

此外,您在获取ID

之前显示使用setContentView(R.layout.displaylist);
list = (ListView) findViewById(R.id.dlist);
        list.setOnItemClickListener(itemclicklistener());

答案 2 :(得分:0)

您需要在setContentView()之前调用findViewById(),否则它将返回null。修改您的代码,使其如下所示:

setContentView(R.layout.displaylist);

list = (ListView) findViewById(R.id.dlist);
list.setOnItemClickListener(itemclicklistener());