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

发布于 2024-12-08 18:54:13 字数 7608 浏览 1 评论 0原文

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

当我只是用代码创建一个列表视图时,它似乎工作得很好。但是当我实际将其设置为线性布局内的列表视图时,除了单击侦听器之外,一切都很好。任何建议都会有帮助。

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

this line of code is for some reason creating a null pointer exception, and i have no idea why.

list.setOnItemClickListener(itemclicklistener());

when i just simply create a listview with code, it seems to work just fine. but when im actually setting it to be a listview inside a linearlayout, everything is fine except for the click listener. any advice would be help full.

the xml's are as follows:

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

永言不败 2024-12-15 18:54:13

setContentView(R.layout.something) 在写findviewbyid函数之后先把它放在上面然后你就不会发现这个空指针异常

setContentView(R.layout.something) put this first after write findviewbyid function then you will not find this null pointer exception

橙味迷妹 2024-12-15 18:54:13

如果您没有为 ListView 使用 androids id,则无法通过 ListActivity 扩展该类,您必须使用 Activity 来扩展它。

如果您通过 ListActivity 扩展类,则应该使用 Android id

android:id="@android:id/list

但是如果您使用 android:id="@+id/dlist" 那么您必须使用 Activity 扩展类

另外您还显示使用 setContentView (R.layout.displaylist); 在获取 id 之前

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

If you are not using androids id for ListView you cannot extends the class by ListActivity you have to extend it with Activity.

You should use Androids id if you extend Class by ListActivity

android:id="@android:id/list

But if you are using android:id="@+id/dlist" then you have to extend class with Activity

Also you show use setContentView(R.layout.displaylist); before fetching the id

list = (ListView) findViewById(R.id.dlist);
        list.setOnItemClickListener(itemclicklistener());
烂柯人 2024-12-15 18:54:13

您需要在 findViewById() 之前调用 setContentView(),否则将返回 null。修改您的代码,使其看起来像这样:

setContentView(R.layout.displaylist);

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

You need to call setContentView() before findViewById() or it will return null. Modify your code so it looks like this:

setContentView(R.layout.displaylist);

list = (ListView) findViewById(R.id.dlist);
list.setOnItemClickListener(itemclicklistener());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文