Android:AsyncTask停止ArrayList填充和显示后刷新ListView

时间:2014-02-03 22:20:39

标签: java android listview arraylist android-asynctask

在下面的代码中,displayList()方法负责使用数据库表中的内容填充ArrayList,具体取决于查看的目的,然后在ListView中显示。

但是,第一次运行新版本的数据库或第一次运行该程序时,当创建一个新的Database Manipulator类实例(在本例中为ManipulateDatabase)时,AsyncTask运行到将初步数据导入数据库,这会中断正在填充的ArrayList并显示ListView。因此,在AsyncTask完成后,ListView显示为空。

我的问题是,如何解决问题,以便在AsyncTask完成后,ListView会显示正确的内容?我非常感谢有用的回应。

相关代码如下所示。

displayList()

private void displayList() {
        try {
            System.out.println("DISPLAYING HERE");
            md = new ManipulateDatabase(this, new ProgressDialog(this));
            if (purpose.equals("ViewNovel")) {
                setTitle("Novels");
                listContents = md.getPieces("0");
                System.out.println(purpose);
            } else if (purpose.equals("TestNovel")) {
                setTitle("Novels");
                listContents = md.getPieces("0");
                System.out.println(purpose);

            } else if (purpose.equals("TestPlay")) {
                setTitle("Plays");
                listContents = md.getPieces("1");
                System.out.println(purpose);

            } else if (purpose.equals("ViewPlay")) {
                setTitle("Plays");
                listContents = md.getPieces("1");
                System.out.println(purpose);
            } else if (purpose.equals("ViewStats")) {
                setTitle("Statistics");
                listContents = md.getPieces("0");
                listContents.addAll(md.getPieces("1"));
                System.out.println(purpose);
            } else if (purpose.endsWith("/Char")) {
                int point = purpose.indexOf("/");
                String rest = purpose.substring(point + 1, purpose.length());
                point = rest.indexOf("/");
                String title = rest.substring(0, point);
                listContents = md.getElements(title, "1", "");
                setTitle(title + " - Characters");
                System.out
                        .println("Tried to get Char elements and put in array");
                System.out.println(purpose);

            }

            else if (purpose.endsWith("/Theme")) {
                int point = purpose.indexOf("/");
                String rest = purpose.substring(point + 1, purpose.length());
                point = rest.indexOf("/");
                String title = rest.substring(0, point);
                listContents = md.getElements(title, "0", "");
                setTitle(title + " - Themes");
                System.out.println(purpose);

            } else if (purpose.contains("*")) {

                System.out.println("Trying to get quotes here guys!");

                int lastSlash = purpose.lastIndexOf("*");
                String extract = purpose.substring(lastSlash + 1,
                        purpose.length());
                System.out.println(extract);
                listContents.clear();
                listContents = md.getQuotes(extract);
                setTitle("Quotes");

            } else if (purpose.contains("/Char/")
                    || purpose.contains("/Theme/")) {
                int lastSlash = purpose.lastIndexOf("/");
                String extract = purpose.substring(lastSlash + 1,
                        purpose.length());
                System.out.println(purpose);
                listContents = md.getPoints(extract, "");
                setTitle(extract);

            }

        } catch (IOException e) {
            System.out.println("Could not create new MD object");
            e.printStackTrace();
        }

        setContentView(R.layout.genlist_layout);
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, listContents));
    }

AsyncTask

private class ImportLitData extends AsyncTask<String, Void, Boolean> {

        /**
         * ProgressDialog in which progress is shown
         */
        private ProgressDialog progressDialog;
        /**
         * Context of class from which the TXTs will need to be imported -
         * Context of the AsyncTask
         */
        private Activity context;

        /**
         * Boolean to store whether import of data from text file was successful
         * or not
         */

        private Boolean success;

        /**
         * Constructor method
         * 
         * @param dialogIn
         *            Progress Dialog which will be updated
         * @param contextIn
         *            context of Class
         */
        public ImportLitData(ProgressDialog dialogIn, Activity contextIn) {
            // progressDialog = dialogIn;
            context = contextIn;
            setUpDialog();
        }

        /**
         * Sets up the download progress dialog
         */
        private void setUpDialog() {
            progressDialog = new ProgressDialog(context);
            progressDialog.setMessage("Importing initial data");
            progressDialog.setIndeterminate(true);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            // progressDialog.show();
        }

