ArrayList不断填充相同的数据

时间:2012-07-13 12:12:25

标签: android json arraylist android-alertdialog

我有一个非常奇怪的问题。我有一些数据,我在对话框中显示。如果我关闭应用程序并再次重新打开它,我的ArrayList将再次添加原始数据(前5个条目 - >关闭&重新打开 - > 10个条目 - >关闭&重新打开 - > 15个条目等。) / p>

这是我将数据解析到ArrayList的方式(这只在我的TabHost中发生一次):

JSONArray jPDFs = json.getJSONArray("pdfs");
            for (int i = 0; i < jPDFs.length(); i++) {
                JSONObject c3 = jPDFs.getJSONObject(i);

                String pdf_title = c3.getString("title");
                String pdf_url = c3.getString("url");

                pdfListTitle.add(pdf_title);
                pdfListTitle2.add(pdf_title);
                pdfListURL.add(pdf_url);
            }

这是我的代码,我在其中显示带有解析数据的对话框:

public void showDialog() {
    items = null; // have tried with and without...
    builder = null; // have tried with and without...

    builder = new AlertDialog.Builder(this);
    Log.e(TabHost.LOG_TAG, "pdfListTitle=" + TabHost.pdfListTitle.size()); // this always hops from 5 -> 10 -> 15 on every reopen (without killing the app with a taskkiller...)

    items = TabHost.pdfListTitle.toArray(new CharSequence[TabHost.pdfListTitle.size()]);

    builder.setTitle(R.string.choose_document);
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            WebView wv = (WebView) findViewById(R.id.webviewpdf);
            wv.setWebViewClient(new WebViewClient());
            wv.getSettings().setJavaScriptEnabled(true);
            wv.getSettings().setBuiltInZoomControls(true);
            wv.loadUrl("http://docs.google.com/gview?embedded=true&url="
                    + TabHost.pdfListURL.get(item));
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

非常感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

我认为你在 TabHost 中将 pdfListTitle 视为静态,这可能是个问题

pdfListTitle 应在每次活动调用时初始化

例如,您可以像{/ 1>这样的onCreate()方法编写此代码

ArrayList<T> pdfListTitle;

protected void onCreate(Bundle savedInstanceState) {

  pdfListTitle = new ArrayList<T>; <----

}

答案 1 :(得分:1)

我想在方法TabHost.pdfListTitle.toArray(..)中,您应该每次重置填充数据的列表。

答案 2 :(得分:0)

简单而天真的解决方法是添加

pdfListTitle.clear()

在用数据填充列表之前

但这不会解决每次显示对话框时调用该方法的问题,除非您需要它。

答案 3 :(得分:0)

正如以前的用户所说,你应该手动清理你的清单(pdfListTitle.clear()),但深入了解问题是有用的。

正如我所看到的,你将pdfListTitle作为静态字段存储在你的TabHost类中(顺便说一句,使用像TabHost这样的名称并不是很好,因为android API中有TabHost {{3}当加载类时,静态字段首先被初始化。并且当Android系统正好卸载这些类时没有任何保证,因为在android中没有&#34;关闭&#34;应用程序。它&#39; ;阅读有关Java中的类加载器(您可以非常简单地了解它)。