Android DismissDialog 的 IllegalArgumentException

发布于 2024-11-03 12:04:17 字数 9652 浏览 6 评论 0原文

我使用以下代码从我们的互联网下载一些文件。

public class SplashDownload extends Activity {

    public static final int PROGRESS_DIALOG = 0;
    private ProgressDialog mProgressDialog;
    private WordDataHelper wordDataHelper;
    private ExtraDataHelper extraDataHelper;

    // put your file path here
    private String filePath = "http://test.com/Assets/";
    // put your filename here
    private String fileName;
    // put your download directory name here
    private String downloadDir;

    private int wordCounter = 0, extraCounter = 0, counter = 1;

    private boolean wordDLOn = true;
    private int totalFileNo;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashdllayout);
        getDownloadList();
    }

    private void goForward() {

        Intent intent = new Intent().setClass(this, LangH.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    private void doNext() {

        if (wordDLOn) {

            System.out.print("wordDetails update: "
                    + wordDetails[wordCounter - 1][0]
                    + extraDetails[extraCounter][0] + fileName);
            wordDataHelper.updateDLStat(Long
                    .valueOf(wordDetails[wordCounter - 1][0]));
        } else {

            System.out.print("extraDetails update: "
                    + extraDetails[extraCounter - 1][0] + fileName);
            extraDataHelper.updateDLStat(Long
                    .valueOf(extraDetails[extraCounter - 1][0]));
        }

        if (wordCounter < wordDetails.length) {
            System.out.print("wordCounter: " + wordCounter + "/"
                    + wordDetails.length);
            startDownload(wordDetails[wordCounter][1]);
            wordCounter++;
        } else if (extraCounter < extraDetails.length) {
            wordDLOn = false;
            downloadDir = "LanH/extras";
            System.out.print("extraCounter: " + extraCounter + "/"
                    + extraDetails.length);
            startDownload(extraDetails[extraCounter][1]);
            extraCounter++;
        } else {
            goForward();
        }
    }

    private void getDownloadList() {

        // lessons download..........

        String[] wordDetails = {"1.mp4","2.mp4","3.mp4","4.mp4","5.mp4","6.mp4","7.mp4","8.mp4",};
        downloadDir = "LanH/words";


        String[] extraDetails = {"a.mp4","b.mp4","c.mp4","d.mp4","e.mp4","f.mp4","g.mp4","h.mp4",};


        totalFileNo = extraDetails.length + wordDetails.length;

        if (wordDetails.length != 0) {
            startDownload(wordDetails[wordCounter]);
            wordCounter++;
        } else if (extraDetails.length != 0) {
            wordDLOn = false;
            startDownload(extraDetails[extraCounter]);
            extraCounter++;
        } else {
            goForward();
        }

    }

    private void startDownload(String dlFilename) {
        // tv = (TextView) findViewById(R.id.tv1);
        fileName = dlFilename;
        System.out.print("fileName: " + fileName);

        File dir = new File(android.os.Environment
                .getExternalStorageDirectory().getAbsolutePath()
                + "/"
                + downloadDir);
        // creates the directory if it doesn't exists
        if (dir.exists() == false) {
            dir.mkdirs();
        }
        dir = null;

        if (checkNet()) {
            if (checkExternalMedia() == true) {
                String url = filePath + fileName;
                new DownloadFileAsync().execute(url, fileName);
                mProgressDialog.setMessage("Downloading file.." + fileName);
            } else {
                Toast.makeText(getApplicationContext(),
                        "External Media is NOT readable/writable",
                        Toast.LENGTH_SHORT).show();
            }
        } else {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("No Internet Connectivity. Check the connection and retry the app.")
                    .setCancelable(false)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int id) {
                            finish();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }


    /** Method to check whether external media available and writable. */
    private boolean checkExternalMedia() {
        boolean stat;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // Can read and write the media
            stat = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // Can only read the media
            stat = false;
        } else {
            // Can't read or write
            stat = false;
        }
        return stat;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case PROGRESS_DIALOG:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file.." + fileName);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(PROGRESS_DIALOG);
        }

        @Override
        protected String doInBackground(String... aurl) {
            int count;

            try {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("DOWNLOAD_TEST", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(
                        android.os.Environment.getExternalStorageDirectory()
                                + "/" + downloadDir + "/" + aurl[1]);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("DOWNLOAD_TEST", progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) { 

            dismissDialog(PROGRESS_DIALOG);

            // tv.append("\n\nFile Download Complete!");
            // Button btn = (Button) findViewById(R.id.btn1);
            // btn.setVisibility(View.GONE);

            // you can call a second intent here to redirect to another screen
            doNext();
        }
    }

    private boolean checkNet() {
        boolean connected = false;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState() == NetworkInfo.State.CONNECTED
                || connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            // we are connected to a network
            connected = true;
        } else
            connected = false;
        return connected;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}

该过程运行良好。据报道,崩溃报告如下:

java.lang.IllegalArgumentException: no dialog with id 0 was ever shown via Activity#showDialog
at android.app.Activity.missingDialog(Activity.java:2663)
at android.app.Activity.dismissDialog(Activity.java:2648)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:264)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

我的代码有什么问题?在 dismissDialog 解决问题之前检查 isShowing() 吗?

I have used following code for download some files from our internet.

public class SplashDownload extends Activity {

    public static final int PROGRESS_DIALOG = 0;
    private ProgressDialog mProgressDialog;
    private WordDataHelper wordDataHelper;
    private ExtraDataHelper extraDataHelper;

    // put your file path here
    private String filePath = "http://test.com/Assets/";
    // put your filename here
    private String fileName;
    // put your download directory name here
    private String downloadDir;

    private int wordCounter = 0, extraCounter = 0, counter = 1;

    private boolean wordDLOn = true;
    private int totalFileNo;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashdllayout);
        getDownloadList();
    }

    private void goForward() {

        Intent intent = new Intent().setClass(this, LangH.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    private void doNext() {

        if (wordDLOn) {

            System.out.print("wordDetails update: "
                    + wordDetails[wordCounter - 1][0]
                    + extraDetails[extraCounter][0] + fileName);
            wordDataHelper.updateDLStat(Long
                    .valueOf(wordDetails[wordCounter - 1][0]));
        } else {

            System.out.print("extraDetails update: "
                    + extraDetails[extraCounter - 1][0] + fileName);
            extraDataHelper.updateDLStat(Long
                    .valueOf(extraDetails[extraCounter - 1][0]));
        }

        if (wordCounter < wordDetails.length) {
            System.out.print("wordCounter: " + wordCounter + "/"
                    + wordDetails.length);
            startDownload(wordDetails[wordCounter][1]);
            wordCounter++;
        } else if (extraCounter < extraDetails.length) {
            wordDLOn = false;
            downloadDir = "LanH/extras";
            System.out.print("extraCounter: " + extraCounter + "/"
                    + extraDetails.length);
            startDownload(extraDetails[extraCounter][1]);
            extraCounter++;
        } else {
            goForward();
        }
    }

    private void getDownloadList() {

        // lessons download..........

        String[] wordDetails = {"1.mp4","2.mp4","3.mp4","4.mp4","5.mp4","6.mp4","7.mp4","8.mp4",};
        downloadDir = "LanH/words";


        String[] extraDetails = {"a.mp4","b.mp4","c.mp4","d.mp4","e.mp4","f.mp4","g.mp4","h.mp4",};


        totalFileNo = extraDetails.length + wordDetails.length;

        if (wordDetails.length != 0) {
            startDownload(wordDetails[wordCounter]);
            wordCounter++;
        } else if (extraDetails.length != 0) {
            wordDLOn = false;
            startDownload(extraDetails[extraCounter]);
            extraCounter++;
        } else {
            goForward();
        }

    }

    private void startDownload(String dlFilename) {
        // tv = (TextView) findViewById(R.id.tv1);
        fileName = dlFilename;
        System.out.print("fileName: " + fileName);

        File dir = new File(android.os.Environment
                .getExternalStorageDirectory().getAbsolutePath()
                + "/"
                + downloadDir);
        // creates the directory if it doesn't exists
        if (dir.exists() == false) {
            dir.mkdirs();
        }
        dir = null;

        if (checkNet()) {
            if (checkExternalMedia() == true) {
                String url = filePath + fileName;
                new DownloadFileAsync().execute(url, fileName);
                mProgressDialog.setMessage("Downloading file.." + fileName);
            } else {
                Toast.makeText(getApplicationContext(),
                        "External Media is NOT readable/writable",
                        Toast.LENGTH_SHORT).show();
            }
        } else {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("No Internet Connectivity. Check the connection and retry the app.")
                    .setCancelable(false)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int id) {
                            finish();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }


    /** Method to check whether external media available and writable. */
    private boolean checkExternalMedia() {
        boolean stat;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // Can read and write the media
            stat = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // Can only read the media
            stat = false;
        } else {
            // Can't read or write
            stat = false;
        }
        return stat;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case PROGRESS_DIALOG:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file.." + fileName);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(PROGRESS_DIALOG);
        }

        @Override
        protected String doInBackground(String... aurl) {
            int count;

            try {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("DOWNLOAD_TEST", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(
                        android.os.Environment.getExternalStorageDirectory()
                                + "/" + downloadDir + "/" + aurl[1]);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("DOWNLOAD_TEST", progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) { 

            dismissDialog(PROGRESS_DIALOG);

            // tv.append("\n\nFile Download Complete!");
            // Button btn = (Button) findViewById(R.id.btn1);
            // btn.setVisibility(View.GONE);

            // you can call a second intent here to redirect to another screen
            doNext();
        }
    }

    private boolean checkNet() {
        boolean connected = false;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState() == NetworkInfo.State.CONNECTED
                || connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            // we are connected to a network
            connected = true;
        } else
            connected = false;
        return connected;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}

The process is running fine. It is reported following crash report:

java.lang.IllegalArgumentException: no dialog with id 0 was ever shown via Activity#showDialog
at android.app.Activity.missingDialog(Activity.java:2663)
at android.app.Activity.dismissDialog(Activity.java:2648)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:264)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

What is the problem in my code? Is isShowing() check before dismissDialog will solve the prob?

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

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

发布评论

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

评论(3

ま昔日黯然 2024-11-10 12:04:17

你的进度对话框真的显示了吗?
您可以尝试使用 removeDialog(PROGRESS_DIALOG); 来清理它,而不是忽略它。

Does your progress dialog actually show up?
Instead of dismissing it you could try using removeDialog(PROGRESS_DIALOG); to have it cleaned up.

失退 2024-11-10 12:04:17

当您执行此操作

mProgressDialog.show();

时,

protected Dialog onCreateDialog(int id)

您已经将对话框的 ID 设置为某个随机值或空值。
因此,当您打电话取消它时,应用程序会认为您疯了。

When you do the

mProgressDialog.show();

during

protected Dialog onCreateDialog(int id)

you already set the ID for the Dialog to some random or null value.
So when you call to dismiss it, the Application thinks you are crazy.

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