        protected Boolean doInBackground(String... params) {
            System.out.println("do in background!");
            BufferedReader pieceScan;
            BufferedReader specificScan;
            BufferedReader elementScan;
            BufferedReader quoteScan;
            try {
                pieceScan = new BufferedReader(new InputStreamReader(
                        getPieceTextFile(context), "UTF-8"));
                specificScan = new BufferedReader(new InputStreamReader(
                        getSpecificTextFile(context), "UTF-8"));
                elementScan = new BufferedReader(new InputStreamReader(
                        getElementTextFile(context), "UTF-8"));
                quoteScan = new BufferedReader(new InputStreamReader(
                        getQuoteTextFile(context), "UTF-8"));

                openSesame();
                String line;
                String pieceName;
                String isDrama;
                String point;
                String element;
                String quote;
                String isCharacter;
                int commaPoint;
                int commaPoint2;

                System.out.println("INITIAL LAUNCH BLOCK INITIATED");
                while ((line = pieceScan.readLine()) != null) {
                    System.out.println("PieceInsertion: ");
                    commaPoint = line.indexOf(",");
                    pieceName = line.substring(0, commaPoint);
                    isDrama = line.substring(commaPoint + 1, commaPoint + 2);
                    ContentValues pv = new ContentValues();
                    pv.put(pieceField, pieceName);
                    pv.put(typeField, (Integer.parseInt(isDrama)));
                    dataBase.insert(pieceTable, null, pv);
                    System.out.println(line
                            + ": INSERTION SHOULD HAVE JUST FINISHED");
                }

                while ((line = specificScan.readLine()) != null) {
                    System.out.println("SpecificInsertion: ");
                    commaPoint = line.indexOf(",");
                    point = line.substring(0, commaPoint);
                    commaPoint2 = (line.substring(commaPoint + 1,
                            line.length() - 1).indexOf(",")) + point.length();
                    // pieceName = line.substring(commaPoint + 1,
                    // commaPoint2 +
                    // 1);
                    element = line.substring(commaPoint2 + 2, line.length());

                    ContentValues sv = new ContentValues();
                    sv.put(pointField, point);
                    // sv.put(pieceField, pieceName);
                    sv.put(elementField, element);
                    dataBase.insert(specificTable, null, sv);
                    System.out.println(line
                            + ": INSERTION SHOULD HAVE JUST FINISHED");
                }

                while ((line = elementScan.readLine()) != null) {
                    commaPoint = line.indexOf(",");
                    element = line.substring(0, commaPoint);
                    commaPoint2 = (line.substring(commaPoint + 1,
                            line.length() - 1).indexOf(",")) + element.length();

                    pieceName = line.substring(commaPoint + 1, commaPoint2 + 1);
                    isCharacter = line.substring(commaPoint2 + 2,
                            commaPoint2 + 3);

                    ContentValues ev = new ContentValues();
                    ev.put(elementField, element);
                    ev.put(pieceField, pieceName);
                    ev.put(elTypeField, (Integer.parseInt(isCharacter)));
                    dataBase.insert(elementTable, null, ev);
                    System.out.println(line
                            + ": INSERTION SHOULD HAVE JUST FINISHED");

                }

                while ((line = quoteScan.readLine()) != null) {
                    commaPoint = line.indexOf("^");
                    quote = line.substring(0, commaPoint);
                    System.out.println("Quote = " + quote);
                    point = line.substring(commaPoint + 1, line.length());
                    System.out.println("Point = " + point);

                    ContentValues qv = new ContentValues();
                    qv.put(quoteField, quote);
                    qv.put(pointField, point);
                    dataBase.insert(quoteTable, null, qv);
                    System.out.println(line
                            + ": INSERTION SHOULD HAVE JUST FINISHED");
                }

                success = true;

            } catch (UnsupportedEncodingException e) {
                System.out.println("Unsupported Encoding Exception!");
                e.printStackTrace();
                success = false;
            } catch (IOException e) {
                System.out.println("IO Exception!");
                e.printStackTrace();
                success = false;
            }

            return success;

        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            System.out.println("onPostExecute");
            progressDialog.cancel();

            String toastMessage = (result) ? "Imported" : "Import Failed";
            Toast resultOut = Toast.makeText(context.getApplicationContext(),
                    toastMessage, Toast.LENGTH_LONG);
            resultOut.show();
        }

        /**
         * Method called before doInBackground is executed
         * 
         * @override
         */
        protected void onPreExecute() {
            super.onPreExecute();
            System.out.println("onPreExecute");
            /* Dialog shown */
            progressDialog.show();

        }

    }

修改 * 我现在已将以下方法添加到GenList类(负责ListView的类) *

public void refreshList() {
        runOnUiThread(new Runnable() {
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

现在我在onPostExecute中调用该方法

protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            System.out.println("onPostExecute");
            progressDialog.cancel();

            String toastMessage = (result) ? "Imported" : "Import Failed";
            Toast resultOut = Toast.makeText(context.getApplicationContext(),
                    toastMessage, Toast.LENGTH_LONG);
            resultOut.show();
            genericList.refreshList();
        }

* 但我遇到此错误,显示在LogCat输出*

02-06 20:10:54.723: E/AndroidRuntime(607): FATAL EXCEPTION: main
02-06 20:10:54.723: E/AndroidRuntime(607): java.lang.NullPointerException
02-06 20:10:54.723: E/AndroidRuntime(607):  at com.lawson.englishlitrevision.GenList$1.run(GenList.java:312)
02-06 20:10:54.723: E/AndroidRuntime(607):  at android.os.Handler.handleCallback(Handler.java:605)
02-06 20:10:54.723: E/AndroidRuntime(607):  at android.os.Handler.dispatchMessage(Handler.java:92)
02-06 20:10:54.723: E/AndroidRuntime(607):  at android.os.Looper.loop(Looper.java:137)
02-06 20:10:54.723: E/AndroidRuntime(607):  at android.app.ActivityThread.main(ActivityThread.java:4424)
02-06 20:10:54.723: E/AndroidRuntime(607):  at java.lang.reflect.Method.invokeNative(Native Method)
02-06 20:10:54.723: E/AndroidRuntime(607):  at java.lang.reflect.Method.invoke(Method.java:511)
02-06 20:10:54.723: E/AndroidRuntime(607):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-06 20:10:54.723: E/AndroidRuntime(607):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-06 20:10:54.723: E/AndroidRuntime(607):  at dalvik.system.NativeStart.main(Native Method)

任何建议为什么会受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

因此,您需要对列表视图进行notifyDataSetChanged调用。这样做有几种选择。您可以将listview传递给AsyncTask的构造函数,然后直接在onPostExecute中调用它,或者您可以在您的activity中创建一个“refreshList”方法(在listview上调用notifyDataSetChanged),并在onPostExecute中调用该方法。我更喜欢后者,因为它允许你做出你想做的其他改变。

请注意,如果您在活动中创建了一个方法,那么您需要更改构造函数以专门接受该活动以便能够对其进行调用,常规Activity不会知道该方法。